Reducing score in relation to countdown timer - actionscript-2

I have a quiz written in actionscript 2. Everything is going swimmingly except that I can't figure out how to get the score to reduce by one point for every second it takes to answer the question.
So... max score is 30 points for each question and there is a 30 sec timer... and so that the quiz is more challenging I'd like it to reduce by 1 point for every second it takes to answer.
Here is my code... and thanks in advance...
Answer0Button.enabled=false; button0._visible=false;
Answer1Button.enabled=false; button1._visible=false;
Answer2Button.enabled=false; button2._visible=false;
Answer3Button.enabled=false; button3._visible=false;
Answer4Button.enabled=false; button4._visible=false;
Answer5Button.enabled=false; button5._visible=false;
function countdown() {
counter--;
countdown_txt.text = counter;
if (counter == 0) {
Answer0Button.enabled=false;
Answer1Button.enabled=false;
Answer2Button.enabled=false;
Answer3Button.enabled=false;
Answer4Button.enabled=false;
Answer5Button.enabled=false;
clearInterval(intID);
AnswerPopUp_mc.gotoAndPlay(1);
AnswerPopUp_mc.AnswerPopUp.DisplayResult.htmlText = "" + TimeIsUp + "";
}
}
// defining variables for data
var ChosenNumberOfQuestions = int(0); // Number of questions in quiz
var TotalNumberOfQuestions = int(0); // Total number of questions in XML file
var NumberOfQuestions = int(0); // min of two above
var QuestionCounter = int(0); // for dynamicaly showing questions
var CurrentQuestion = QuestionCounter + 1; // for dynamicaly showing questions
var Points = 0; // for each question
var TotalPoints = 0; // Max Points
var Score = 0; // display total score
var NumberOfCorrectAnswers = 0; // counter for questions answered correctly
var RandOrderQuestions = new Array();
var Questions = new Array();
var Images = new Array();
var CorrectAnswers = new Array();
var Answers = new Array();
var ExplanationsIfCorrect = new Array();
var ExplanationsIfNotCorrect = new Array();
var TimesForSolving = new Array();
var NumberOfPoints = new Array();
// roll over states for buttons
button0.onEnterFrame = function() {
if (mouse_over_button0) {
_root.button0.nextFrame();
} else {
_root.button0.prevFrame();
}
};
button1.onEnterFrame = function() {
if (mouse_over_button1) {
_root.button1.nextFrame();
} else {
_root.button1.prevFrame();
}
};
button2.onEnterFrame = function() {
if (mouse_over_button2) {
_root.button2.nextFrame();
} else {
_root.button2.prevFrame();
}
};
button3.onEnterFrame = function() {
if (mouse_over_button3) {
_root.button3.nextFrame();
} else {
_root.button3.prevFrame();
}
};
button4.onEnterFrame = function() {
if (mouse_over_button4) {
_root.button4.nextFrame();
} else {
_root.button4.prevFrame();
}
};
button5.onEnterFrame = function() {
if (mouse_over_button5) {
_root.button5.nextFrame();
} else {
_root.button5.prevFrame();
}
};
// Label Color
var changeColor2 = new Color(label_mc.coloredLabel);
changeColor2.setRGB(labelColor);
// Change Buttons Color
var changeColorA = new Color(button0.letterA_mc.letterA);
changeColorA.setRGB(labelColor);
var changeColorB = new Color(button1.letterB_mc.letterB);
changeColorB.setRGB(labelColor);
var changeColorC = new Color(button2.letterC_mc.letterC);
changeColorC.setRGB(labelColor);
var changeColorD = new Color(button3.letterD_mc.letterD);
changeColorD.setRGB(labelColor);
var changeColorE = new Color(button4.letterE_mc.letterE);
changeColorE.setRGB(labelColor);
var changeColorF = new Color(button5.letterF_mc.letterF);
changeColorF.setRGB(labelColor);
// Change Color of points, counter...
var changeColorCounter = new Color(countdown_txt);
changeColorCounter.setRGB(labelColor);
var changeSlashColor = new Color(slash);
changeSlashColor.setRGB(labelColor);
var changeCurrQColor = new Color(DisplayCurrQ);
changeCurrQColor.setRGB(labelColor);
var changeTotalQColor = new Color(DisplayTotalQ);
changeTotalQColor.setRGB(labelColor);
var changePointsColor = new Color(DisplayPoints);
changePointsColor.setRGB(labelColor);
var changeScoreColor = new Color(DisplayScore);
changeScoreColor.setRGB(labelColor);
// Background Color
new Color (BackGround.bg).setRGB(BackgroundColor);
new Color (FadeIn.bg1.bg).setRGB(BackgroundColor);
// loading data from XML
var xmlData = new XML();
xmlData.ignoreWhite = true;
xmlData.onLoad = function () {
// Default Time for solving
DefaultTimeInSeconds = this.firstChild.attributes.DefaultTimeInSeconds;
trace ("DefaultTime: " + DefaultTimeInSeconds);
// Default Points
DefaultPoints = this.firstChild.attributes.DefaultPoints;
trace ("DefaultPoints: " + DefaultPoints);
// Default comment on answers
DefaultIfCorrectAnswer = this.firstChild.attributes.DefaultIfCorrectAnswer;
DefaultIfWrongAnswer = this.firstChild.attributes.DefaultIfWrongAnswer;
// Default if time is up
TimeIsUp = this.firstChild.attributes.TimeIsUp;
// Random order of questions or not
RandomQuestions = this.firstChild.attributes.RandomQuestions;
trace ("RandomQuestions: " + RandomQuestions);
// Number Of Questions
ChosenNumberOfQuestions = this.firstChild.attributes.NumberOfQuestions;
trace ("ChosenNumberOfQuestions: " + ChosenNumberOfQuestions);
// Counting total number of Questions in XML file
var nodes = this.firstChild.childNodes;
for (var a=0; a<nodes.length; a++){
TotalNumberOfQuestions = a+1;
}
trace ("TotalNumberOfQuestions: " + TotalNumberOfQuestions);
// Finaly - number of questions in QUIZ - min of two above
if (ChosenNumberOfQuestions < TotalNumberOfQuestions) {
NumberOfQuestions = ChosenNumberOfQuestions;
} else {
NumberOfQuestions = TotalNumberOfQuestions;
}
// Random order Questions or not
// first we populate array with question numbers
for(i=0; i<TotalNumberOfQuestions; i++){
RandOrderQuestions[i] = i;
trace(RandOrderQuestions);
}
// if we want random questions we use random sorting of number of questions
if (RandomQuestions == "TRUE") {
RandOrderQuestions.sort(function () {
return random(2) ? true : false;
});
trace(RandOrderQuestions);
}
///////////////////////////
// POPULATING FROM XML
for (var i=0; i < NumberOfQuestions; i++ )
{
// Chose the number of question from RandOrderQuestions array
var numInXML = RandOrderQuestions[i];
trace("Question number in XML: " + numInXML);
// populating questions from XML
Questions[i] = this.firstChild.childNodes[numInXML].childNodes[0].firstChild.nodeValue;
//trace(Questions);
//populating Correct Answers from XML
CorrectAnswers[i] = this.firstChild.childNodes[numInXML].childNodes[1].attributes.correctAnswer;
//trace(CorrectAnswers);
// populating options for answers from XML
var NewArray = new Array(); // temp array for answers for each question
for (var j=0; j < this.firstChild.childNodes[numInXML].childNodes[1].childNodes.length; j++ )
{
trace(i + " "+ j);
NewArray[j] = this.firstChild.childNodes[numInXML].childNodes[1].childNodes[j].firstChild.nodeValue;
//trace(NewArray);
NewArray.sort(function () {
return random(2) ? true : false;
});
}
Answers.push(NewArray); // push answers for this i question in main Answers array
//populating additional options from XML
ExplanationsIfCorrect[i] = this.firstChild.childNodes[numInXML].childNodes[2].attributes.explanationIfCorrect;
ExplanationsIfNotCorrect[i] = this.firstChild.childNodes[numInXML].childNodes[2].attributes.explanationIfNotCorrect;
TimesForSolving[i] = this.firstChild.childNodes[numInXML].childNodes[2].attributes.timeInSeconds;
NumberOfPoints[i] = this.firstChild.childNodes[numInXML].childNodes[2].attributes.points;
Images[i] = this.firstChild.childNodes[numInXML].childNodes[2].attributes.imageIfCorrect;
Images[i] = this.firstChild.childNodes[numInXML].childNodes[2].attributes.imageIfIncorrect;
}
trace("Questions: " + Questions); trace("Correct Answers: " + CorrectAnswers);
trace(NewArray);
trace(ExplanationsIfCorrect); trace(ExplanationsIfNotCorrect); trace(TimesForSolving); trace(NumberOfPoints); trace(Images);
// show first question (QuestionCounter=0)
QuestionNumber.text = "Question #" + 1;
QuestionDisplay.htmlText = Questions[QuestionCounter];
// show answers for first question (QuestionCounter=0)
if (0 < Answers[QuestionCounter].length){ Answer0Display.text = Answers[QuestionCounter][0]; Answer0Button.enabled=true; button0._visible=true;} else { button0._visible=false;}
if (1 < Answers[QuestionCounter].length){ Answer1Display.text = Answers[QuestionCounter][1]; Answer1Button.enabled=true; button1._visible=true;} else { button1._visible=false;}
if (2 < Answers[QuestionCounter].length){ Answer2Display.text = Answers[QuestionCounter][2]; Answer2Button.enabled=true; button2._visible=true;} else { button2._visible=false;}
if (3 < Answers[QuestionCounter].length){ Answer3Display.text = Answers[QuestionCounter][3]; Answer3Button.enabled=true; button3._visible=true;} else { button3._visible=false;}
if (4 < Answers[QuestionCounter].length){ Answer4Display.text = Answers[QuestionCounter][4]; Answer4Button.enabled=true; button4._visible=true;} else { button4._visible=false;}
if (5 < Answers[QuestionCounter].length){ Answer5Display.text = Answers[QuestionCounter][5]; Answer5Button.enabled=true; button5._visible=true;} else { button5._visible=false;}
// show image if defined
if (Images[QuestionCounter]){ loadMovie(Images[QuestionCounter],"imgContainer"); } else { }
// determine the number of points
if (NumberOfPoints[QuestionCounter]){ Points = NumberOfPoints[QuestionCounter] } else { Points = DefaultPoints }
// start counter
if (TimesForSolving[QuestionCounter]){
countdown_time = TimesForSolving[QuestionCounter]
} else {
countdown_time = DefaultTimeInSeconds
} // now call the function
counter = countdown_time;
countdown_txt.text = countdown_time;
clearInterval(intID);
intID = setInterval(countdown,1000);
}

