var _fuzziness = 100;
var _fuzStep = 20;

function onLoaded() {
	
    var csInterface = new CSInterface();
    var extId = csInterface.getExtensionID();
    var extPath = csInterface.getSystemPath(SystemPath.EXTENSION);
    var appDataPath = csInterface.getSystemPath(SystemPath.USER_DATA);
    var userExtPath = appDataPath + '/Adobe/CEP/extensions/' + extPath.match(/[^\/]+$/);
    var osInfo = csInterface.getOSInformation();
    var osName = osInfo.substring(0, "Windows".length) == "Windows" ? "Windows" : "Mac";
	
	loadJSX();
	
	var eventPersistent = new CSEvent("com.adobe.PhotoshopPersistent","APPLICATION");
	eventPersistent.extensionId = extId;
	csInterface.dispatchEvent(eventPersistent);
    
    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 () {});		// disable default context menu
    
        $('.ui-corner-all').removeClass('ui-corner-all');
        

}


/**
 * 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;
    
    
	    addRule(styleId, "button, select, input[type=button], input[type=submit]", "border-radius:3px;");
	
	    
	    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) + ");";
           
	    } else {
	    	fontColor = "#ffffff;";
	    	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) + ");";
           
	    }
        

	    
        var orangeBackgroundBg = "background-image: -webkit-linear-gradient(top, " + "#DF3A01" + " , " + "#DF3A01" + ");";
        var blueBackgroundBg = "background-image: -webkit-linear-gradient(top, " + "#1c79f7" + " , " + "#1c79f7" + ");";
	    var greenBackgroundBg = "background-image: -webkit-linear-gradient(top, " + "#0B610B" + " , " + "#0B610B" + ");";
        var redBackgroundBg = "background-image: -webkit-linear-gradient(top, " + "#8A0808" + " , " + "#8A0808" + ");";
        
    
	    //Update the default text style with pp values
	    addRule(styleId, ".fontColor, .ui-state-default a, .ui-state-default a:link, .ui-state-default a:visited", "color:" + fontColor + ";");
	    addRule(styleId, ".default, .divAsButton", "font-size:11px" + "; color:" + fontColor + "; background-color:" + toHex(panelBackgroundColor) + ";");
        addRule(styleId, "button", "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;");
	    addRule(styleId, ".darkBgText", "background-color: "+ toHex(panelBackgroundColor, -45) + ";");
		addRule(styleId, "select","color:"+fontColor+"!important; background-color:" + inputBackgroundColor + "!important;background:" + inputBackgroundColor + "!important;");
		addRule(styleId, "option","background-color:" + inputBackgroundColor + "!important;background:" + inputBackgroundColor + "!important;");
	
		addRule(styleId, ".blueButton, .blueButton:hover",blueBackgroundBg);
    addRule(styleId, ".orangeButton, .orangeButton:hover",orangeBackgroundBg);
    addRule(styleId, ".greenButton, .greenButton:hover",greenBackgroundBg);
    addRule(styleId, ".redButton, .redButton:hover",redBackgroundBg);
    
	if(isPanelThemeLight)
	{
		$("#uitheme").attr('href', "css/jquery-ui.theme-light.css");
	} else
	{
		$("#uitheme").attr('href', "css/jquery-ui.theme-dark.css");
	} 		
	
	
}

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);
}

function resetSliders()
{
    $("#shadowsSlider").val(0);
    $("#midtoneSlider").val(50);
    $("#highlightsSlider").val(255);
    
    $("#shadowsSliderValue").text(0);
    $("#midtoneSliderValue").text(50);
    $("#highlightsSliderValue").text(255);
    
}

function updateSliderValues()
{    
    $("#shadowsSliderValue").text($("#shadowsSlider").val());
    $("#midtoneSliderValue").text($("#midtoneSlider").val());
    $("#highlightsSliderValue").text($("#highlightsSlider").val());
    
    runScript('updateMaskLevels', "["+[$("#shadowsSlider").val(),$("#midtoneSlider").val(),$("#highlightsSlider").val()].join(",")+"]");
}

function createLuminosityMask()
{
    resetFuzziness();
    runScript('LuminosityMask',_fuzziness);
}

function createColorRangeMask()
{
    resetFuzziness();
    runScript('ColorRangeMask',_fuzziness);
}

function decreaseLuminosityMaskFuzziness()
{
    decreaseFuzziness();
    runScript('DecreaseLuminosityMaskFuzziness',_fuzziness);
}

function increaseLuminosityMaskFuzziness()
{
    increaseFuzziness();
    runScript('IncreaseLuminosityMaskFuzziness',_fuzziness);
}

function decreaseColorMaskFuzziness()
{
    decreaseFuzziness();
    runScript('DecreaseColorMaskFuzziness',_fuzziness);
}

function increaseColorMaskFuzziness()
{
    increaseFuzziness();
    runScript('IncreaseColorMaskFuzziness',_fuzziness);
}

  
function resetFuzziness()
{
    _fuzziness = 100;
    $("#increaseColButton").prop("disabled",false);
    $("#increaseLumButton").prop("disabled",false);
    
    $("#decreaseColButton").prop("disabled",false);
    $("#decreaseLumButton").prop("disabled",false);
    
}

function increaseFuzziness()
{
    _fuzziness += _fuzStep;
    $("#decreaseColButton").prop("disabled",false);
    $("#decreaseLumButton").prop("disabled",false);
    
    if(_fuzziness>=200)
    {
        _fuzziness = 200;
        $("#increaseColButton").prop("disabled",true);
        $("#increaseLumButton").prop("disabled",true);
    }
    else
    {
        $("#increaseColButton").prop("disabled",false);
        $("#increaseLumButton").prop("disabled",false);
    }
}

function decreaseFuzziness()
{
    _fuzziness -= _fuzStep;
    $("#increaseColButton").prop("disabled",false);
    $("#increaseLumButton").prop("disabled",false);
    
    if(_fuzziness<=0)
    {
        _fuzziness = 0;
        $("#decreaseColButton").prop("disabled",true);
        $("#decreaseLumButton").prop("disabled",true);
    }
    else
    {
        $("#decreaseColButton").prop("disabled",false);
        $("#decreaseLumButton").prop("disabled",false);
    }
}



function runScript(func, arg) {
	 
	var extScript;
	 
	if(arg!=undefined) 
		extScript = "$._ext_PHXS.runScript(\""+func+"\","+arg+")";
	else
		extScript = "$._ext_PHXS.runScript(\""+func+"\")";
	
	evalScript(extScript);

}

function runAction(set, action) {
	 
	var extScript = "$._ext_PHXS.runAction(\""+set+"\",\""+action+"\")";
	
	evalScript(extScript);

}

function urlClick(url)
{
	var csInterface = new CSInterface();
	csInterface.openURLInDefaultBrowser("http://"+url);
}

