
/////////////////////////////////////////////////////////////
//  Created by Zetta LLC @ AdobeScripting.com              //
//  Northfield MN, USA  Ph: 952-232-0211                   //
//  Email: Info@AdobeScripting.com                         //
//  Copyright: (c) 2015 Zetta LLC                          //
//  Authors:  Sandra Voelker   sandra@AdobeScripting.com   //
//            Sam Gannaway     sam@AdobeScripting.com      //
//  Original Creation date: February  2015                 //
/////////////////////////////////////////////////////////////


function onLoaded() {
    var csInterface = new CSInterface();
    updateThemeWithAppSkinInfo(csInterface.hostEnvironment.appSkinInfo);
    // Update the color of the panel when the theme color of the product changed.
    csInterface.addEventListener(CSInterface.THEME_COLOR_CHANGED_EVENT, onAppThemeColorChanged);
    csInterface.setContextMenu('<menu></menu>', function () {});

    // workaround for Mac font boldness
//    if(navigator.userAgent.search("Macintosh") != -1)
//        $("button:contains('Tone: Silver Gelatin')").css("font-size", '9px');
	
    $(".toolIcon[data-function], button[data-function], .divAsButton[data-function]").click(function() 
        {
            console.log($(this).attr("data-function") );
            csInterface.evalScript($(this).attr("data-function"), function(msg) {console.log(msg);});
            if ($(this).hasClass("toolIcon"))
            {
                $(".toolIcon.activeTool").removeClass("activeTool");
                $(this).addClass("activeTool");
            }
        });

	    function unregisterPhotoshopEvent(in_eventId) 
	    {
	        var event = new CSEvent("com.adobe.PhotoshopUnRegisterEvent",
	                                "APPLICATION");
	        event.extensionId = csInterface.getExtensionID();
	        event.appId = csInterface.getApplicationID();
	        event.data = in_eventId;
	        csInterface.dispatchEvent(event);
	//console.log("Unregistered: "+in_eventId);
	    }
	

    // Liquify workaround
    $("button:contains('Liquify')").click( function() {
        csInterface.evalScript('popLiquify("' +csInterface.getSystemPath(SystemPath.EXTENSION) +'")', function(msg) {console.log("Liquify: "+msg);});
    });

    // EVENTS

    unregisterPhotoshopEvent("1936483188");
    
    function registerPhotoshopEvent(in_eventId) 
    {
        var event = new CSEvent("com.adobe.PhotoshopRegisterEvent",
                                "APPLICATION");
        event.extensionId = csInterface.getExtensionID();
        event.appId = csInterface.getApplicationID();
        event.data = in_eventId;
        csInterface.dispatchEvent(event);
//console.log("Registered: "+in_eventId);
    }

        window.setTimeout( function() {registerPhotoshopEvent("1936483188");}, 100);      // select event

        csInterface.addEventListener("PhotoshopCallback" , function(event) 
            {
                var ids = event.data.split(',');
                var eventID = ids[0];
                var descID = ids[1];
                if (eventID == "1936483188")
                {
                    $(".toolIcon.activeTool").removeClass("activeTool");
                    csInterface.evalScript('getToolCharStringID('+ descID +')', function(msg) 
                        {
                            var msgParts = msg.split(',');
                            var charID = msgParts[0];
                            var stringID = msgParts[1];
                            console.log((".ps_tool[data-toolID='"+ charID +"'][data-idType='charID']") + " : "+ (".ps_tool[data-toolID='"+ stringID +"'][data-idType='stringID']"))
                            if(charID != null && charID != 'null' && charID != '')
                                $(".toolIcon[data-toolID='"+ charID +"'][data-idType='charID']").addClass("activeTool");
                            else if(stringID != null && stringID != 'null' && stringID != '')
                                $(".toolIcon[data-toolID='"+ stringID.trim() +"'][data-idType='stringID']").addClass("activeTool");
                            console.log(msg);
                        });
                }
            });

}