I don't see where you added your scores, but I believe you can set score = counter since your counter is the time remaining.

Related

freeze solution value for next iteration

I want to save some solution from iter=1 for iter=2 and so on.
A part of the main block is placed here.
var x = opl.x.solutionValue;
for (var k in data2.M){
for (var r in data2.Links){
if (x[k][r.N]==1){
x[k][r.N]= opl.x[k][r.N].solutionValue;
var data3 = new IloOplDataElements();
var xnew =opl.x[k][r.N].solutionValue;
xnew = x[k][r.N];
data3.xnew = x[k][r.N];
opl.addDataSource(data3);
writeln("x[",k,"]","[",r.N,"]"," = ",x [k][r.N]);
writeln("xnew[",k,"]","[",r.N,"]"," = ",data3.xnew [k][r.N]);
}
}}
when I run this model; Without any error, the xnew is not update and printed in scripting log xnew undefined.
I have the same .mod file for each iteration and I defined xnew in the .mod file as follows:
{float} xnew [s][N]= [];
could you help me to solve this problem?
A really appreciate your comments.
Let me start from the example https://github.com/AlexFleischerParis/howtowithoplchange/blob/master/change2darray.mod to show how to freeze for next iteration.
if (k!=11)
{opl.x.LB=output;
opl.x.UB=output;
}
is doing the freeze
in
int a[1..2][1..2];
main {
var source = new IloOplModelSource("sub2d.mod");
var cplex = new IloCplex();
var def = new IloOplModelDefinition(source);
var output=0;
for(var k=11;k<=15;k++)
{
var opl = new IloOplModel(def,cplex);
var data2= new IloOplDataElements();
data2.y=thisOplModel.a;
data2.y[1][1]=k;
opl.addDataSource(data2);
opl.generate();
// if k!=11 then freeze x to the output value from last time
if (k!=11)
{opl.x.LB=output;
opl.x.UB=output;
}
if (cplex.solve()) {
writeln("OBJ = " + cplex.getObjValue());
} else {
writeln("No solution");
}
opl.postProcess();
output=opl.x.solutionValue;
data2.end();
opl.end();
}
}
where sub2d.mod is
int y[1..2][1..2]=...;
execute
{
writeln("y=",y);
}
dvar float x;
maximize x;
subject to {
x<=sum(i in 1..2, j in 1..2) y[i][j];
}
and if you change sub2d.mod to
int y[1..2][1..2]=...;
execute
{
writeln("y=",y);
}
dvar boolean x[1..2][1..2];
maximize sum(i in 1..2,j in 1..2)x[i][j];
subject to {
sum(i in 1..2,j in 1..2) x[i][j]<=(sum(i in 1..2, j in 1..2) y[i][j]) ;
}
then you can write
int a[1..2][1..2];
main {
var source = new IloOplModelSource("sub2d.mod");
var cplex = new IloCplex();
var def = new IloOplModelDefinition(source);
var output=0;
for(var k=11;k<=15;k++)
{
var opl = new IloOplModel(def,cplex);
var data2= new IloOplDataElements();
data2.y=thisOplModel.a;
data2.y[1][1]=k;
opl.addDataSource(data2);
opl.generate();
// if k!=11 then freeze x to the output value from last time
if (k!=11)
{opl.x[1][1].LB=output;
opl.x[1][1].UB=output;
}
if (cplex.solve()) {
writeln("OBJ = " + cplex.getObjValue());
} else {
writeln("No solution");
}
opl.postProcess();
output=opl.x[1][1].solutionValue;
writeln("x[1][1]=",opl.x[1][1].solutionValue);
writeln("x[2][1]=",opl.x[2][1].solutionValue);
data2.end();
opl.end();
}
}

