﻿var csxsapp;
var log = getLogFile();
var assetsPath = null;
var extensionID = "";

var contentPlacerNames = ["Content Placer Tool",                  //enUS,enGB
                          "Nástroj pro umístění obsahu",          //csCZ
                          "内容置入器工具",                        //zhCN,zhTW
                          "Værktøjet Indholdsindsættelse",        //dadK
                          "Inhaltsplatzierung-Werkzeug",          //deDE
                          "Herramienta Colocador de contenido",   //esES
                          "Sisällön sijoitustyökalu",             //fiFI
                          "Outil Importation de contenu",         //frFR
                          "Tartalomelhelyező",                    //huHU
                          "Strumento inserimento contenuti",      //itIT
                          "コンテンツ配置ツール",                   //jaJP
                          "내용 배치 도구",                        //koKR
                          "Innholdsplasseringsverktøy",           //nbNO
                          "Inhoud plaatsen",                      //nlNL
                          "Narzędzie Umieszczanie zawartości",    //plPL
                          "Ferramenta Posicionador de conteúdo",  //ptBR
                          "Инструмент \"Поместить содержимое\"",  //ruRU
                          "Verktyget Innehållsmontering",         //svSe
                          "İçerik Yerleştirici Aracı",            //trTR
                          "Інструмент “Поміщення вмісту”"         //ukUA
                        ];


var contentCollectorNames = ["Content Collector Tool",                 //enUS,enGB
                             "Nástroj pro nasbírání obsahu",           //csCZ
                             "Værktøjet Indholdsindsamling",           //daDK
                             "Inhaltsaufnahme-Werkzeug",               //deDE
                             "内容收集器工具",                          //zhCN,zhTW
                             "Herramienta Recopilador de contenido",  //esES
                             "Sisällön keräystyökalu",                 //fiFI
                             "Outil Récupérateur de contenu",          //frFR
                             "Tartalomgyűjtő",                         //huHU
                             "Strumento raccolta contenuti",           //itIT
                             "コンテンツ収集ツール",                     //jaJP
                             "내용 수집 도구",                          //koKR
                             "Innholdsinnsamlingsverktøy",             //nbNO
                             "Inhoud verzamelen",                      //nlNL
                             "Narzędzie Kolektor zawartości",          //plPL
                             "Ferramenta Coletor de conteúdo",         //ptBR
                             "Инструмент \"Собрать содержимое\"",      //ruRU
                             "Verktyget Innehållssamling",             //svSE
                             "İçerik Toplayıcı Aracı",                 //trTR
                             "Інструмент “Колектор вмісту”"           //ukUA
                            ];
// Unlike other tools, "Content Collector Tool" and "Content Placer Tool" share the same action ID (140289). 
// Executing the action ID results in tool box toggles between these two tools.
// To have identical behaviors with other tools, I have to give these two tools fake IDs and map them to the real one programmatically.	
// See http://redmine.eur.adobe.com/issues/3864 for more information.
var fakeContentPlacerID = 9999998;
var fakeContentCollectorID = 9999999;
var realContentDropperID = 140289;

// The DPS extensions are not included in the InDesign installation footprint. As a result the user will need to install
// the DPS extension bundle separately and therefore a unique ActionID will be allocated to the two extensions. This can
// differ between installations. As a result, we will attempt to invoke the menu action by searching by menu name as opposed
// to action ID. 
// See http://redmine.eur.adobe.com/issues/3967 for more information.
var folioBuilderExtensionName = "Folio Builder";
var fakeFolioBuilderID = 9999997;
var folioOverlaysExtensionName = "Folio Overlays";
var fakeFolioOverlaysID = 9999996;
//---------------------------
function onPanelInit(){}

//---------------------------
function onPanelClose(){}

//---------------------------
function onPanelHide(){}

//---------------------------
function onPanelShow(){}

//---------------------------
function setExtensionID(id)
{
    extensionID = id;
}

// called by the AS code
function registerAppObject(appObj) {
    csxsapp = appObj;
}

function supportSwfInHtml() 
{
	return '<object><property id="support"><string>false</string></property></object>';
}

//---------------------------
function invoke_script_file(filepath) {
  	  var strXMLResult = '<object><property id="bSuccess">';

	try {
		strXMLResult += '<true/></property>';
		strXMLResult += '<property id="strError"><string></string></property>';
        var scriptFile =  decode (filepath);
        writelog("invoke script file " + scriptFile);
		var f = new File(scriptFile);
	    if (f.exists) {
			$.evalFile(f, 300000);
	    } else {
	  	alert("File does not exist: " + scriptFile);
	    }
	}catch(err){
		alert(err);
		strXMLResult = '<object><property id="bSuccess">';
		strXMLResult += '<false/></property>';
		strXMlResult += '<property id="strError"><string></string></property>';
	}
	strXMLResult += '</object>';
	return strXMLResult;
};