/**
 * Update the theme with the AppSkinInfo retrieved from the host product.
 */
function updateThemeWithAppSkinInfo(appSkinInfo) {
	
    //Update the background color of the panel
    var panelBackgroundColor = appSkinInfo.panelBackgroundColor.color;
    document.body.bgColor = toHex(panelBackgroundColor);
        
    var styleId = "ppstyle";
    
    var csInterface = new CSInterface();
	var appName = csInterface.hostEnvironment.appName;
    
    if(appName == "PHXS"){
	    addRule(styleId, "button, select, input[type=button], input[type=submit]", "border-radius:3px;");
	}
	if(appName == "PHXS" || appName == "PPRO" || appName == "PRLD") {
		////////////////////////////////////////////////////////////////////////////////////////////////
		// NOTE: Below theme related code are only suitable for Photoshop.                            //
		// If you want to achieve same effect on other products please make your own changes here.    //
		////////////////////////////////////////////////////////////////////////////////////////////////
		
	    
	    var gradientBg = "background-image: -webkit-linear-gradient(top, " + toHex(panelBackgroundColor, 40) + " , " + toHex(panelBackgroundColor, 10) + ");";
	    var gradientDisabledBg = "background-image: -webkit-linear-gradient(top, " + toHex(panelBackgroundColor, 15) + " , " + toHex(panelBackgroundColor, 5) + ");";
	    var boxShadow = "-webkit-box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.4), 0 1px 1px rgba(0, 0, 0, 0.2);";
	    var boxActiveShadow = "-webkit-box-shadow: inset 0 1px 4px rgba(0, 0, 0, 0.6);";
	    
	    var isPanelThemeLight = panelBackgroundColor.red > 127;
	    var fontColor, disabledFontColor;
	    var borderColor;
	    var inputBackgroundColor;
	    var gradientHighlightBg;
        var buttonHoverBg;
		
	    if(isPanelThemeLight) {
	    	fontColor = "#000000;";
	    	disabledFontColor = "color:" + toHex(panelBackgroundColor, -70) + ";";
	    	borderColor = "border-color: " + toHex(panelBackgroundColor, -90) + ";";
	    	inputBackgroundColor = toHex(panelBackgroundColor, 54) + ";";
	    	gradientHighlightBg = "background-image: -webkit-linear-gradient(top, " + toHex(panelBackgroundColor, -40) + " , " + toHex(panelBackgroundColor,-50) + ");";
            buttonHoverBg = "background-image: -webkit-linear-gradient(top, " + toHex(panelBackgroundColor, 20) + " , " + toHex(panelBackgroundColor, -10) + ");";
            $(".ps_tool").attr("src", function() {return "images/"+ $(this).attr("data-icon")+"\.png"});
            $("img[src='images/ps_action_D.png']").attr("src", "images/ps_action.png")
	    } else {
	    	fontColor = "#dddddd;";
	    	disabledFontColor = "color:" + toHex(panelBackgroundColor, 100) + ";";
	    	borderColor = "border-color: " + toHex(panelBackgroundColor, -45) + ";";
	    	inputBackgroundColor = toHex(panelBackgroundColor, -20) + ";";
	    	gradientHighlightBg = "background-image: -webkit-linear-gradient(top, " + toHex(panelBackgroundColor, -20) + " , " + toHex(panelBackgroundColor, -30) + ");";
            buttonHoverBg = "background-image: -webkit-linear-gradient(top, " + toHex(panelBackgroundColor, 60) + " , " + toHex(panelBackgroundColor, 30) + ");";
            $(".ps_tool").attr("src", function() {return "images/"+ $(this).attr("data-icon")+"_D\.png"});
            $("img[src='images/ps_action.png']").attr("src", "images/ps_action_D.png")
	    }
	    
	
	    //Update the default text style with pp values
	    
//	    addRule(styleId, ".default", "font-size:" + (appSkinInfo.baseFontSize+1) + "px" + "; color:" + fontColor + "; background-color:" + toHex(panelBackgroundColor) + ";");
	    addRule(styleId, ".default, button, .divAsButton", "font-size:11px" + "; color:" + fontColor + "; background-color:" + toHex(panelBackgroundColor) + ";");
	    addRule(styleId, "button, select, input[type=text], input[type=button], input[type=submit], .divAsButton", borderColor);    
	    addRule(styleId, "button, select, input[type=button], input[type=submit], .divAsButton", gradientBg);    
	    addRule(styleId, "button, select, input[type=button], input[type=submit], .divAsButton", boxShadow);
	    addRule(styleId, "button:hover, .divAsButton:hover", buttonHoverBg);    
	    addRule(styleId, "button:enabled:active, input[type=button]:enabled:active, input[type=submit]:enabled:active, .divAsButton:active", gradientHighlightBg);
	    addRule(styleId, "button:enabled:active, input[type=button]:enabled:active, input[type=submit]:enabled:active, .divAsButton:active", boxActiveShadow);
	    addRule(styleId, "[disabled]", gradientDisabledBg);
	    addRule(styleId, "[disabled]", disabledFontColor);
	    addRule(styleId, "input[type=text]", "padding:1px 3px;");
	    addRule(styleId, "input[type=text]", "background-color: " + inputBackgroundColor) + ";";
	    addRule(styleId, "input[type=text]:focus", "background-color: #ffffff;");
	    addRule(styleId, "input[type=text]:focus", "color: #000000;");
	    
	} else {
		// For AI, ID and FL use old implementation	
		addRule(styleId, ".default", "font-size:" + appSkinInfo.baseFontSize + "px" + "; color:" + reverseColor(panelBackgroundColor) + "; background-color:" + toHex(panelBackgroundColor, 20));
	    addRule(styleId, "button", "border-color: " + toHex(panelBgColor, -50));
	}
}

