//////////////////////////////////////////////////////////////////////////////////////////////
//
// ADOBE CONFIDENTIAL
// ___________________
//
//  Copyright 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.
//////////////////////////////////////////////////////////////////////////////////////////////

//////////////////////////////////////////////////////////////////////////////////////////////
// Summary Comment
// There is a browser control which is the primary UI for the panel.
// We load the DW Extract HTML in this view and through JS Bridging we communication between the Dw and Dw Extract Web App.
//////////////////////////////////////////////////////////////////////////////////////////////

/*global alert: false, console: false, dw: false, window: false, document: false, DWPSDExtractBridge: false,
initUI: false, setupJSBridging: false, dwscripts:false,
MM: false
*/

var gInitedUI = false,
	gWindowChromeSize = 0,
	gInitialPanelHeight = 644,
	gInitialPanelWidth = 512,
	gBrowser = null,
	gActiveDOM = null,
	gInitialSizeSet = false,
	gWindowHeightOffset = 0,
	HELP_DOC = MM.HELP_extract,
	gWindowWidthOffset = 0;
    
//////////////////////////////////////////////////////////////////////////////////////////////
// DW API callback functions. 
//

//--------------------------------------------------------------------
// FUNCTION:
//   refresh
//
// DESCRIPTION:
//  Refresh the panel.
//
// ARGUMENTS:
//  none
//
// RETURNS:
//  none
//--------------------------------------------------------------------
function refresh() {
    "use strict";
    initUI(true);
}
//--------------------------------------------------------------------
// FUNCTION:
//   initialSize
//
// DESCRIPTION:
//  Calculates and returns the initial size for the panel when asked for by Dw
//
// ARGUMENTS:
//   platform - "Mac" or "Win"
//
// RETURNS:
//  the Initial Size required by the panel as a string - "width, height"
//--------------------------------------------------------------------
function initialSize(platform) {
	"use strict";

	var maxIntialSize = dw.getMaxPanelSize(),
        screenHeight = maxIntialSize[1],// array = {width, height}
        height = gInitialPanelHeight;

	if (screenHeight < gInitialPanelHeight + gWindowChromeSize) {
		height = screenHeight - gWindowChromeSize;
	}

	gInitialSizeSet = true;
	return gInitialPanelWidth.toString() + "," + height.toString();   // OWL adds ~38 px of chrome to the height         
}

//--------------------------------------------------------------------
// FUNCTION:
//   initialPosition
//
// DESCRIPTION:
//  Calculates and returns the initial Position for the panel when asked for by Dw
//
// ARGUMENTS:
//   platform - "Mac" or "Win"
//
// RETURNS:
//  the Initial Size required by the panel as a string - "x, y"
//--------------------------------------------------------------------
function initialPosition(platform) {
	"use strict";
}

//--------------------------------------------------------------------
// FUNCTION:
//   canShow
//
// DESCRIPTION:
//  Calculates and returns a boolean if the panel should be shown
//
// ARGUMENTS:
//   platform - "Mac" or "Win"
//
// RETURNS:
//  the Initial Size required by the panel as a string - "width, height"
//--------------------------------------------------------------------
function canShow(platform) {
	"use strict";
	return true;
}

//--------------------------------------------------------------------
// FUNCTION:
//   displayHelp
//
// DESCRIPTION:
//  Redirect to the Help url for Extract
//
// RETURNS:
//  Redirect to the Help url for Extract
//--------------------------------------------------------------------
function displayHelp() {
    "use strict";
	dwscripts.displayDWHelp(HELP_DOC);
    dw.logEvent("ExtractPanel", "DWContext_Extract_HelpLaunched");
}

//--------------------------------------------------------------------
// FUNCTION:
//   isResizable
//
// DESCRIPTION:
//  Calculates and returns a boolean if the panel is resizable
//
// RETURNS:
//  boolean - true or false
//--------------------------------------------------------------------
function isResizable() {
	"use strict";
	return true;
}

//--------------------------------------------------------------------
// FUNCTION:
//   selectionChanged
//
// DESCRIPTION:
//  Handle the Selection Change message from Dw, Is used to refresh the UI
//
// ARGUMENTS:
//   none
//
// RETURNS:
//  nothing 
//--------------------------------------------------------------------
function selectionChanged() {
	"use strict";
	var dom = dw.getDocumentDOM();
	if (dom && !gInitedUI) {
		initUI(false);
	} else if (dom !== gActiveDOM) {
		gActiveDOM = dom;
	}
	//if (!dom) {
	//	// All documents are now closed
	//	// shutDown the UI
	//}
}

// function documentEdited()
// {
// // needs to be implemented if we listen to dw document edits
// }

//--------------------------------------------------------------------
// FUNCTION:
//   onShow
//
// DESCRIPTION:
//  Handle the Show event from Dreamweaver for the panel and see if
// the browser needs to refresh the UI
//
// ARGUMENTS:
//   none
//
// RETURNS:
//  nothing 
//--------------------------------------------------------------------
function onShow() {
    "use strict";
    if (!gInitedUI) {
        initUI(false);
    }
}

