//#include "core/aedres_xml_core.jsx"
#include "XML Rules/glue code.jsx"
#include "core/api_metopes.jsx"
#include "core/classes_ui.jsx"
#include "core/metopes_aid_client.jsx"

#targetengine "session";//palette displaying


//global  variables
var myDocument = null;
var afg = null; 


var tags= new Array();
var styles = new Array();



runExtractorModule();

/**************************************************/
//prepares and shows palette environment according to the current loaded document
function runExtractorModule()
{

     try
     {   
        myDocument= app.activeDocument;
     }
     catch(e)
          {
            alert(i18n('nodocload'));
            return;  
          }
     
    //convert tag collection as an array
    for(i = 0; i < myDocument.xmlTags.length; i++)
    {
        tags[i] = myDocument.xmlTags.item(i).name;
    }   
   
    //collects all bloc styles and converts ias an Array
    for(i = 0; i < myDocument.objectStyles.length; i++)
    {
        styles[i] = myDocument.objectStyles.item(i).name;
    }
/*********************UI construction*********************************/

    var palette = new Window ("palette", i18n('aftool'), undefined, {resizeable: true});

    palette.alignChildren = "left";

    var main = palette.add ("group");
    main.orientation = "column";
    main.alignChildren = "left";

    //buttons
    var addRmGroup = palette.add("group");
    var buttons = palette.add ("group");
    var applyButton = buttons.add ("button", undefined, i18n('apply'));
    var closeButton = buttons.add ("button", undefined, i18n('close'));

    //button events
    closeButton.onClick = function () 
    {
        palette.close();
    }

    applyButton.onClick = function () 
    {    
        try{
       blocStyle = myDocument.objectStyles.item(afg.stylesDropDown.selection.index);
        tag = afg.tagsDropDown.selection.text;
     
        displayMess = i18n('node') + tag + "' | "
        if(afg.attributeNamesDropDown.selection.index  != 0)// 0 = all attributes
        {   
            name = afg.attributeNamesDropDown.selection.text;    
            displayMess += i18n('attribute') + name +"' | ";
        }
        else name = null;
     
        if(afg.attributeValuesDropDown.selection.index  != 0) // 0 = all values
        {
            val =  afg.attributeValuesDropDown.selection.text;   
            displayMess +=i18n('value') + val+"'";
        }
        else val = null;

        //progress bar 
        var pBar = new ProgressBar(displayMess);  
        xpath="//body/descendant::" + tag;
        if(name != null)
        {
            if(val!=null)
            {
                xpath +="[@" + name + "='" + val + "']";
            }
            else xpath +="[@" + name + "]"; 
       }

        
        var tc = new TagCounter(xpath);
        __processRuleSet(myDocument.xmlElements.item(0), new Array(tc));
        pBar.reset(i18n('afprocessing'), tc.count);
        //select firt xml element (at the frist page) for rendering optimization
        myDocument.xmlElements.item(0).insertionPoints[0].select;
        
        af = new AnchoredFrames(blocStyle, xpath, pBar);
        ruleTab = new Array();
        ruleTab.push(af);
        __processRuleSet(myDocument.xmlElements.item(0), ruleTab);
        pBar.close();
        
        //restore initial pstyle (on anchored frame following elements)        
        __processRuleSet(myDocument.xmlElements.item(0), new Array(new RestorePStyles("//body/descendant::*[@fenc='true']")));
        
        alert(i18n('afend') + tc.count + i18n('afcreated'));
        }
        catch(e) {logger.alert(err + ", line = " + err.line + "-" + err.fileName)}

 
    }

    afg = new AnchoredFrameTagUI(main); 
    
    //afg.tagsDropDown.selection = noteIndex;
    //updateAttributeNamesListForTag(afg, "note");//note is the default tag selection
    //drop down list events
    afg.tagsDropDown.onChange = function ()
    {
         updateAttributeNamesListForTag(afg, tags[afg.tagsDropDown.selection.index]);        
    }

    afg.attributeNamesDropDown.onChange = function ()
    {
         if(afg.attributeNamesDropDown.selection.index == 0)
         {
             afg.attributeValuesDropDown.removeAll();
         }
         else
         {
            updateAttributeValuesListForTag(afg, afg.tagsDropDown.selection.text, afg.attributeNamesDropDown.selection.text);
         }
    }


    palette.show();   
}