Label Printing using iTextSharp

I have a logic to export avery label pdf. The logic exports the pdf with labels properly but when i print that pdf, the page size measurements (Page properties) that i pass isn't matching with the printed page.
Page Properties
Width="48.5" Height="25.4" HorizontalGapWidth="0" VerticalGapHeight="0" PageMarginTop="21" PageMarginBottom="21" PageMarginLeft="8" PageMarginRight="8" PageSize="A4" LabelsPerRow="4" LabelRowsPerPage="10"
The above property values are converted equivalent to point values first before applied.
Convert to point
private float mmToPoint(double mm)
{
return (float)((mm / 25.4) * 72);
}
Logic
public Stream SecLabelType(LabelProp _label)
{
List<LabelModelClass> Model = new List<LabelModelClass>();
Model = RetModel(_label);
bool IncludeLabelBorders = false;
FontFactory.RegisterDirectories();
Rectangle pageSize;
switch (_label.PageSize)
{
case "A4":
pageSize = iTextSharp.text.PageSize.A4;
break;
default:
pageSize = iTextSharp.text.PageSize.A4;
break;
}
var doc = new Document(pageSize,
_label.PageMarginLeft,
_label.PageMarginRight,
_label.PageMarginTop,
_label.PageMarginBottom);
var output = new MemoryStream();
var writer = PdfWriter.GetInstance(doc, output);
writer.CloseStream = false;
doc.Open();
var numOfCols = _label.LabelsPerRow + (_label.LabelsPerRow - 1);
var tbl = new PdfPTable(numOfCols);
var colWidths = new List<float>();
for (int i = 1; i <= numOfCols; i++)
{
if (i % 2 > 0)
{
colWidths.Add(_label.Width);
}
else
{
colWidths.Add(_label.HorizontalGapWidth);
}
}
var w = iTextSharp.text.PageSize.A4.Width - (doc.LeftMargin + doc.RightMargin);
var h = iTextSharp.text.PageSize.A4.Height - (doc.TopMargin + doc.BottomMargin);
var size = new iTextSharp.text.Rectangle(w, h);
tbl.SetWidthPercentage(colWidths.ToArray(), size);
//var val = System.IO.File.ReadLines("C:\\Users\\lenovo\\Desktop\\test stock\\testing3.txt").ToArray();
//var ItemNoArr = Model.Select(ds => ds.ItemNo).ToArray();
//string Header = Model.Select(ds => ds.Header).FirstOrDefault();
int cnt = 0;
bool b = false;
int iAddRows = 1;
for (int iRow = 0; iRow < ((Model.Count() / _label.LabelsPerRow) + iAddRows); iRow++)
{
var rowCells = new List<PdfPCell>();
for (int iCol = 1; iCol <= numOfCols; iCol++)
{
if (Model.Count() > cnt)
{
if (iCol % 2 > 0)
{
var cellContent = new Phrase();
if (((iRow + 1) >= _label.StartRow && (iCol) >= (_label.StartColumn + (_label.StartColumn - 1))) || b)
{
b = true;
try
{
var StrArr = _label.SpineLblFormat.Split('|');
foreach (var x in StrArr)
{
string Value = "";
if (x.Contains(","))
{
var StrCommaArr = x.Split(',');
foreach (var y in StrCommaArr)
{
if (y != "")
{
Value = ChunckText(cnt, Model, y, Value);
}
}
if (Value != null && Value.Replace(" ", "") != "")
{
cellContent.Add(new Paragraph(Value));
cellContent.Add(new Paragraph("\n"));
}
}
else
{
Value = ChunckText(cnt, Model, x, Value);
if (Value != null && Value.Replace(" ", "") != "")
{
cellContent.Add(new Paragraph(Value));
cellContent.Add(new Paragraph("\n"));
}
}
}
}
catch (Exception e)
{
var fontHeader1 = FontFactory.GetFont("Verdana", BaseFont.CP1250, true, 6, 0);
cellContent.Add(new Chunk("NA", fontHeader1));
}
cnt += 1;
}
else
iAddRows += 1;
var cell = new PdfPCell(cellContent);
cell.FixedHeight = _label.Height;
cell.HorizontalAlignment = Element.ALIGN_LEFT;
cell.Border = IncludeLabelBorders ? Rectangle.BOX : Rectangle.NO_BORDER;
rowCells.Add(cell);
}
else
{
var gapCell = new PdfPCell();
gapCell.FixedHeight = _label.Height;
gapCell.Border = Rectangle.NO_BORDER;
rowCells.Add(gapCell);
}
}
else
{
var gapCell = new PdfPCell();
gapCell.FixedHeight = _label.Height;
gapCell.Border = Rectangle.NO_BORDER;
rowCells.Add(gapCell);
}
}
tbl.Rows.Add(new PdfPRow(rowCells.ToArray()));
_label.LabelRowsPerPage = _label.LabelRowsPerPage == null ? 0 : _label.LabelRowsPerPage;
if ((iRow + 1) < _label.LabelRowsPerPage && _label.VerticalGapHeight > 0)
{
tbl.Rows.Add(CreateGapRow(numOfCols, _label));
}
}
doc.Add(tbl);
doc.Close();
output.Position = 0;
return output;
}
private PdfPRow CreateGapRow(int numOfCols, LabelProp _label)
{
var cells = new List<PdfPCell>();
for (int i = 0; i < numOfCols; i++)
{
var cell = new PdfPCell();
cell.FixedHeight = _label.VerticalGapHeight;
cell.Border = Rectangle.NO_BORDER;
cells.Add(cell);
}
return new PdfPRow(cells.ToArray());
}
A PDF document may have very accurate measurements, but then those measurements get screwed up because the page is scaled during the printing process. That is a common problem: different printers will use different scaling factors with different results when you print the document using different printers.
How to avoid this?
In the print dialog of Adobe Reader, you can choose how the printer should behave:
By default, the printer will try to "Fit" the content on the page, but as not every printer can physically use the full page size (due to hardware limitations), there's a high chance the printer will scale the page down if you use "Fit".
It's better to choose the option "Actual size". The downside of using this option is that some content may get lost because it's too close to the border of the page in an area that physically can't be reached by the printer, but the advantage is that the measurements will be preserved.
You can set this option programmatically in your document by telling the document it shouldn't scale:
writer.AddViewerPreference(PdfName.PRINTSCALING, PdfName.NONE);
See How to set initial view properties? for more info about viewer preferences.