//---------------------------
function invoke_function_in_script_file(filepath, ns, functionName, arguments) {
  	var strXMLResult = '<object><property id="bSuccess">';
	try {
		strXMLResult += '<true/></property>';
		strXMLResult += '<property id="strError"><string></string></property>';
        var scriptFile =  decode (filepath);
        writelog("invoke script file " + scriptFile);
        var args = decodeArrayString(arguments);
	    var f = new File(scriptFile);
	    if (f.exists) {
			$.evalFile(f, 300000);
			var scope = ns ? this[ns] : this;
			if (arguments) {
			    scope[functionName].call(null, args);
			} else {
			    scope[functionName].call(null);
			}
	    } else {
	  	    alert("File does not exist: " + scriptFile + " or invalid script file.");
	    }
	}catch(err){
		alert(err);
		strXMLResult = '<object><property id="bSuccess">';
		strXMLResult += '<false/></property>';
		strXMlResult += '<property id="strError"><string></string></property>';
	}
	strXMLResult += '</object>';
	return strXMLResult;
};

//---------------------------
function setAssetsPath(path, key)
{
    assetsPath = path;
    this["assetsPath_" + key] = path;
}

//---------------------------
function getAssetsPath()
{
    var mypath = $.fileName;
    writelog("my path =" + mypath);
    var myfile = new File(mypath);
    var folder = myfile.parent;
    var name = myfile.name;
    var index = name.lastIndexOf(".jsx");
    var name = name.substr(0, index);
    return folder.fsName + "/" + name + ".assets";
}

