/*
 * ADOBE CONFIDENTIAL
 *
 * Copyright (c) 2013-2014 Adobe Systems Incorporated. All rights reserved.
 *
 * NOTICE:  All information contained herein is, and remains
 * the property of Adobe Systems Incorporated and its suppliers,
 * if any.  The intellectual and technical concepts contained
 * herein are proprietary to Adobe Systems Incorporated and its
 * suppliers and are protected by trade secret or copyright law.
 * Dissemination of this information or reproduction of this material
 * is strictly forbidden unless prior written permission is obtained
 * from Adobe Systems Incorporated.
 */

/*jslint vars: true, plusplus: true, devel: true, nomen: true, indent: 4 */
/*global define: true, graphite: true, document: true*/

define([
    'jquery',
    'underscore',
    'backbone',
    'parfait/PSDDetailsView',
    'plugin-dependencies',
    'DWPSDExtractManager',
    'ccweb.files.extract/controllers/DetailsController',
    'utils/TemplateUtil',
    'ccweb.files.extract/controllers/SelectionController'
], function ($, _, Backbone, PSDDetailsView, deps, DWPSDExtractManager, DetailsController, TemplateUtil, SelectionController) {
    "use strict";

    var DwPSDDetailsView = PSDDetailsView.extend({
        
        initialize: function (authModel, path) {
            PSDDetailsView.prototype.initialize.apply(this, arguments);
            _.bindAll(this, "resizeHandler");
            $(window).on('resize', this.resizeHandler);
        },
        
        remove: function () {
            $(window).off('resize', this.resizeHandler);
            window.graphite.events.off(null, null, this);
            this.removeEventListeners();

            var views = ['detailPanelView', 'previewView', 'extractAssetPopup', 'extractCodePopup',
                    'colorChipPopup', 'layerThumbPopup', 'assetThumbPopup', 'helpView',
                    'extractForDeviceDlg', 'selectionBar'];

            DetailsController.setSelectedTab('psdInspectTab');
            DetailsController.setSelectedInspectItem(null);
            this.destroyViews(views);
            SelectionController.psdView = null;

            this.$el.empty();
            this.unbind();
            this.stopListening();
            return Backbone.View.prototype.remove.apply(this, arguments);
        },
        
        resizeHandler: function () {
            if (this.timer) {
                clearTimeout(this.timer);
            }

            this.timer = setTimeout(function () {
                var $selectionDiv = $('div.selection-controlbar'),
                    $breadcrumb = $('#breadcrumbs ul li.less-width');
                if ($selectionDiv.length > 0 && $breadcrumb.length > 0) {
                    var selectionDivLeft = $selectionDiv[0].getBoundingClientRect().left,
                        breadCrumbRight = $breadcrumb[0].getBoundingClientRect().right;
                    if (selectionDivLeft < breadCrumbRight) {
                        var curWidth = $breadcrumb.width();
                        $breadcrumb.width(curWidth - (breadCrumbRight - selectionDivLeft));
                    } else {
                        var fileNameElement = $breadcrumb.find('a.back-to-files');
                        if (fileNameElement.length > 0) {
                            var maxWidth = fileNameElement[0].getBoundingClientRect().width + 8, // 8 is the margin applied
                                availableWidth = selectionDivLeft - $breadcrumb[0].getBoundingClientRect().left;
                            $breadcrumb.width(Math.min(maxWidth, availableWidth));
                        }
                    }
                }
            }, 100);
        },

        events: function () {
            return _.extend({}, PSDDetailsView.prototype.events, {
                'click .details-anchor' : 'handleTabClick'
            });
        },
        
        handleModelImgdataChanged: function () {
            if (this.$notification) {
                this.$notification.remove();
                this.$notification = null;
            }
            this.$el.find(".thumbnail-header").remove();

            var currentURLs = this.model.get("path").split('/'),
                urlIndex = 0,
                urlInfo = { urls: [] };
            
            for (urlIndex; urlIndex < currentURLs.length; ++urlIndex) {
                var newURLInfo = {};
                newURLInfo.label = currentURLs[urlIndex];
                if (urlIndex === 0) {
                    currentURLs[urlIndex] = '#' + currentURLs[urlIndex];
                } else {
                    currentURLs[urlIndex] = currentURLs[urlIndex - 1] + '/' + currentURLs[urlIndex];
                }
                newURLInfo.href = currentURLs[urlIndex];
                
                if (urlIndex === currentURLs.length - 1) {
                    urlInfo.urls.push(newURLInfo);
                }
            }
            
            this.$el.append(TemplateUtil.createTemplate("#thumbnail-header-template", urlInfo));
            if (window.graphite.routers.main.isWelcomeExpDismissed()) {
                this.$el.find("#breadcrumbs").rcrumbs({
                    nbFixedCrumbs: 1
                });

                this.$el.find(".thumbnail-header .back-to-files")
                    .click(function () {
                        if (navigator.onLine) {
                            SelectionController.changeSelection([], false);
                            var backHref = this.getAttribute("data-href");
                            /* Check if BackHref ends with .psd . If yes, then refresh the PSD view otherwise load the folder contents. */
                            if (backHref.toLowerCase().indexOf('.psd', backHref.length - 4) === -1 && !$(this).hasClass('psdCrumb')) {
                                Backbone.history.navigate(decodeURI(backHref), true);
                            } else if (!graphite.serverAPI.isPreviewLoading()) {
                                var newFragment = Backbone.history.fragment;
                                Backbone.history.fragment = null;
                                Backbone.history.navigate(newFragment, true);
                            }
                        }
                        return false;
                    });
                
                this.$el.find(".thumbnail-header .back-to-files:last-child").addClass('psdCrumb');
                
                if (deps.utils.getCurrentPage() !== undefined) {
                    this.$el.find(".thumbnail-header .back-to-files").css("visibility", "visible");
                    this.$el.find(".thumbnail-header .header-separator").css("visibility", "visible");
                } else {
                    this.$el.find(".thumbnail-header .back-to-files").css("visibility", "hidden");
                    this.$el.find(".thumbnail-header .header-separator").css("visibility", "hidden");
                }
            } else {
                this.$el.find(".thumbnail-header-nowrap").addClass("hide");
                this.$el.find("#get-started-button").removeClass("hide");
                this.$el.find("#get-started-nowrap")
                    .click(function () {
                        graphite.events.trigger("get-started-clicked");
                        window.graphite.routers.main.setIsWelcomeExpDismissed(true);
                        DWPSDExtractManager.setPrefToShowUploadDialogOnReload(true);
                        DWPSDExtractManager.refreshPanel();
                    });
            }
            
            this.$el.find(".styles-label").html(deps.translate("STYLES"));
            this.$el.find(".layers-label").html(deps.translate("LAYERS"));
        },
        
        handleTabClick: function (event) {
            var selectedAnchorId = $(event.target).attr('id');
            DetailsController.setSelectedTab(selectedAnchorId);
            $(event.target).parent().find('a').each(function (index) {
                if ($(this).attr('id') === selectedAnchorId && !$(this).hasClass('active')) {
                    $(this).addClass("active");
                    if (selectedAnchorId) {
                        var panelName = "";
                        switch (selectedAnchorId) {
                        case "psdLayersTab":
                            panelName = "Layers";
                            break;
                        case "psdInspectTab":
                            panelName = "Styles";
                            break;
                        default:
                            break;
                        }
                        if (panelName) {
                            graphite.events.trigger("selectedTab", {formatSubEvent : [panelName]});
                        }
                    }
                } else {
                    $(this).removeClass("active");
                }
            });
        }
    });

    return DwPSDDetailsView;

});
