var Pb = Pb ||
{};
/**
* Portalbuilder Pb.BackOffice namespace and functions.
* @author msalla
* @requires jquery
* @requires jquery.hotkeys
* @requires jquery.url
* @requires jquery.json
* @requires Pb
* @requires Pb.Constants
* @requires Pb.Utils
* @namespace Pb.BackOffice
*/
(function() {
    if (window.jQuery) {
        (function($) {
            var TBackOffice = function() {
                /**
                * In the future we should namespace more carefully this functions.
                * @namespace Pb.BackOffice
                * @author msalla
                */
                function BackOffice() {
                }
                BackOffice.prototype = {
                    // OK to declare value types in the prototype
                    // BackOffice global class vars are prototype fields
                    EIPOnlineMode: true,
                    _backOfficeBindingHost: undefined,
                    _backOfficeBindingRequested: false,
                    /**
                    * Sets the value of an internal property to cache the result of the
                    * getBackOfficeBindingHost and avoid multiple service calls. This
                    * function is used inside the callback function to set the value of the
                    * BackOfficeBindingHost.
                    * @param {Object} aBackOfficeBindingHost
                    */
                    setBackOfficeBindingHost: function(aBackOfficeBindingHost) {
                        // The service call must be sinchronous not asynchronous
                        this._backOfficeBindingHost = aBackOfficeBindingHost;
                        this._backOfficeBindingRequested = true;
                    },
                    /**
                    * Gets the backoffice binding host.
                    * @return The backoffice binding host.
                    * @type String
                    */
                    getBackOfficeBindingHost: function() {
                        if ((!this._backOfficeBindingHost) && !this._backOfficeBindingRequested) {
                            var lCallbackFunction = function getBackOfficeBindingHostCallback(data, responseStatus) {
                                Pb.BackOffice.setBackOfficeBindingHost.apply(Pb.BackOffice, [data.d]);
                            };
                            // Call to server service to get the backoffice binding
                            var lErrorFunction = function(XMLHttpRequest, textStatus, errorThrown) {
                                alert("Error getting backoffice binding. " + $.secureEvalJSON(XMLHttpRequest.responseText).Message);
                            };
                            $.ajax({
                                async: false,
                                type: "POST",
                                url: Pb.Constants.BackOffice.ServiceUrl + "/GetBackOfficeBindingHost?pbl=" + utils.url.get_PageLang(),
                                // This is necessary for IIS6 and ASP.Net Web Service Call to work
                                data: "{}",
                                success: lCallbackFunction,
                                contentType: "application/json; charset=utf-8",
                                dataType: "json",
                                error: lErrorFunction
                            });
                        }
                        return this._backOfficeBindingHost;
                    },
                    /**
                    * Checks if the current hosts is the backofficeBindingHost.
                    * @returns if the current hosts is the backofficeBindingHost.
                    * @type Boolean
                    */
                    isCurrentHostBackOfficeBindingHost: function() {
                        var lCurrentHost = jQuery.url.attr("host").toLowerCase();
                        var lBackOfficeBindingHost = this.getBackOfficeBindingHost();
                        return lCurrentHost == lBackOfficeBindingHost;
                    },
                    /**
                    * Enables the ctrl + shift + e hotkey to enter InPlace Editing and the ctrl + shift + b
                    * to access to the backoffice.
                    * @return
                    * @type void;
                    */
                    enableBackOfficeHotKey: function() {
                        jQuery(document).bind('keydown', 'ctrl+shift+e', function(evt) {
                            if (!Pb.BackOffice.isCurrentHostBackOfficeBindingHost()) {
                                var lCurrentUrlAsBackOfficeUrl = jQuery.url.attr("protocol") + "://" +
                    Pb.BackOffice.getBackOfficeBindingHost() +
                    (jQuery.url.attr("port") ? jQuery.url.attr("port") : "") +
                    jQuery.url.attr("relative");
                                document.location = lCurrentUrlAsBackOfficeUrl;
                                return true;
                            }
                        });
                        jQuery(document).bind('keydown', 'ctrl+shift+b', function(evt) {
                            var lCurrentUrlAsBackOfficeUrl = jQuery.url.attr("protocol") + "://" +
                Pb.BackOffice.getBackOfficeBindingHost() +
                (jQuery.url.attr("port") ? jQuery.url.attr("port") : "") +
                Pb.Constants.BackOffice.BackOfficeHomeUrl;
                            document.location = lCurrentUrlAsBackOfficeUrl;
                            return true;
                        });
                    },
                    /**
                    * Move a list of multivalue content rows below or before another target row position. All rows are identified using
                    * its RowId. All RowId's must be from the provided aContentVersionId.
                    * @param {Guid} aContentVersionId - The content version id.
                    * @param {Guid[]} aRowIdsToMove - The list of row id's.
                    * @param {Guid} aTargetRowId - The target row id to move the rows to.
                    * @param {boolean} aBelow - Flag indicating if the rows must be moved below or before the target row position.
                    * @return - True if everything went fine.
                    * @type {boolean}
                    */
                    moveMultiValueRowsToRowPosition: function(aContentVersionId, aRowIdsToMove, aTargetRowId, aBelow, aTakeOwnership, aSuccessFunc, aErrFunc) {
                        var params = $.compactJSON({
                            'aOnline': this.EIPOnlineMode,
                            'aContentVersionId': aContentVersionId,
                            'aRowsToMoveIdList': aRowIdsToMove,
                            'aTargetRowId': aTargetRowId,
                            'below': aBelow,
                            'aTakeOwnership': aTakeOwnership
                        });
                        var lAjaxResult;
                        $.ajax({
                            async: true,
                            type: 'POST',
                            url: Pb.Constants.BackOffice.EipServiceUrl + '/MoveEIPContentVersionPropertyRows?pbl=' + utils.url.get_PageLang(),
                            contentType: 'application/json; charset=utf-8',
                            dataType: 'json',
                            data: params,
                            success: aSuccessFunc,
                            error: aErrFunc ? aErrFunc : function(XMLHttpRequest, textStatus, errorThrown) {
                                try {
                                    alert($.evalJSON(XMLHttpRequest.responseText).Message);
                                }
                                catch (ex) {
                                    alert(ex.message);
                                }
                            }
                        });
                    },
                    /**
                    * Move a list of multivalue content rows below or before a numerical target position. All rows are identified using
                    * its RowId. All RowId's must be from the provided aContentVersionId.
                    * @param {Guid} aContentVersionId - The content version id.
                    * @param {Guid[]} aRowIdsToMove - The list of row id's.
                    * @param {int} aTargetPosition - The target position to move the rows to.
                    * @param {boolean} aBelow - Flag indicating if the rows must be moved below or before the target position.
                    * @return - True if everything went fine.
                    * @type {boolean}
                    */
                    moveMultiValueRowsToPosition: function(aContentVersionId, aRowIdsToMove, aTargetPosition, aBelow) {
                        var params = $.compactJSON({
                            'aOnline': this.EIPOnlineMode,
                            'aContentVersionId': aContentVersionId,
                            'aRowsToMoveIdList': aRowIdsToMove,
                            'aPosition': aTargetPosition
                        });
                        var lAjaxResult;
                        $.ajax({
                            async: false,
                            type: 'POST',
                            url: Pb.Constants.BackOffice.EipServiceUrl + '/MoveEIPContentVersionPropertyRowsToPosition?pbl=' + utils.url.get_PageLang(),
                            contentType: 'application/json; charset=utf-8',
                            dataType: 'json',
                            data: params,
                            success: function() {
                                lAjaxResult = true;
                            },
                            error: function(XMLHttpRequest, textStatus, errorThrown) {
                                try {
                                    alert($.evalJSON(XMLHttpRequest.responseText).Message);
                                }
                                catch (ex) {
                                    alert(ex.message);
                                }
                                lAjaxResult = false;
                            }
                        });
                        return lAjaxResult;
                    },
                    /**
                    * Creates a new multivalue content row below or before another target row position. The target RowId must
                    * be from the provided aContentVersionId. The new multivalue content row will be created using the content
                    * definition default values.
                    * @param {Guid} aContentVersionId - The content version id.
                    * @param {Guid} aTargetRowId - The target row id to move the rows to.
                    * @param {boolean} aBelow - Flag indicating if the rows must be moved below or before the target row position.
                    * @return - True if everything went fine.
                    * @type {boolean}
                    */
                    insertMultiValueRowAtPosition: function(aContentVersionId, aTargetRowId, aBelow, aSuccessFunc, aErrFunc, aPropertyValues) {
                        var params = $.compactJSON({
                            'aOnline': this.EIPOnlineMode,
                            'aContentVersionId': aContentVersionId,
                            'aTargetRowId': aTargetRowId,
                            'below': aBelow,
                            'aPropertyValues': aPropertyValues
                        });
                        var lAjaxResult;
                        $.ajax({
                            async: true,
                            type: 'POST',
                            url: Pb.Constants.BackOffice.EipServiceUrl + '/InsertEIPContentVersionPropertyRow?pbl=' + utils.url.get_PageLang(),
                            contentType: 'application/json; charset=utf-8',
                            dataType: 'json',
                            data: params,
                            success: aSuccessFunc,
                            error: aErrFunc ? aErrFunc : function(XMLHttpRequest, textStatus, errorThrown) {
                                try {
                                    alert($.evalJSON(XMLHttpRequest.responseText).Message);
                                }
                                catch (ex) {
                                    alert(ex.message);
                                }
                            }
                        });
                    },
                    /**
                    * Deletes a list of multivalue content rows. All rows are identified using its RowId.
                    * All RowId's must be from the provided aContentVersionId.
                    * @param {Guid} aContentVersionId - The content version id.
                    * @param {Guid[]} aRowIdsToDelete - The list of row id's to delete.
                    * @return - True if everything went fine.
                    * @type {boolean}
                    */
                    deleteMultiValueRows: function(aContentVersionId, aRowIdsToDelete, aSuccessFunc, aErrFunc) {
                        var params = $.compactJSON({
                            'aOnline': this.EIPOnlineMode,
                            'aContentVersionId': aContentVersionId,
                            'aRowsToDeleteIdList': aRowIdsToDelete
                        });
                        var lAjaxResult;
                        $.ajax({
                            async: true,
                            type: 'POST',
                            url: Pb.Constants.BackOffice.EipServiceUrl + '/DeleteEIPContentVersionPropertyRow?pbl=' + utils.url.get_PageLang(),
                            contentType: 'application/json; charset=utf-8',
                            dataType: 'json',
                            data: params,
                            success: aSuccessFunc,
                            error: aErrFunc ? aErrFunc : function(XMLHttpRequest, textStatus, errorThrown) {
                                try {
                                    alert($.evalJSON(XMLHttpRequest.responseText).Message);
                                }
                                catch (ex) {
                                    alert(ex.message);
                                }
                            }
                        });
                    },
                    /**
                    * Creates a new content below or before another content position. The target RowId must
                    * be from the provided aContentVersionId. The new multivalue content row will be created using the content
                    * definition default values.
                    * @param {Guid} aNewContentParentContentId - The parent content id of the new content.
                    * @param {Guid} aNewContentDefinitionId - The parent content id of the new content.
                    * @param {Guid} aNewContentFrameId - The content id of a frame to create a frame relation to when creating the new content.
                    * @param {Guid} aNewContentRelationTypeId - The relationTypeId of the relation to be created with the new content using the aNewContentTargetRelationContentId as the destination (subContent is used by default).
                    * @param {boolean} aRelationDirectionSourceElementAsTarget - Indica el sentido del elemento origen en la relación de ordenación..
                    * @param {Guid} aNewContentTargetRelationElementId - The element id of the content to use as the target of the relation to be created with the new content (aNewContentParentContentId is used by default if this value is null).
                    * @param {Guid} aNewContentTargetPositionContentId - The content id to use to set the position of the content based on the relationType.
                    * @param {boolean} aInsertBelowTarget - Flag indicating if the new created content position must be set below or before the aNewContentTargetPositionId.
                    * @param {boolean} aNavigateToCreatedElement - Flag indicating navigation.
                    * @param {function} aCallbackFunction - Success callback function (probably used to force a postback and refresh the page).
                    * @param {function} aErrorCallbackFunction - Error/cancel callback function.
                    * @return - True if everything went fine.
                    * @type {boolean}
                    */
                    insertContentAtContentPosition: function(aNewContentParentContentId, aNewContentDefinitionId, aNewContentFrameId, aNewContentRelationTypeId, aRelationDirectionSourceElementAsTarget, aNewContentTargetRelationElementId, aNewContentTargetPositionContentId, aInsertBelowTarget, aNavigateToCreatedElement, aCallbackFunction, aErrorCallbackFunction) {
                        var params = [{
                            key: 'aOnline',
                            value: this.EIPOnlineMode + ''
                        }, {
                            key: 'ParentId',
                            value: aNewContentParentContentId
                        }, {
                            key: 'DefinitionId',
                            value: aNewContentDefinitionId
                        }, {
                            key: 'FrameContentId',
                            value: aNewContentFrameId
                        }, {
                            key: 'RelationTypeId',
                            value: aNewContentRelationTypeId ? aNewContentRelationTypeId : Pb.Constants.RelationType.SUB_CONTENT
                        }, {
                            key: 'RelationDirectionSourceElementAsTarget',
                            value: aRelationDirectionSourceElementAsTarget ? aRelationDirectionSourceElementAsTarget : false
                        }, {
                            key: 'TargetRelationElementId',
                            value: aNewContentTargetRelationElementId ? aNewContentTargetRelationElementId : aNewContentParentContentId
                        }, {
                            key: 'TargetPositionContentId',
                            value: aNewContentTargetPositionContentId
                        }, {
                            key: 'InsertBelowTarget',
                            value: aInsertBelowTarget
                        }, {
                            key: 'MustRedirectToCreatedContent',
                            value: aNavigateToCreatedElement // TODO: Ver si se debe pasar parámetro
}];

                            var self = this;
                            self.IsNewContentCreated = false;

                            var closeFunction = function() {
                                var lWindowTop = Pb.Utils.safeGetWindowTop();
                                if (lWindowTop.RedirectToNewContentFunction) {
                                    lWindowTop.RedirectToNewContentFunction.apply();
                                }
                                if (aErrorCallbackFunction && !self.IsNewContentCreated) {
                                    aErrorCallbackFunction.apply();
                                }
                                /*debugger; window.location = window.location*/
                            };

                            // Bindeamos en caso de confirmación de contenido creado
                            var jDocument = $(Pb.Utils.safeGetWindowTop().document);
                            if (aCallbackFunction) {
                                jDocument.bind('newContentCreated', aCallbackFunction);
                            }
                            jDocument.bind('newContentCreated', function(evt, aNewContentId) { self.IsNewContentCreated = true; });

                            TLK.OpenModalWindow(utils.url.buildUrl(Pb.Constants.BackOffice.WizardNewContentUrl, params), null, 'Nuevo contenido', undefined, 640, 580, closeFunction);
                        },
                        /**
                        * Creates a new content below or before another content position. The target RowId must
                        * be from the provided aContentVersionId. The new multivalue content row will be created using the content
                        * definition default values.
                        * @param {Guid} aContentsSourceContentId - The source content id of the selected items.
                        * @param {Guid} aContentRelationTypeId - The relationTypeId of the relation to be created with the new content using the aNewContentTargetRelationContentId as the destination (subContent is used by default).
                        * @param {Guid[]} aIdsToMove - The content id's to move.
                        * @param {Guid} aContentTargetPositionContentId - The content id to use to set the position of the contents based on the relationType.
                        * @param {boolean} aInsertBelowTarget - Flag indicating if the new created content position must be set below or before the aNewContentTargetPositionId.
                        * @return - True if everything went fine.
                        * @type {boolean}
                        */
                        moveContentsToContentPosition: function(aContentsSourceContentId, aContentRelationTypeId, aRelationDirectionSourceElementAsTarget, aIdsToMove, aContentTargetPositionContentId, aInsertBelowTarget, aSuccessFunc, aErrFunc) {
                            var params = $.compactJSON({
                                "aSourceId": aContentsSourceContentId,
                                "aRelationTypeId": aContentRelationTypeId,
                                "aRelationDirectionSourceElementAsTarget": aRelationDirectionSourceElementAsTarget,
                                "aSelectedRowsIds": aIdsToMove,
                                "aTargetElementId": aContentTargetPositionContentId,
                                "toBelow": aInsertBelowTarget ? 'below' : 'above'
                            });
                            $.ajax({
                                async: true,
                                type: 'POST',
                                url: Pb.Constants.BackOffice.ServiceUrl + '/MoveElementsTo?pbl=' + utils.url.get_PageLang(),
                                contentType: 'application/json; charset=utf-8',
                                dataType: 'json',
                                data: params,
                                success: aSuccessFunc,
                                error: aErrFunc ? aErrFunc : function(XMLHttpRequest, textStatus, errorThrown) {
                                    try {
                                        alert($.evalJSON(XMLHttpRequest.responseText).Message);
                                    }
                                    catch (ex) {
                                        alert(ex.message);
                                    }
                                }
                            });
                        },
                        /**
                        * Creates a new content below or before another content position. The target RowId must
                        * be from the provided aContentVersionId. The new multivalue content row will be created using the content
                        * definition default values.
                        * @param {Guid} aContentsSourceContentId - The source content id of the selected items.
                        * @param {Guid} aContentRelationTypeId - The relationTypeId of the relation to be created with the new content using the aNewContentTargetRelationContentId as the destination (subContent is used by default).
                        * @param {Guid[]} aIdsToMove - The content id's to move.
                        * @param {int} aNewPosition - The first position of the contents based on the relationType.
                        * @return - True if everything went fine.
                        * @type {boolean}
                        */
                        moveContentsToPosition: function(aContentsSourceContentId, aContentRelationTypeId, aRelationDirectionSourceElementAsTarget, aIdsToMove, aNewPosition) {
                            var params = $.compactJSON({
                                "aSourceId": aContentsSourceContentId,
                                "aRelationTypeId": aContentRelationTypeId,
                                "aRelationDirectionSourceElementAsTarget": aRelationDirectionSourceElementAsTarget,
                                "aSelectedRowsIds": aIdsToMove,
                                "aNewPosition": aNewPosition
                            });
                            var lAjaxResult;
                            $.ajax({
                                async: false,
                                type: 'POST',
                                url: Pb.Constants.BackOffice.ServiceUrl + '/MoveElementsToPosition?pbl=' + utils.url.get_PageLang(),
                                contentType: 'application/json; charset=utf-8',
                                dataType: 'json',
                                data: params,
                                success: function() {
                                    lAjaxResult = true;
                                },
                                error: function(XMLHttpRequest, textStatus, errorThrown) {
                                    try {
                                        alert($.evalJSON(XMLHttpRequest.responseText).Message);
                                    }
                                    catch (ex) {
                                        alert(ex.message);
                                    }
                                    lAjaxResult = false;
                                }
                            });
                            return lAjaxResult;
                        },
                        /**
                        * Checks a list of contents based on their id's for deletion.
                        * @param {Guid[]} aContentIds - The list of contents to check for deletion.
                        * @param {ElementDeletionClientResult[]} aCheckDeletionResults (out) - The list of elements deletion results to be deleted. Each ElementDeletionClientResult has three properties<br/>: · boolean CanDelete - Flag if the element can be deleted;<br/> · boolean  HasWarnings - Flag indicating if a message with deletion warning should be shown to the client;<br/> · string Message - Deletion warning or confirmation message.
                        * @return - True if everything went fine.
                        * @type {boolean}
                        */
                        checkDeleteContents: function(aContentIds, aCheckDeletionResults) {
                            var params = $.compactJSON({
                                'aOnline': this.EIPOnlineMode,
                                'aElementIds': aContentIds
                            });
                            var lAjaxResult;
                            $.ajax({
                                async: false,
                                type: 'POST',
                                url: Pb.Constants.BackOffice.ServiceUrl + '/ConfirmRemoveMultiple?pbl=' + utils.url.get_PageLang(),
                                contentType: 'application/json; charset=utf-8',
                                dataType: 'json',
                                data: params,
                                success: function(data, responseStatus) {
                                    if (data.d && data.d.length) {
                                        for (var i = 0; i < data.d.length; i++) {
                                            aCheckDeletionResults[i] = data.d[i];
                                        }
                                    }
                                    lAjaxResult = true;
                                },
                                error: function(XMLHttpRequest, textStatus, errorThrown) {
                                    try {
                                        alert($.evalJSON(XMLHttpRequest.responseText).Message);
                                    }
                                    catch (ex) {
                                        alert(ex.message);
                                    }
                                    lAjaxResult = false;
                                }
                            });
                            return lAjaxResult;
                        },
                        /**
                        * Deletes a list of contents using their id's.
                        * @param {Guid[]} aContentIds - The list of contents to be deleted.
                        * @return - True if everything went fine.
                        * @type {boolean}
                        */
                        deleteContents: function(aContentIds) {
                            var params = $.compactJSON({
                                'aOnline': this.EIPOnlineMode,
                                'aKeys': aContentIds
                            });
                            var lAjaxResult;
                            $.ajax({
                                async: false,
                                type: 'POST',
                                url: Pb.Constants.BackOffice.ServiceUrl + '/DeleteElement?pbl=' + utils.url.get_PageLang(),
                                contentType: 'application/json; charset=utf-8',
                                dataType: 'json',
                                data: params,
                                success: function() {
                                    lAjaxResult = true;
                                },
                                error: function(XMLHttpRequest, textStatus, errorThrown) {
                                    try {
                                        alert($.evalJSON(XMLHttpRequest.responseText).Message);
                                    }
                                    catch (ex) {
                                        alert(ex.message);
                                    }
                                    lAjaxResult = false;
                                }
                            });
                            return lAjaxResult;
                        }
                    };
                    return {
                        BackOffice: new BackOffice()
                    };
                } ();
                $.extend(Pb, TBackOffice);

                $.pbBackoffice = Pb.BackOffice;

                //var extensions = {
                //};

                //$.each( extensions, function( i )
                //{
                //	$.fn[i] = this;
                //});
            })(window.jQuery);
        }
    })();