How to get modified values from dojo table

I have a Dojo table with list of key value pairs. Both fields are editable, once a value is modified i am doing:
var items = grid.selection.getSelected();
However, the modified value is not picked up only the old value is picked.
I tried the following:
dojo.parser.parse()
dojo.parser.instantiate([dojo.byId("tableDiv")]);
but none of them worked. Can any one sugggest a solution for this.
function getAllItems() {
var returnData = "";
//dojo.parser.parse();
//dojo.parser.instantiate([dojo.byId("tableDiv")]);
//grid._refresh();
var items = grid.selection.getSelected();
function gotItems(items, request) {
var i;
for (i = 0; i < items.length; i++) {
var item = items[i];
var paramName = grid.store.getValues(item, "paramName");
var paramValue = grid.store.getValues(item, "paramValue");
if (returnData == "") {
returnData = paramName + "&" + paramValue;
} else {
returnData = returnData + "#" + paramName + "&"
+ paramValue;
} document.getElementById("returnData").value = returnData;
document.getElementById("successFlag").value = "true";
}
}
//Called when loop fails
function fetchFailed(error, request) {
alert("Error reading table data");
}
//Fetch the data.
jsonStore.fetch({
onComplete : gotItems,
onError : fetchFailed
});
}

JSFL - Adding a movieclip to a specific layer and frame

