/*
    Copyright 2015 Adobe Systems Incorporated.  All rights reserved. 
*/
/*global $*/
/*jslint vars:true*/
$(document).ready(function (event) {
    'use strict';
    
    window.preview.main.setUpLocalization(function () {
        $('.copyIcon').attr('title', window.preview.utils.translate('DEVICE_COPY_ICON_TOOLTIP'));
    });
     
    
    var msg = '', link = '', url = '', icon = '';
    if (window.navigator.onLine) {
        msg = window.preview.utils.translate('DEVICE_PREVIEW_DESCRIPTION');
        link = window.preview.utils.translate('DEVICE_INIT_WAIT_MESSAGE');
        icon = window.preview.config.ICON_PATHS.SPINNER;
    } else {
        window.preview.main.setCurrentError(window.preview.config.PREVIEW_ERRORS.ERROR_NO_INTERNET);
        msg = window.preview.utils.translate('DEVICE_NOT_CONNECTED_TO_INTERNET');
        icon = window.preview.config.ICON_PATHS.NO_INTERNET_ERROR;
    }
    
    window.preview.handlers.setMessageUrlIcon(msg, link, url, icon);
    window.addEventListener('online', $.proxy(window.preview.handlers.handleOnOnlineNotification, window.preview.handlers));
    window.setTimeout($.proxy(window.preview.handlers.initAppCheckTimeoutCallback, window.preview.handlers), window.preview.config.DW_SERVICE_FAIL_TIMEOUT);
    //get theme from query param and platform from navigator
	//to apply font and color changes
    window.getUrlVars = function (url) {
		'use strict';
		
		if (!url) {
			return;
		}

		var vars = {};
		url.replace(/[?&]+([^=&]+)=([^&]*)/gi, function (m, key, value) {
			vars[key] = value;
		});
		return vars;
    };

    window.getThemeFromGETParam = function (url) {
		'use strict';
		var urlVars = window.getUrlVars(url), ret = '';
		if (urlVars) {
			ret = urlVars.theme;
		}

		return ret;
    };
    
    var theme = window.getThemeFromGETParam(window.location.href);
    window.preview.handlers.applyTheme(theme);
    if (window.navigator.platform.indexOf("Win") !== -1) {
        $('body').css('font-family', 'Tahoma');
	}
    if (window.navigator.platform.indexOf("Mac") !== -1) {
        $('body').css('font-family', 'Lucida Grande');
	}
    window.preview.main.adjustWindowHeight();
    
});

