
var allSliders = {
	"cyan":true,
	"magenta":true,
	"yellowColor":true,
	"black":true	
};

var rawParams = {
	"tint":"Tint",
    "temperature":"Temp",
	"hue":"HA",
	"saturation":"SA",
	"luminance":"LA"
}

var colorSliders = {
	"blacks":true,
	"whites":true,
	"neutrals":true	
};

var allActions = 
[
"Alabaster",
"All The Blues",
"Black and White Intense",
"Bright Star",
"Cinematic Blue",
"Cinematic Green",
"Cold Shadows",
"Colour Shine",
"Country Road",
"Dark and Moody",
"Deep Dark Wood",
"Deep Sky",
"Deep Vintage",
"Ercu",
"Fall Arrived",
"Foggy Night",
"Frostbite",
"Gothic City",
"Highlights Punch",
"Hint Of Pink",
"Illuminate",
"Intense Contrast",
"Kunzite",
"Light White",
"Liquorice",
"Mellow Yellow",
"Moody Oak",
"Neutral Plateau",
"Original",
"Pink Dawn",
"Polaroid",
"Purple Rain",
"Rich",
"Skin Glow",
"Softer Colours",
"Tranquil",
"Uranus",
"Warm Beach",
"Warm Highlights",
"Yoke"];

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');
        
       $( "#actionsDD" ).select2({placeholder: "Actions", minimumResultsForSearch: Infinity});
      
        

     //   csInterface.addEventListener("rayaPro5BlendResetSliders", function(event){
    //		resetSliders();
    //    });
        
        
        // Create a new Event
       var event = new CSEvent("com.adobe.PhotoshopRegisterEvent", "APPLICATION");

        // Set Event properties: extension id
        event.extensionId = extId;

        // Set Event properties: data (as Type ID string, comma separated)
        // 1668247673 = charIDToTypeID( "copy" ) = copy
        // 1885434740 = charIDToTypeID( "past" ) = paste
        // 1668641824 = charIDToTypeID( "cut " ) = cut
        
  //      PSEvent.SELECT = "1936483188";
//PSEvent.SET = "1936028772";
        
        //set, close, open, select
        //event.data = "1936028772, 1332768288, 1131180832, 1936483188, 1298866208";
     //   event.data = "1332768288, 1131180832, 1936483188, 1298866208";
event.data = "1936483188";
        // Dispatch the Event
        csInterface.dispatchEvent(event);

        // Attach a callback
      //  csInterface.addEventListener("PhotoshopCallback", PSCallback);
        csInterface.addEventListener("com.adobe.PhotoshopJSONCallback" + extId, PSCallback);
        
    
        
        evalScript("$._ext_PHXS.getOpacity();", setOpacity);
	
    	var rawColor = getChecked("colorMixerRadio");
        var selColor = getChecked("selectiveColorRadio");
    
        evalScript("$._ext_PHXS.getAllParams(\""+rawColor+"\",\""+selColor+"\");", setAllParams);
}