I am trying to replace an outdated movieclip with a newer one.
To do this I'm usin JSFL to locate the old movieclips, save a reference, then add the new version in its place.
I have looked at addItem addItemToDocument and they successfully add the clip, but I'm unsure of how to add it to the specific layer and frame that the old instance of the movieclip was on.
Halps
Replacing all instances of the old movieclip with instances of the new movieclip, could be an easier solution.
All instances of the old movieclip can be found by parsing the timelines of the flash document.
Here is some code:
var _doc = (fl.getDocumentDOM() ? fl.getDocumentDOM() : fl.createDocument());
var _lib = _doc.library;
fl.outputPanel.clear();
ReplaceItemWithItem('Game Layouts/card holder', 'Game Layouts/card holder new');
function ReplaceItemWithItem(oldmcname, newmcname)
{
var item1 = GetItem(oldmcname);
var item2 = GetItem(newmcname);
if (!item1) return false;
if (!item2) return false;
if (oldmcname == newmcname)
return true;
return ReplaceAllItems(item1, item2);
}
function ReplaceAllItems(item1, item2)
{
var timelines = _doc.timelines;
var i, l = timelines.length;
var items = _lib.items;
var changed = false;
// Main timelines
for (i = 0; i < l; i++)
{
var timeline = timelines[i];
changed |= ReplaceItems(timeline, item1, item2);
}
// Timelines in library items
for (i = 0, l = items.length; i < l; i++)
{
var item = items[i];
switch (item.itemType)
{
case "movie clip":
case "graphic":
case "button":
changed |= ReplaceItems(item.timeline, item1, item2);
break;
}
}
return changed;
}
function ReplaceItems(timeline, item1, item2)
{
var changed = false;
if (timeline && item1 && item2)
{
var layers = timeline.layers;
var lay, layl = layers.length;
for (lay = 0; lay < layl; lay++)
{
var layer = layers[lay];
var frames = layer.frames;
var fr, frl = frames.length;
for (fr = 0; fr < frl; fr++)
{
var frame = frames[fr];
if (frame && frame.startFrame == fr)
{
var elements = frame.elements;
var e, el = elements.length;
for (e = 0; e < el; e++)
{
var elem = elements[e];
if (elem && elem.elementType == "instance") // Elements can be empty
{
var item = elem.libraryItem;
if (item.name == item1.name)
{
elem.libraryItem = item2;
changed = true;
}
}
}
}
}
}
}
return changed;
}
function GetItem(itemname)
{
if (!_lib.selectItem(itemname))
{
alert("'" + name + "' does not exist in the library!");
return null;
}
return _lib.getSelectedItems()[0];
}
Hope this helps!