/*********************XML RULES*********************************/

//tag counter  according to an xpath
function TagCounter(xpth)
{
        this.name = "TagCounter";
        this.xpath = xpth;
        this.count = 0;
        this.apply = function(myElement, myRuleProcessor)
        {
            this.count++;
            return true;
        }
}





//removes contents, puts this contents in a anchored frame and applies a bloc style on each
function AnchoredFrames(blocStyle, xpath, progressBar)
{
    this.name = "AnchoredFrames";

    this.xpath = xpath;
    this.index = 0;
    this.apply = function(myElement, myRuleProcessor)
    {

        try{
            var isText = myElement.insertionPoints.length > 0 ;
            //txt element
            if(isText){
                    //saves next paragraph style if exists
                    //nextParaStyle = null;
                    //nextSibling = null;
                    //try{
                        /*nextSibling = myElement.parent.xmlElements.nextItem(myElement);
                        if(nextSibling){
                            if(nextSibling.paragraphs.length > 0){
                                  nextParaStyle = nextSibling.paragraphs[0].appliedParagraphStyle;
                            }
                        }*/
                        //parentTextFrame = myElement.insertionPoints[0].parentTextFrames[0];
                        
                    //}
                    //catch(e){/*no sibling*/}
                    myTextFrame = myElement.insertionPoints[0].parentTextFrames[0];
                    myChar = myTextFrame.parentStory.characters.item(myElement.insertionPoints[0].index-2);
                    myFrame = myChar.insertionPoints.item(0).textFrames.add();
                    myFrame.recompose;
                    myFrame.applyObjectStyle(blocStyle,clearingOverrides=false,clearingOverridesThroughRootObjectStyle=true);
                    myElement.texts.item(0).move(LocationOptions.AT_END, myFrame.texts.item(0));
                    myElement.texts.item(0).recompose;
                    myElement.contents = "";
                    
                     //restores next para style if exists
                     //if(nextParaStyle != null){
                     //    nextSibling.paragraphs[0].appliedParagraphStyle = nextParaStyle;
                     //}
                    
               //var myTextFrame = myElement.insertionPoints[0].parentTextFrames[0];
               //myTextFrame.applyObjectStyle(blocStyle,clearingOverrides=false,clearingOverridesThroughRootObjectStyle=true);
            }
            else{//graphic element
                if(myElement.graphics.length > 0){
                    var myGraphic = myElement.graphics[0];
                    myGraphic.parent.applyObjectStyle(blocStyle,clearingOverrides=false,clearingOverridesThroughRootObjectStyle=true); 
                }
            }
            progressBar.hit();
        }
         catch(e){e}
        return true;
    }
}

/*
Restore initiall pstyles
*/
function RestorePStyles(xpath){
    this.name = "RestorePStyles";
    this.xpath = xpath;
    this.apply = function(myElement, myRuleProcessor)
        {
            try{
                initialStyle = myElement.xmlAttributes.item("aid:pstyle");
		appliedStyle = myElement.paragraphs.item(0).appliedParagraphStyle.name;
		if(appliedStyle != initialStyle.value)
		{
                    myElement.applyParagraphStyle(initialStyle.value);
		}
            }
            catch(e){alert(e)}
            return true;
        }
}


function WithTextElements(){
    
    this.xpath ="//*/text()";
    this.tags = new Array();
    this.apply = function(myElement, myRuleProcessor)
    
    {
        this.tags.push(myElement.parent.localName());

        return true;
    }

}