//--------------------------------------------------------------------
// FUNCTION:
//   onResize
//
// DESCRIPTION:
//  Handle the Resize event from Dreamweaver and resize the embedded
//  browser control
//
// ARGUMENTS:
//   none
//
// RETURNS:
//  nothing 
//--------------------------------------------------------------------
function onResize() {
	"use strict";
	if (!gInitedUI) {
		initUI(false);
	} else {
		var height = window.innerHeight;
		if (gBrowser === null) {
			gBrowser = document.getElementById('browser_extract_panel');
		}
		if (gBrowser && gBrowser.style) {
			gBrowser.style.height = height - gWindowHeightOffset + "px";
			gBrowser.style.width = window.innerWidth - gWindowWidthOffset + "px";
            gBrowser.style["margin-left"] = "-15px";

	    }
	}
}

//--------------------------------------------------------------------
// FUNCTION:
//   isAvailableInCodeView
//
// DESCRIPTION:
//  Should the panel be enabled when foxus is in code view
//
// ARGUMENTS:
//   none
//
// RETURNS:
//  boolean - true or false 
//--------------------------------------------------------------------
function isAvailableInCodeView() {
	"use strict";
	return true;
}

//--------------------------------------------------------------------
// FUNCTION:
//   onHide
//
// DESCRIPTION:
//  Handle the onHide message
//
// ARGUMENTS:
//   none
//
// RETURNS:
//  none
//--------------------------------------------------------------------
function onHide() {
	"use strict";
    //Do something before the panel hides
    // Needs to be implemented
	dw.psdExtract.updateCSSForSelection("", "", "", 0, 0, 0, 0, false, "", "", "", "");
}

//--------------------------------------------------------------------
// FUNCTION:
//   minSize
//
// DESCRIPTION:
//  Define the min Size for the Panel. Cannot be resized beyond this
//
// ARGUMENTS:
//   none
//
// RETURNS:
//  "width, height" 
//--------------------------------------------------------------------
function minSize() {
	"use strict";
	return "480, 410";
}

//////////////////////////////////////////////////////////////////////////////////////////////
// Panel Behaviour Implementation
//
//--------------------------------------------------------------------
// FUNCTION:
//   getDwData
//
// DESCRIPTION:
//  Get the data that we want to pass to Extract panel as a string.
//
// ARGUMENTS:
//   none
//
// RETURNS:
//  nothing 
//--------------------------------------------------------------------
function getDwData() {
    "use strict";
    var dwData = {
        'configPath': dw.getUserConfigurationPath(),
        'programConfigPath': dw.getConfigurationPath(),
        'isWelcomeExpDismissed': dw.psdExtract.isWelcomeExpDismissed(),
        'OsType': dw.psdExtract.IsMacOS() ? 'MAC' : 'WINDOWS',
        'userDocumentsPath': dw.getSpecialFolderPath(1), //1 stands for Documents Folder. Please refer API documentation
        'shortDateFormat': dw.getPreferredShortDateFormat(),
        'appLanguage': dw.getAppLanguage(),
        'shouldShowUploadDialogOnReload': dw.psdExtract.shouldShowUploadDialogOnReload()
    },
        serialize = function (obj) {
            var str = [],
                prop = null;
            for (prop in obj) {
                if (obj.hasOwnProperty(prop)) {
                    str.push(encodeURIComponent(prop) + "=" + encodeURIComponent(obj[prop]));
                }
            }
            return str.join("&");
        };
    return serialize(dwData);
}
//--------------------------------------------------------------------
// FUNCTION:
//   handlePreferenceChange
//
// DESCRIPTION:
//	Handler for Preference update event
//
// ARGUMENTS:
//   none
//
// RETURNS:
//  nothing 
//--------------------------------------------------------------------
function handlePreferenceChange() {
    "use strict";
    var browserWindow = gBrowser.getWindow();

    if (browserWindow && browserWindow.dwPSDExtractManager) {
        browserWindow.dwPSDExtractManager.getExtractPreferences();
    }
}


//--------------------------------------------------------------------
// FUNCTION:
//   initUI
//
// DESCRIPTION:
//	Initialize the browser control and load the HTML which 
//	contains most of the Panel UI code.
//
// ARGUMENTS:
//   none
//
// RETURNS:
//  nothing 
//--------------------------------------------------------------------
function initUI(force) {
	"use strict";

	gBrowser = document.getElementById('browser_extract_panel');
	gBrowser.setEnableDragDrop(true);
	gBrowser.style.width = window.innerWidth - gWindowWidthOffset + "px";
	gBrowser.style["margin-left"] = "-15px";

	//We don't get the right Window size on first launch.
	if (gInitialSizeSet) {
		gBrowser.style.height = gInitialPanelHeight - gWindowHeightOffset + "px";
		gInitialSizeSet = false;
	} else {
		gBrowser.style.height = window.innerHeight - gWindowHeightOffset + "px";
	}
    createTemporaryHTML();

	if (!gInitedUI || force) {
		gInitedUI = true;
		gBrowser.setScrollbarMode("off", "h");
        var queryStr = getDwData(),
            // Add the variables that might be required by Extract as a query string. We extract them as soon as index.html starts loading
            htmlPath = dw.getConfigurationPath() + '/Floaters/dw-extract/indextemp.html?',
            initializeExtractService = function () {
                setupJSBridging();
                // attempt 1 to initialize extract. Can fail.
                dw.psdExtract.initializeExtract();
            };
        
		gBrowser.addEventListener('BrowserControlLoad', initializeExtractService, false);
		document.addEventListener('DWPreferenceSettingChanged', handlePreferenceChange, false);
		gBrowser.openURL(htmlPath);
	}
}