InDesign copy layer to another document

I am trying to write a script that copies a layer from one document into another.
var srcDocName = 0;
var destDocName = 1;
var layerNameOriginal = "Original";
var layerNameCopyTo = "Destination";
var destDoc = app.documents.item(destDocName);
var layerSrc = app.documents.item(srcDocName).layers.item(layerNameOriginal);
try {
layerSrc.duplicate(destDoc, ElementPlacement.INSIDE);
}
catch(e) {
alert(e)
}
Apparently this works in Photoshop but not in InDesign. I have been trying for ages to find some decent documentation for InDesign scripting. But all I can find is the CS scripting guide, which isn't of much use.
http://wwwimages.adobe.com/www.adobe.com/content/dam/Adobe/en/products/indesign/pdfs/InDesignCS5_ScriptingGuide_JS.pdf
If someone can point me to a good reference to the object model I would be grateful.
After some more googling I finally found the answer:
var sourceLayer = app.documents[0].layers.itemByName("Layer1");
var destLayer = app.documents[1].layers[0];
sourceLayer.pageItems.everyItem().duplicate(destLayer);
I also came across jongware which seems to be a complete Object reference extracted directly out of Adobe CS.
You can use this script: https://redokun.com/blog/indesign-copy-entire-layer-one-file-another
The underlying implementation is basically the same, but we've added a UI so it's not necessary to edit the script every time the layer name changes.
Edit: We've been told that the solution above doesn't work with threaded text frames, so I re-wrote the script. The new implementation is way more complex but it now supports threaded TFs.
To expand on the solution offered by Loopo and offer you the ability to copy all layers from 1 document to another...
main();
function main()
{
var source = GetSourceDocument();
if(source == -1)
{
return;
}
var target = GetTargetDocument ();
if(target == -1)
{
return;
}
if(target == source)
{
return;
}
copyLayersOver(source, target);
}
function GetSourceDocument()
{
var returnVal = -1;
var oldPrefs = app.scriptPreferences.userInteractionLevel;
app.scriptPreferences.userInteractionLevel=UserInteractionLevels.INTERACT_WITH_ALL;
var dialog = app.dialogs.add({name:"Document to Copy From", canCanel: true, label:"DocumentToCopyFrom"});
var col1 = dialog.dialogColumns.add();
var StringList= [];
for(var i = 0; i<app.documents.length; i++)
{
StringList.push("[" + app.documents[i].index + "] " + app.documents[i].name);
}
var ddl = col1.dropdowns.add({id:"SourceDocDDL", stringList: StringList});
if(dialog.show() == true)
{
returnVal = ddl.stringList[ddl.selectedIndex].split("]")[0].substr(1);
}
else
{
returnVal -1;
}
dialog.destroy();
app.scriptPreferences.userInteractionLevel = oldPrefs;
return returnVal;
}
function GetTargetDocument()
{
var returnVal = -1;
var oldPrefs = app.scriptPreferences.userInteractionLevel;
app.scriptPreferences.userInteractionLevel=UserInteractionLevels.INTERACT_WITH_ALL;
var dialog = app.dialogs.add({name:"Document to Copy To", canCanel: true, label:"DocumentToCopyTo"});
var col1 = dialog.dialogColumns.add();
var StringList= [];
for(var i = 0; i<app.documents.length; i++)
{
StringList.push("[" + app.documents[i].index + "] " + app.documents[i].name);
}
var ddl = col1.dropdowns.add({id:"SourceDocDDL", stringList: StringList});
if(dialog.show() == true)
{
returnVal = ddl.stringList[ddl.selectedIndex].split("]")[0].substr(1);
}
else
{
returnVal -1;
}
dialog.destroy();
app.scriptPreferences.userInteractionLevel = oldPrefs;
return returnVal;
}
function copyLayersOver(source, target)
{
var sourceDocument = app.documents[source];
var targetDocument = app.documents[target];
var sourceLayers = sourceDocument.layers;
//Match the number of pages
while(targetDocument.pages.length < sourceDocument.pages.length)
{
targetDocument.pages.add();
}
//copy the layers over
for(var i= 0; i < sourceLayers.length; i++)
{
var names = targetDocument.layers.everyItem().name;
var merge = false;
for(var y = 0; y < names.length; y++)
{
if(names[y] == sourceLayers[i].name)
{
merge = true;
break;
}
}
if(merge)
{
var targetLayer = targetDocument.layers.add();
targetLayer.name = "temp";
sourceLayers[i].pageItems.everyItem().duplicate(targetLayer);
targetDocument.layers.itemByName(sourceLayers[i].name).merge(targetLayer);
}
else
{
var targetLayer = targetDocument.layers.add();
targetLayer.name = sourceLayers[i].name;
targetLayer.layerColor = sourceLayers[i].layerColor;
sourceLayers[i].pageItems.everyItem().duplicate(targetLayer);
}
}
}