//---------------------------
function decode(s)
{
		var code = s.replace(/#0D;/g, "\n");
		code = code.replace(/#0A;/g, "\r");
		code = code.replace(/#22;/g, "\"");
		code = code.replace(/#27;/g, "'");
		code = code.replace(/#23;/g, "#");
        return code;
}

//---------------------------
function decodeArrayString(arrayString)
{
    var res = null;
    if ('' == arrayString) {
        res = [];
    } else if (arrayString) {
        res = [];
        try {
            var items = arrayString.split(',');
            for (var i = 0; i < items.length; i++) {
                res.push(decodeURIComponent(items[i]));
            }
        } catch (err) {
            alert('String ' + arrayString + ' cannot be decode into an array.');
        }
    }
    
    return res;
}

//---------------------------
function id_invoke_script(script)
{
	var strXMLResult = '<object><property id="bSuccess">';
	try
	{  
		strXMLResult += '<true/></property>';
		strXMLResult += '<property id="strError"><string></string></property>';
		writelog("-----------------------");
        var code = decode(script);
		writelog(code);
		writelog("-----------------------");		
		eval(code);
	}
	catch(err)
	{
		alert(err);
		strXMLResult = '<object><property id="bSuccess">';
		strXMLResult += '<false/></property>';
		strXMlResult += '<property id="strError"><string></string></property>';
	}
	strXMLResult += '</object>';
	return strXMLResult;
}

//---------------------------
function invoke_script(script)
{
    //have to make a copy, wrapped call cause problem
    var strXMLResult = '<object><property id="bSuccess">';
    try
    {  
        strXMLResult += '<true/></property>';
        strXMLResult += '<property id="strError"><string></string></property>';
        writelog("-----------------------");
        var code = decode(script);
        writelog(code);
        writelog("-----------------------");        
        eval(code);
    }
    catch(err)
    {
        alert(err);
        strXMLResult = '<object><property id="bSuccess">';
        strXMLResult += '<false/></property>';
        strXMlResult += '<property id="strError"><string></string></property>';
    }
    strXMLResult += '</object>';
    return strXMLResult;
}

//---------------------------
function id_invoke_command(id)
{
    writelog("invoke command " + id);
    var n = (new Number(id)).valueOf();

    if (n == fakeContentCollectorID || n == fakeContentPlacerID)
    {
    	var a = app.menuActions.itemByID(realContentDropperID);

    	a.invoke();
    	
    	var toolBox = app.toolBoxTools;
    	var currentToolName = toolBox.currentToolName;

    	if (n == fakeContentCollectorID)
    	{
			if (!isInArray(currentToolName, contentCollectorNames))
    		{
    			a.invoke();
    		}
    	}
    	else if (n == fakeContentPlacerID)
    	{
			if (!isInArray(currentToolName, contentPlacerNames))
    		{
    			a.invoke();
    		}
    	}
    }
    else if (n == fakeFolioBuilderID)
    {
        var a = app.menuActions.itemByName(folioBuilderExtensionName);
        a.invoke();
    }
    else if (n == fakeFolioOverlaysID)
    {
        var a = app.menuActions.itemByName(folioOverlaysExtensionName);
        a.invoke();
    }
    else
    {
    	var a=app.menuActions.itemByID(n); 
	    a.invoke();
    }
}

//---------------------------
function invoke_feature_by_id(id)
{
    writelog("invoke feature by id " + id);
    if (arguments.length == 1)
    {
        id_invoke_command(id);
    }
    else
    {
        var a = "";
        for (var i=0;i<arguments.length;i++)
        {
            a += arguments[i] + ",";
        }
        alert("invoke feature by id " + a);
    }
}

//---------------------------
function getHostLocale()
{ 
    writelog("get host locale " + $.locale);
    return '<object><property id="result"><string>' + $.locale + '</string></property></object>';
}

//---------------------------
function getHostPath()
{ 
    var f = new File(app.filePath);
    var path = f.fsName;
    writelog("get host path " + path);
    return '<object><property id="result"><string>' + path + '</string></property></object>';
}
//---------------------------
function writelog(message)
{
	log.open("a");
	log.writeln(message);
	log.close();
}

//---------------------------
function getLogFile() {
		if (IsMacintoshOS ())
		{
			var f = new File("~/Library/Logs/Adobe/ID07_panel.log");
			return f;
		} else{
			var f = new File(Folder.userData + "/ID07_panel.log");
			return f;
		}
}

//---------------------------
function IsMacintoshOS() {
	if ( $.os.search(/macintosh/i) != -1 ) {
		return true;
	} else {
		return false;
	}
}

//---------------------------
function IsWindowsOS() {
	if ( $.os.search(/windows/i) != -1 ) {
		return true;
	} else {
		return false;
	}
}

//---------------------------
function addListeners()
{
    writelog("add listeners");        
    app.eventListeners.add('afterAttributeChanged', onAttrMsg, false);   
    return "<value>true</value>"; 
}

//---------------------------
function removeListeners()
{
    writelog("remove listeners");
    //app.removeEventListener( 'afterAttributeChanged', onAttrMsg );
    //app.removeEventListener('onIdle', onIdle);
}

//---------------------------
function onIdle()
{
    writelog("On idle");
    invokePlayerFunction('<invoke name="handleIdle" returntype="void"><arguments></arguments></invoke>');
}

//---------------------------
function onAttrMsg(event)
{
    var tool = new String(event.attributeValue);
    writelog("onAttrMsg " + tool);
    
    var id = fakeContentCollectorID;

	if (isInArray(tool, contentPlacerNames) || isInArray(tool, contentCollectorNames))
    {
	   	var toolBox = app.toolBoxTools;
		var currentToolName = toolBox.currentToolName;
		
		if (isInArray(currentToolName, contentPlacerNames))
		{
			id = fakeContentPlacerID;
		}
    }
    else
    {
		var index = "$ID/" + tool;
	    var menuAction = app.menuActions.item(index);
	    id = menuAction.id;
	}
	
	writelog("onAttrMsg - " + id);    
	csxsapp.handleAttrMsg(id);
}

//---------------------------
function getCurrentToolID()
{
    var tool = app.toolBoxTools.currentToolName;
    writelog("currentToolName " + tool);
    var index = "$ID/" + tool;
    var menuAction = app.menuActions.item(index);
    var id = menuAction.id;
    writelog("currentToolID - " + id);
    var xml = '<object>';
    xml += '<property id="success"><true/></property>';
    xml += '<property id="currentToolID"><string>';
    xml += id;
    xml += '</string></property>';
    xml += '</object>';
    return xml;
}

//---------------------------
function resolveCfgFilePath()
{
	if (IsMacintoshOS ())
	{
		var f = "file://~/Library/Preferences/Macromedia/Flash Player/#Security/FlashPlayerTrust/Configurator.cfg";
		return f;
	} else {
		var f = "file://" + Folder.userData + "/Macromedia/Flash Player/#Security/FlashPlayerTrust/Configurator.cfg";
		return f;
	}
}

//---------------------------
function addSecurityEntry(path)
{
	writelog("call addSecuirytEntry");
	//Try to add this folder to flash player trusted cfg file
	var cfgpath = resolveCfgFilePath ();
	writelog("cfgpath = " + cfgpath);
	var f = new File(cfgpath);
	if (!f.exists)
		f.open("w");
	else 
		f.open("a");
	//var mypath = getMyPath();
	var mypath = path;
	writelog("resolve path is " + mypath);
	f.writeln("\r\n" + mypath);
	f.close();
}

//---------------------------
function checkSecurityEntry(path)
{
	writelog("call checkSecuirytEntry");
	//Try to add this folder to flash player trusted cfg file
	var cfgpath = resolveCfgFilePath ();
	writelog("cfgpath = " + cfgpath);
	var f = new File(cfgpath);
	var result = '<object><property id="result"><string>false</string></property></object>';
	if (f.exists)
	{
		f.open("r");
		while (!f.eof)
		{
			var s = f.readln();
			if (s!=null)
			{
				if (s == path)
				{
						result = '<object><property id="result"><string>true</string></property></object>';
						break;
				}
			}
		}
		f.close();
	}
	return result;
}

//---------------------------
function isInArray(name, array)
{
	for (var i = 0; i < array.length; i++)
	{
		if (name == array[i])
		{
			return true;
		}
	}
	return false;
}