
function onLoaded() {

    //PSSelectEvent code
    var psSelectEvent = new PSSelectEvent();
    psSelectEvent.start(function()
	{
		//code below this line is called when a selection is active
		document.getElementById("activeSelectionImg").style.visibility = "visible";
		
	},function()
	{
		//code below this line is called when a selection is inactive
		document.getElementById("activeSelectionImg").style.visibility = "hidden";
	});

    var csInterface = new CSInterface();
	
    
    var appName = csInterface.hostEnvironment.appName;
    
    if(appName != "FLPR"){
    	loadJSX();
    }    
    
    var appNames = ["PHXS"];
    for (var i = 0; i < appNames.length; i++) {
        var name = appNames[i];
        if (appName.indexOf(name) >= 0) {
           var btn = document.getElementById("btn_" + name);
           if (btn)
                btn.disabled = false;
        }
    }
    

    var psActionSetLoader = new PSActionSetLoader(csInterface,false);
    psActionSetLoader.loadAction("actionsets/","TK-V4-Actions.atn","Copyright 2014 Tony Kuyper");

    
    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);
    
    // if there is not a local variable already saved, then these set the default values. 
	if (localStorage.PSpixelDimension){} else { localStorage.PSpixelDimension = "100"; }
	if (localStorage.PSopacitySetting){} else  { localStorage.PSopacitySetting = "50"; }
	// note:  Local storage is only stored as strings, so I need to convert these to bool in order to read them in. 
	if (localStorage.radio1Bool) {} else  { localStorage.radio1Bool = "true"; }
	if (localStorage.radio2Bool) {} else  { localStorage.radio2Bool = "false";}
	if (localStorage.radio3Bool) {} else  { localStorage.radio3Bool = "false";}
	
	$("#tonyswebsite").click(function()
	        {
	            csInterface.openURLInDefaultBrowser('http://www.goodlight.us/writing/actionspanelv4/help-and-user-guides.html');
	        });
	
}



/**
 * 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;
	    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) + ");";
	    } 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) + ");";
	    }
	    
	
	    //Update the default text style with pp values
	    
	    addRule(styleId, ".default", "font-size:" + appSkinInfo.baseFontSize + "px" + "; color:" + fontColor + "; background-color:" + toHex(panelBackgroundColor) + ";");
	    addRule(styleId, "button, select, input[type=text], input[type=button], input[type=submit]", borderColor);    
	    addRule(styleId, "button, select, input[type=button], input[type=submit]", gradientBg);    
	    addRule(styleId, "button, select, input[type=button], input[type=submit]", boxShadow);
	    addRule(styleId, "button:enabled:active, input[type=button]:enabled:active, input[type=submit]:enabled:active", gradientHighlightBg);
	    addRule(styleId, "button:enabled:active, input[type=button]:enabled:active, input[type=submit]:enabled: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);
}

function onClickButton(ppid) {
    if(ppid == "FLPR"){
    	var jsfl = 'fl.createDocument(); fl.getDocumentDOM().addNewText({left:100, top:100, right:300, bottom:300} , "Hello Flash!" ); ';
    	evalScript(jsfl);
    } else {
    	var extScript = "$._ext_" + ppid + ".run()";
		evalScript(extScript);
	}
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//These are Specific functions that run based on buttons. 
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////



//This script looks at the radio buttons and determines which one is selected. 
//the "sGroupName" is the group of radio buttons that we are going to loop through. 
function checkedRadioBtn(sGroupName)
{   
// this sets the group to an array that is a list of all the names of the items in the sGroupName
var group = document.getElementsByName(sGroupName);
// because its an array now, I can look at every item in the list one by one with a for statement. 
for ( var i = 0; i < group.length; i++) {
	// if the "checked" variable for that item is true... then return that item. (because its a radio button group, only one item in the group can be true, so this works.) 
 if (group.item(i).checked) 
 {
 	// return the id name of the item that was true.  so I can use that name in the main JSX script. 
     return group.item(i).id;
 } 
}
}

//handy dandy trusty string to boolean function. (you might recognize this. ;)
function stringToBoolean(string)
{
switch(string.toLowerCase()){
	case "true": case "yes": case "1": return true;
	case "false": case "no": case "0": case null: return false;
	default: return Boolean(string);
}
}

$(function() {

// gets the values in local storage, so when the window opens, the values default to whatever was last saved. 
document.getElementById("PxDimension").value=localStorage.getItem("PSpixelDimension");
document.getElementById("opacity").value=localStorage.getItem("PSopacitySetting");
// convert string local stored values to boolean for reading as radio button checked values.
document.getElementById("radio1").checked=stringToBoolean(localStorage.getItem("radio1Bool"));
document.getElementById("radio2").checked=stringToBoolean(localStorage.getItem("radio2Bool"));
document.getElementById("radio3").checked=stringToBoolean(localStorage.getItem("radio3Bool"));

// this is the "onClick" command for the button. 
$( "#Ok_btn" ).click(function() 
{
	// find which radio button is selected in group. 
	var getSelectedRadio = checkedRadioBtn("radio");  
	// extract whatever values are in the edit text boxes
	var PSpixelDimension = $( "#PxDimension" ).val();
	var PSopacitySetting = $( "#opacity" ).val();
	
	// re-saves the values to local storage for next time the window is opened.  
	localStorage.PSpixelDimension = PSpixelDimension;
	localStorage.PSopacitySetting = PSopacitySetting;
	// even though this value is a boolean, it will save as a string in the local storage. 
	localStorage.radio1Bool = document.getElementById("radio1").checked;
	localStorage.radio2Bool = document.getElementById("radio2").checked;
	localStorage.radio3Bool = document.getElementById("radio3").checked;
 	
	// build a string that is the name of the function you want to run in the JSX file. 
	var PSrunSharpen = "ext_runSharpen('" + PSpixelDimension + "','" + PSopacitySetting + "','" + getSelectedRadio + "')";
	// run the command in the JSX file.  (Photoshop DOES the work!) 
	evalScript(PSrunSharpen);
});

}); 

$(function() {
	$( document ).tooltip();
	});
	 
$(function() {
	 $( "#tabs" ).tabs();
	 });