function createTemporaryHTML() {
    var htmlPath = dw.getConfigurationPath() + '/Floaters/dw-extract/index.html',
        htmlTempPath = dw.getConfigurationPath() + '/Floaters/dw-extract/indextemp.html',
        queryStr = getDwData(),
        str = DWfile.read(htmlPath);
		str = str.replace("\$\$QUERYSTR\$\$",queryStr);
		DWfile.write(htmlTempPath,str);
}


//--------------------------------------------------------------------
// FUNCTION:
//   setupJSBridging
//
// DESCRIPTION:
//  Set up the JS Bridging Infrastructure between the Extract Panel and Dw
//
// ARGUMENTS:
//   none
//
// RETURNS:
//  nothing 
//--------------------------------------------------------------------
function setupJSBridging() {
	"use strict";
    var browserWindow = gBrowser.getWindow();
    // set up the JS Bridging Functions
    browserWindow.DWPSDExtractCallJsBridgingFunction = function (funcName, argsObj) {
        if (funcName && DWPSDExtractBridge && DWPSDExtractBridge[funcName]) {
            dw.logDebugMsg("function called: " + funcName);
            DWPSDExtractBridge[funcName](argsObj);
        } else {
            dw.logDebugMsg("invalid function called: " + funcName + "\n" + funcName + " not defined in DWPSDExtractBridge");
        }
    };
}

//////////////////////////////////////////////////////////////////////////////////////////////
// Panel Utility Methods for Dw.
//

//--------------------------------------------------------------------
// FUNCTION:
//   loadString
//
// DESCRIPTION:
//	Loads a string from resource files. This is used for the dwBrowser
//	view to load resource strings.
//
// ARGUMENTS:
//  The string Id to be loaded
//
// RETURNS:
//  Localized string 
//--------------------------------------------------------------------
function loadString(str) {
    "use strict";
    if (str && str.length && str.length > 0) {
        return dw.loadString(str);
    }
    return "";
}

//--------------------------------------------------------------------
// FUNCTION:
//   hidePanel
//
// DESCRIPTION:
//  hides PSD extract panel if visible

// ARGUMENTS:
//  none
//
// RETURNS:
//  none
//--------------------------------------------------------------------

function hidePanel() {
    "use strict";
    if (dw.getFloaterVisibility("DWPSDExtract")) {
        gInitedUI = false;
        dw.toggleFloater("DWPSDExtract");
    }
}

//--------------------------------------------------------------------
// FUNCTION:
//   downloadPSDExtractAsset
//
// DESCRIPTION:
//  This function calls webapp for downloading
//  the asset for the current selection. This
//  function is called from Dreamweaver.

// ARGUMENTS:
//  filePath: The file to which the asset needs
//              to be extracted to.
//
// RETURNS:
//  none
//--------------------------------------------------------------------
function downloadPSDExtractAsset(filepath, layerIDs, fileFormat, imageEncodingQuality, extractInfoType, nonEncodedPath) {
    "use strict";
    var browserWindow = gBrowser.getWindow();

    // set up the JS Bridging Functions
    browserWindow.dwPSDExtractManager.downloadPSDExtractAsset(filepath, layerIDs, fileFormat, imageEncodingQuality, extractInfoType, nonEncodedPath);
}

//--------------------------------------------------------------------
// FUNCTION:
//   getSelectedCSSFromPopup
//
// DESCRIPTION:
//  This function extracts selected CSS properties from the selection  
//  pop up and returns a formatted combined string containing all CSS properties.

// ARGUMENTS:
//  includeWebkitGrad: whether to include webkit gradients in the css string.
//  includeMozGrad   : whether to include mozilla gradients in the css string.
//  includeOGrad     : whether to include opera gradients in the css string.
//  shouldFormatCode : should the CSS String be formatted with \t and \n.
//
// RETURNS:
//  string containing all the selected css properties.
//--------------------------------------------------------------------
function getSelectedCSSFromPopup(includeWebkitGrad, includeMozGrad, includeOGrad, shouldFormatCode) {
    "use strict";
    var browserWindow = gBrowser.getWindow();

    // set up the JS Bridging Functions
    return browserWindow.dwPSDExtractManager.getSelectedCSSFromPopup(includeWebkitGrad, includeMozGrad, includeOGrad, shouldFormatCode);
}