function addRule(stylesheetId, selector, rule) {
    var stylesheet = document.getElementById(stylesheetId);
    
    if (stylesheet) {
        stylesheet = stylesheet.sheet;
           if( stylesheet.addRule ){
               stylesheet.addRule(selector, rule);
           } else if( stylesheet.insertRule ){
               stylesheet.insertRule(selector + ' { ' + rule + ' }', stylesheet.cssRules.length);
           }
    }
}


function reverseColor(color, delta) {
    return toHex({red:Math.abs(255-color.red), green:Math.abs(255-color.green), blue:Math.abs(255-color.blue)}, delta);
}

/**
 * Convert the Color object to string in hexadecimal format;
 */
function toHex(color, delta) {
    function computeValue(value, delta) {
        var computedValue = !isNaN(delta) ? value + delta : value;
        if (computedValue < 0) {
            computedValue = 0;
        } else if (computedValue > 255) {
            computedValue = 255;
        }

        computedValue = computedValue.toString(16);
        return computedValue.length == 1 ? "0" + computedValue : computedValue;
    }

    var hex = "";
    if (color) {
        with (color) {
             hex = computeValue(red, delta) + computeValue(green, delta) + computeValue(blue, delta);
        };
    }
    return "#" + hex;
}

function onAppThemeColorChanged(event) {
    // Should get a latest HostEnvironment object from application.
    var skinInfo = JSON.parse(window.__adobe_cep__.getHostEnvironment()).appSkinInfo;
    // Gets the style information such as color info from the skinInfo, 
    // and redraw all UI controls of your extension according to the style info.
    updateThemeWithAppSkinInfo(skinInfo);
} 



    
/**
 * Load JSX file into the scripting context of the product. All the jsx files in 
 * folder [ExtensionRoot]/jsx will be loaded. 
 */
function loadJSX() {
    var csInterface = new CSInterface();
    var extensionRoot = csInterface.getSystemPath(SystemPath.EXTENSION) + "/jsx/";
    csInterface.evalScript('$._ext.evalFiles("' + extensionRoot + '")');
}

function evalScript(script, callback) {
    new CSInterface().evalScript(script, callback);
}