function Handlers() {
    'use strict';
    this.deviceClients = {};
    this.copyInProgress = false;
    this.theme = {'arrow-right': '', 'arrowdown': ''};
    
    
    this.onEditBrowserList = function () {
        window.DWDevicePreviewCallJsBridgingFunction("EditBrowserList");
    };
       
    this.browserListChanged = function () {
        window.DWDevicePreviewCallJsBridgingFunction("getPrimaryBrowser", {'callback': $.proxy(window.preview.main.setPrimaryBrowser, window.preview.main)});
        window.DWDevicePreviewCallJsBridgingFunction("getDefaultbrowserList", {'callback': $.proxy(window.preview.main.refreshBrowserList, window.preview.main)});
    };
    
    this.initAppCheckTimeoutCallback = function () {
        //called after about 10 seconds to check if we are up, or else show some message
        if (window.preview.main.getCurrentError() !== window.preview.config.PREVIEW_ERRORS.ERROR_NO_INTERNET && !(window.preview.main.getAccessToken() && window.preview.main.getUserId() && window.preview.config.DW_SERVER_HOSTS && window.preview.config.DW_SERVER_PORT)) {
                //we have not recieved the required information from DW, ask DW what exactly went wrong and then display accordingly
            if (!window.preview.main.getIsInitializedFirstTime()) {
                window.DWDevicePreviewCallJsBridgingFunction("getPreviewError", {'callback': $.proxy(this.errorHandler, this)});
                return;
            }
        }
    };
    
    this.errorHandler = function (retObj) {
        var msg = '', link = '', url = '', icon = '';
        switch (retObj) {
        case window.preview.config.PREVIEW_ERRORS.ERROR_NO_INTERNET:
            window.preview.main.setCurrentError(window.preview.config.PREVIEW_ERRORS.ERROR_NO_INTERNET);
            msg = window.preview.utils.translate('DEVICE_NOT_CONNECTED_TO_INTERNET');
            icon = window.preview.config.ICON_PATHS.NO_INTERNET_ERROR;
            break;
        case window.preview.config.PREVIEW_ERRORS.ERROR_NO_GUID:
            window.preview.main.setCurrentError(window.preview.config.PREVIEW_ERRORS.ERROR_NO_GUID);
            msg = window.preview.utils.translate('DEVICE_USER_CREDENTIAL_ERROR');
            icon = window.preview.config.ICON_PATHS.GENERIC_ERROR;
            link = window.preview.utils.translate('DEVICE_TROUBLESHOOT');
            url = window.preview.utils.getTroubleshootingPageURL();
            break;
        case window.preview.config.PREVIEW_ERRORS.ERROR_NO_ACCESS_TOKEN:
            window.preview.main.setCurrentError(window.preview.config.PREVIEW_ERRORS.ERROR_NO_ACCESS_TOKEN);
            msg = window.preview.utils.translate('DEVICE_USER_CREDENTIAL_ERROR');
            icon = window.preview.config.ICON_PATHS.GENERIC_ERROR;
            link = window.preview.utils.translate('DEVICE_TROUBLESHOOT');
            url = window.preview.utils.getTroubleshootingPageURL();
            break;
        case window.preview.config.PREVIEW_ERRORS.ERROR_NO_NODE_SERVER:
            window.preview.main.setCurrentError(window.preview.config.PREVIEW_ERRORS.ERROR_NO_NODE_SERVER);
            msg = window.preview.utils.translate('DEVICE_NODE_PROCESS_FAILED');
            icon = window.preview.config.ICON_PATHS.GENERIC_ERROR;
            link = window.preview.utils.translate('DEVICE_TROUBLESHOOT');
            url = window.preview.utils.getTroubleshootingPageURL();
            url += window.preview.config.TROUBLESHOOTING_ANCHOR.NO_LAUNCH_ID;
            break;
        case window.preview.config.PREVIEW_ERRORS.ERROR_NONE:
            break;
        default:
            break;
        }
        
        if (msg) {
            this.setMessageUrlIcon(msg, link, url, icon);
        }
    };

    this.setMessageUrlIcon = function (msg, linkMsg, url, icon) {
        $('#devicePreviewDesc').text(msg);
        $('#link').html(linkMsg);
        
        if (icon) {
            $('.ccSpinner').attr('src', icon);
        } else {
            $('.ccSpinner').attr('src', window.preview.config.ICON_PATHS.SPINNER);
        }
        window.preview.main.adjustWindowHeight();
    };
    
    this.newDeviceConnected = function (clientData) {
        
        if (window.preview.main.getIsReInitialised()) {
            window.preview.main.setIsReInitialised(false);
            if (window.navigator.onLine) {
                $('#devicePreviewDesc').text(window.preview.utils.translate('DEVICE_PREVIEW_DESCRIPTION'));
                $('#devicePreviewDesc').css('color', window.preview.config.DESCRIPTION_DEFAULT_COLOR);
            }
        }
        var browserLabel = '';
        var socketID = clientData.id,
            deviceModel = clientData.device && clientData.device.model ? clientData.device.model : "",
            osName = clientData.os && clientData.os.name ? clientData.os.name : "",
            osVersion = clientData.os && clientData.os.version ? clientData.os.version : "",
            deviceInfo = browserLabel + deviceModel || osName + ' - ' + osVersion,
            browserName = clientData.browser && clientData.browser.name ? clientData.browser.name : "",
            browserVersion = clientData.browser && clientData.browser.major ? ' ( v' + clientData.browser.major + ' )' : "",
            devicePixelRatio = clientData.devicePixelRatio ?  ' dPR: ' +  parseFloat(Number((clientData.devicePixelRatio)).toFixed(2)) : '',
            deviceMetadataArray = [];

        var deviceTemplate = "";
        if (clientData.isLocalConnection) {
            deviceTemplate =  "<tr class=\"deviceEntryRow\" data-id=\"" + socketID + "\"><td class=\"deviceInfo\"><span>" + browserName + browserVersion + "</span></td></tr>";
        } else {
            deviceTemplate =  "<tr class=\"deviceEntryRow\" data-id=\"" + socketID + "\"><td class=\"deviceInfo\"><span class=>" + deviceInfo + "</span> <span>" + browserName + browserVersion + "</span></td></tr>";
        }

        this.deviceDisconnected(socketID);  //Ensure uniqueness of the device socket IDs.
        window.preview.socketApp.sendMouseHoverOut(socketID);
        if (clientData.isLocalConnection) {
            $('.browserListToggle > .devicesConnected > tbody').append(deviceTemplate);
            this.installHoverHandler($('.deviceEntryRow').last());
            this.installInspectHandler($('.inspect').last());
        } else {
            $('.deviceList.devicesConnected > tbody').append(deviceTemplate);
            this.installHoverHandler($('.deviceEntryRow').last());
            this.installInspectHandler($('.inspect').last());
        }
        this.deviceClients[clientData.id] = clientData;
        
        if (osName && osVersion) {
            deviceMetadataArray.push("OSVersion:" + osName + " " + osVersion);
        }
        if (deviceModel) {
            deviceMetadataArray.push("DeviceModel:" + deviceModel);
        }
        if (browserName && browserVersion) {
            deviceMetadataArray.push("BrowserVersion:" + browserName + " " + browserVersion);
        }
        if (devicePixelRatio) {
            deviceMetadataArray.push("DevicePixelRatio:" + devicePixelRatio);
        }
        if (typeof deviceMetadataArray !== 'undefined' && deviceMetadataArray.length > 0) {
            window.preview.metricsController.trackEvent('meta-data', {dataGroup: deviceMetadataArray});
        }
        
        window.DWDevicePreviewCallJsBridgingFunction("updateDeviceCount", {count: window.preview.utils.getDevicesCount()});
        window.preview.main.adjustWindowHeight();
        window.preview.handlers.applyTheme();
    };
    
    this.deviceDisconnected = function (clientId) {
        var $deviceEntry;

        $deviceEntry = $('.deviceList').find('tr').filter('[data-id=\"' + clientId + '\"]');
        
        var $browserEntry = $('.browserListToggle > .devicesConnected').find('tr').filter('[data-id=\"' + clientId + '\"]');
        $deviceEntry.remove();
        $browserEntry.remove();
        window.preview.main.adjustWindowHeight();
        
        if (this.deviceClients.hasOwnProperty(clientId)) {
            delete this.deviceClients[clientId];
        }
        
        window.DWDevicePreviewCallJsBridgingFunction("updateDeviceCount", {count: window.preview.utils.getDevicesCount()});
    };
    
    this.installHoverHandler = function ($element) {
        var self = this;
        
        $element.hover(
            function () {
                var clientId = $(this).data('id'),
                    clientData = self.deviceClients[clientId];
                
                window.preview.socketApp.sendMouseHoverIn(clientData);
                $element.addClass("hoverOn");
            },
            function () {
                var clientId = $(this).data('id');
                window.preview.socketApp.sendMouseHoverOut(clientId);
                $element.removeClass("hoverOn");
            }
        );
    };
    
    this.handleOnOnlineNotification = function () {
        if (window.preview.main.getCurrentError() === window.preview.config.PREVIEW_ERRORS.ERROR_NO_INTERNET) {
            window.location.reload(true);
        }
    };
    
    this.clearInspectStateHandler = function () {
        $('.deviceList').find('.inspectOn').removeClass("inspectOn");
        $('.deviceList').find('.deviceClicked').removeClass("deviceClicked");
    };
    
    this.installInspectHandler = function ($element) {
        var self = this;
        $element.on('click', function (event) {
            var socketId = $(this).parent().data('id');
            if ($element.hasClass('inspectOn')) {
                window.DWDevicePreviewCallJsBridgingFunction("setLiveViewInspectMode", {'mode': false});
                $('.deviceList').find('.inspectOn').removeClass("inspectOn");
                $('.deviceList').find('.deviceClicked').removeClass("deviceClicked");
                window.preview.socketApp.sendInspectOffCommand(socketId);
            } else {
                window.preview.socketApp.sendInspectOffCommand();
                window.DWDevicePreviewCallJsBridgingFunction("setLiveViewInspectMode", {'mode': true});
                window.DWDevicePreviewCallJsBridgingFunction("showOrHidePreviewPopup", {'show': false});
                window.preview.socketApp.queryDeviceViewportCommand(socketId);
                $('.deviceList').find('.inspectOn').removeClass("inspectOn");
                $('.deviceList').find('.deviceClicked').removeClass("deviceClicked");
                $element.addClass("inspectOn");
                $('.inspectOn').parent().addClass('deviceClicked');
                window.preview.metricsController.trackEvent('inspect-clicked');
            }
        });
    };
    
    this.onLaunchURLinBrowser = function (event) {
        // TODO: We need to fetch the actual URL and launch that.
		// I will do this change post the first cut check-in.
        // Preview local url in Browser. - Prashanth Nethi
        var url = 'http://' + window.preview.config.DW_LOCAL_HOST + ':' + window.preview.config.DW_SERVER_PORT + '/preview/app/index.html?m=c';
        var browser = $(event.target).closest('tr').attr('id');
        if (browser !== "") {
            window.DWDevicePreviewCallJsBridgingFunction("LaunchURLinBrowser", {'URL': url, 'theBrowser': browser});
        }
    };
    
    this.getInspectedSocketId = function () {
        var $inspectElement = $('.deviceList').find('.inspectOn'),
            socketId = '';
        if ($inspectElement && $inspectElement.length > 0) {
            socketId = $inspectElement.parent().data('id');
        }
        return socketId;
    };
    
    this.getHoveredSocketId = function () {
        var $hoveredElement = $('.deviceList').find('.hoverOn'),
            socketId = '';
        if ($hoveredElement && $hoveredElement.length > 0) {
            socketId = $hoveredElement.data('id');
            $hoveredElement.removeClass('hoverOn');
        }
        return socketId;
    };
    
    this.applyTheme = function (themeNameParam) {
        
        var themeName = themeNameParam || window.lastAppliedTheme;
        window.lastAppliedTheme = themeName;
        
        var backgroundColor = '',
			editList = '',
            browserListColor = '',
            hoverBackground = '',
            clickBackground = '',
            shortcut = '',
            header = '',
            link = '',
            text = '',
            deviceBackgroundColor = '',
            deviceListColor = '';

        if (themeName === "dark") {
            backgroundColor = window.preview.config.THEME.Darkest.G3;
            editList = window.preview.config.THEME.Darkest.G9;
            browserListColor = window.preview.config.THEME.Darkest.G9;
            deviceListColor = window.preview.config.THEME.Darkest.G8;
            hoverBackground = window.preview.config.THEME.Darkest.G5;
            clickBackground = window.preview.config.THEME.Darkest.G1;
            shortcut = window.preview.config.THEME.Darkest.G8;
            header = window.preview.config.THEME.Darkest.G8;
            link = window.preview.config.THEME.Darkest.G9;
            text = window.preview.config.THEME.Darkest.G8;
            deviceBackgroundColor = window.preview.config.THEME.Darkest.G11;

        } else if (themeName === "midDark") {
            backgroundColor = window.preview.config.THEME.Dark.G3;
            editList = window.preview.config.THEME.Dark.G9;
            browserListColor = window.preview.config.THEME.Dark.G9;
            deviceListColor = window.preview.config.THEME.Dark.G8;
            hoverBackground = window.preview.config.THEME.Dark.G5;
            clickBackground = window.preview.config.THEME.Dark.G1;
            shortcut = window.preview.config.THEME.Dark.G8;
            header = window.preview.config.THEME.Dark.G8;
            link = window.preview.config.THEME.Dark.G9;
            text = window.preview.config.THEME.Dark.G8;
            deviceBackgroundColor = window.preview.config.THEME.Dark.G11;

		} else if (themeName === "light") {
            backgroundColor = window.preview.config.THEME.Lightest.G3;
            editList = window.preview.config.THEME.Lightest.G8;
            browserListColor = window.preview.config.THEME.Lightest.G10;
            deviceListColor = window.preview.config.THEME.Lightest.G8;
            hoverBackground = window.preview.config.THEME.Lightest.G2;
            clickBackground = window.preview.config.THEME.Lightest.G5;
            shortcut = window.preview.config.THEME.Lightest.G9;
            header = window.preview.config.THEME.Lightest.G9;
            link = window.preview.config.THEME.Lightest.G10;
            text = window.preview.config.THEME.Lightest.G8;
            deviceBackgroundColor = window.preview.config.THEME.Lightest.G11;

		} else if (themeName === "midLight") {
            backgroundColor = window.preview.config.THEME.Light.G3;
            editList = window.preview.config.THEME.Light.G8;
            browserListColor = window.preview.config.THEME.Light.G10;
            deviceListColor = window.preview.config.THEME.Light.G8;
            hoverBackground = window.preview.config.THEME.Light.G2;
            clickBackground = window.preview.config.THEME.Light.G5;
            shortcut = window.preview.config.THEME.Light.G9;
            header = window.preview.config.THEME.Light.G9;
            link = window.preview.config.THEME.Light.G10;
            text = window.preview.config.THEME.Light.G8;
            deviceBackgroundColor = window.preview.config.THEME.Light.G11;
        }
        $("body").css("background-color", backgroundColor);
        $(".editList").css("color", editList);
        $(".browserList").css("color", browserListColor);
        $(".deviceList").css("color", browserListColor);
        $(".devicesConnected").css("color", deviceListColor);
        $(".nonHTMLerror").css("color", deviceListColor);
        
        $(".listHeader").css("color", header);
        $("#link").css("color", link);
        $(".devicesConnected > tbody").css("background-color", deviceBackgroundColor);
        $(".nonHTMLerror").css("background-color", deviceBackgroundColor);
        $(".previewText").css("color", text);
        $(".shortcut").css("color", shortcut);
        this.theme['arrow-down'] = header;
        this.theme['arrow-right'] = header;
        
        var theme_regex = function (index, css) {
            return (css.match(/(^|\s)theme-\S+/g) || []).join(' ');
        };
        $(".devicesConnected").removeClass(theme_regex);
        $(".devicesConnected").addClass("theme-" + themeName);
        
        $(".devicesConnected > tbody > tr").removeClass(theme_regex);
        $(".devicesConnected > tbody > tr").addClass("theme-" + themeName);
        
        $(".devicesConnected > tbody").removeClass(theme_regex);
        $(".devicesConnected > tbody").addClass("theme-" + themeName);
        
        $(".nonHTMLerror > .errorImage").removeClass(theme_regex);
        $(".nonHTMLerror > .errorImage").addClass("theme-" + themeName);
        
        $(".arrow-right").removeClass(theme_regex);
        $(".arrow-right").addClass("theme-" + themeName);
        
        $(".arrow-down").removeClass(theme_regex);
        $(".arrow-down").addClass("theme-" + themeName);
        
        $(".pibList").removeClass(theme_regex);
        $(".pibList").addClass("theme-" + themeName);
    };
}

window.preview.handlers = window.preview.handlers || new Handlers();

window.onDWThemeChange = function (themeName) {
	window.preview.handlers.applyTheme(themeName);
};