/**
 * 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;
    panelBackgroundColor.green = 47;
    panelBackgroundColor.red = 47;
    panelBackgroundColor.blue = 47;
    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, 20) + " , " + toHex(panelBackgroundColor, 5) + ");";
	    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.3), 0 1px 1px rgba(0, 0, 0, 0.1);";
	    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 = "#333333;";
	    	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 = "#bbbbbb;";
	    	disabledFontColor = "color:" + toHex(panelBackgroundColor, 100) + ";";
	    	borderColor = "border-color: " + toHex(panelBackgroundColor, -45) + ";";
	    	inputBackgroundColor = toHex(panelBackgroundColor, -20) + ";";
	    	gradientHighlightBg = "background-image: -webkit-linear-gradient(top, " + toHex(panelBackgroundColor, -30) + " , " + toHex(panelBackgroundColor, -40) + ");";
            buttonHoverBg = "background-image: -webkit-linear-gradient(top, " + toHex(panelBackgroundColor, 50) + " , " + toHex(panelBackgroundColor, 20) + ");";
           
	    }
        

	    

        
    
	    //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-10) + ";");
	    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;");
	

    
	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 setOpacity(opacity)
{
    if(opacity==undefined || opacity=="undefined") opacity = 0;
	document.querySelector("#strengthSlider").value = Number(opacity);
	document.querySelector("#strengthSliderValue").textContent = opacity.toString();
}

function setAllParams(data)
{
 
    try{
    var data = JSON.parse(data);
    if(data.sel)
	for(var prop in colorSliders)
	{
		document.querySelector("#"+prop+"Slider").value = data.sel[prop];
		document.querySelector("#"+prop+"SliderValue").textContent = data.sel[prop].toString();
	}
    if(data.raw)
	for(var prop in rawParams)
	{
		document.querySelector("#"+prop+"Slider").value = data.raw[prop];
		document.querySelector("#"+prop+"SliderValue").textContent = data.raw[prop].toString();
	}
}catch(e){}
}

function setRawParams(data)
{
 
var data = JSON.parse(data);
	for(var prop in rawParams)
	{
        if(data[prop]==undefined) continue;
		document.querySelector("#"+prop+"Slider").value = data[prop];
		document.querySelector("#"+prop+"SliderValue").textContent = data[prop].toString();
	}
 
}

function setSelParams(data)
{
 var data = JSON.parse(data);
	for(var prop in colorSliders)
	{
         if(data[prop]==undefined) continue;
		document.querySelector("#"+prop+"Slider").value = data[prop];
		document.querySelector("#"+prop+"SliderValue").textContent = data[prop].toString();
	}
	
 
}

function PSCallback(event)
{ 

   var d = JSON.parse(event.data.substr(5));
   var targetName = d.eventData["null"]._name;
    
    
	if(targetName=="Colorizer Grading") 
	{
        
          evalScript("$._ext_PHXS.getOpacity();", setOpacity);
		
		return;
	}
	
	
	
	if(targetName!="Colorize") 
	{
		//deactivate sliders?
		return;
	}
	
	var rawColor = getChecked("colorMixerRadio");
    var selColor = getChecked("selectiveColorRadio");
    
    evalScript("$._ext_PHXS.getAllParams(\""+rawColor+"\",\""+selColor+"\");", setAllParams);


}


function colorMixerColorChanged(color)
{
	evalScript("$._ext_PHXS.getRawParams(\""+color+"\");", setRawParams);

}

function selectiveColorChanged(color)
{
	evalScript("$._ext_PHXS.getSelParams(\""+color+"\");", setSelParams);
	
}

function deactivateSliders()
{    
    $("#darkGreySlider").prop('disabled', true);

}

function activateSliders()
{
    $("#darkGreySlider").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 runActionFromSet(set, action) {
	 
	var extScript = "$._ext_PHXS.runAction(\""+set+"\",\""+action+"\")";
	
	evalScript(extScript);

}

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

}

function urlClick(url)
{
	var csInterface = new CSInterface();
	csInterface.openURLInDefaultBrowser(url);
}

function runRandomAction()
{

	document.querySelector("#strengthSlider").value = 100;
	document.querySelector("#strengthSliderValue").textContent = 100;
	var index = Math.floor(allActions.length*Math.random());
	runAction(allActions[index]);
}

function runActionPressed()
{

   
	
	document.querySelector("#strengthSlider").value = 100;
	document.querySelector("#strengthSliderValue").textContent = 100;
	runAction(document.querySelector("#actionsDD").value);
}


function uncheckAll(id)
{
	$("#"+id).children().removeClass("checked");
}

function getChecked(id)
{
	return $("#"+id).children(".checked").first().attr("name");
	
}




function resetSliders()
{
	
	for(var prop in colorSliders)
	{
		document.querySelector("#"+prop+"Slider").value = 0;
		document.querySelector("#"+prop+"SliderValue").textContent = "0";
	}
	for(var prop in rawParams)
	{
		document.querySelector("#"+prop+"Slider").value = 0;
		document.querySelector("#"+prop+"SliderValue").textContent = "0";
	}
}

function resetColorSliders()
{
	
	for(var prop in colorSliders)
	{
		document.querySelector("#"+prop+"Slider").value = 0;
		document.querySelector("#"+prop+"SliderValue").textContent = "0";
	}
}




function colorize(){
	resetSliders();
    evalScript("$._ext_PHXS.colorize();");
	
	
}

function updateSliderValue(slider)
{
	var value = document.querySelector("#"+slider+"Slider").value;
	if(!value) value = 0;				
	document.querySelector("#"+slider+"SliderValue").textContent = value.toString();
    return value;
}

function updateRaw(slider)
{
	var value = updateSliderValue(slider);
    
	var paramName = rawParams[slider];
				
	if(slider!="tint" && slider!="temperature")
			paramName+="_"+getChecked("colorMixerRadio");
			
	 evalScript("$._ext_PHXS.updateRaw(\""+paramName+"\","+value+");");
  
}

function updateSelective(slider)
{
    var value = updateSliderValue(slider);
    
    var color = getChecked("selectiveColorRadio");
    
	 evalScript("$._ext_PHXS.updateSelective(\""+color+"\",\""+slider+"\","+value+");");
     
}

function updateStrength()
{
    var value = updateSliderValue("strength");
    evalScript("$._ext_PHXS.updateStrength("+value+");");

}