/*
Written by Matthew Daniel to create rich content automatically from CSV file
November 7, 2018
Resources:
https://github.com/fabianmoronzirfas/extendscript
http://jongware.mit.edu/idcs6js/index_Basics%20Suite.html

TODO:
1. Write a function that will check if a color swatch exists if not create it
2. Possibly make multiple pages past 500+ OMSIDs
*/

// https://www.rorohiko.com/underscore/
//#include "_.jsx";

// Polyfill: https://stackoverflow.com/questions/35276076/how-can-i-use-higher-order-functions-like-array-reduce-in-an-indesign-script
//#include "polyfill.js";

// Scrollable alert function
function alert_scroll(title, input) {
  if (input instanceof Array)
    input = input.join("\r");
  var w = new Window("dialog", title);
  w.add("button", undefined, "Close", {
    name: "ok"
  });
  var list = w.add("edittext", undefined, input, {
    multiline: true,
    scrolling: true
  });
  list.maximumSize.height = w.maximumSize.height - 100;
  list.minimumSize.width = 500;
  w.show();
  /* How to use:
   var reflectProperties = variable name you want to see;
   alert_scroll("Object Properties", reflectProperties.reflect.properties.sort());
  */
}

// Function to get textframe size
function geoBounds(frameRef) {
  var gBounds = frameRef.geometricBounds;
  var myBounds = {};
  myBounds.y1 = gBounds[0];
  myBounds.x1 = gBounds[1];
  myBounds.y2 = gBounds[2];
  myBounds.x2 = gBounds[3];
  return myBounds;
}

// Check if object is empty
function isEmptyObject(obj) {
  for (var prop in obj) {
    if (Object.prototype.hasOwnProperty.call(obj, prop)) {
      return false;
    }
  }
  return true;
}

// Get text frame Y2 value
function getTextFrmY2(frameRef) {
  try{
    var gb = frameRef.geometricBounds;
    var y2 = gb[2];
    return y2;
  }catch(e){
    alert("Error for getTextFrmY2, most likely its that the text frame was never created or has the incorrect reference. \nLine: " + e.line + "\n" + e);
  }
}

// Get text frame geometric bounds
function getTxtFrmGeometricBounds(frameRef, name) {
  try {
    var myGB = {};
    var gb = frameRef.geometricBounds;
    myGB.xcoord = gb[1];
    myGB.ycoord = gb[0];
    myGB.width = gb[3] - gb[1];
    myGB.height = gb[2] - gb[0];
    myGB.y1 = gb[0];
    myGB.x1 = gb[1];
    myGB.y2 = gb[2];
    myGB.x2 = gb[3];
    return myGB;
  } catch (e) {
    app.documents.item(0).close(SaveOptions.NO);
    alert("Error for getTxtFrmGeometricBounds \nName: " + name + "\nLine: " + e.line + '\n' + e); // show error on screen or do something with the error
    exit();
  }
}

// Get active page based on item number
function activePage(itemNum) {
  try {
    var thePage = app.documents.item(0).pages.item(itemNum);
    return thePage;
  } catch (e) {
    app.documents.item(0).close(SaveOptions.NO);
    alert("Error for activePage \nLine: " + e.line + '\n' + e); // show error on screen or do something with the error
    exit();
  }
}

// Create Text Frames – How to Use: http://jongware.mit.edu/idcs6js/pc_TextFramePreference.html
function createTextFrame(itemNum, itemLayer, name, contentType, geometricBounds, contents, paragraphStyle, autoSizingReferencePoint, autoSizingType, verticalJustification) {
  try{
    var myActivePage = activePage(itemNum);
    var myActiveTextFrame = myActivePage.textFrames.add({
      itemLayer: itemLayer,
      name: name,
      contentType: contentType,
      geometricBounds: geometricBounds,
      contents: contents
    });
    myActiveTextFrame.textFramePreferences.autoSizingReferencePoint = autoSizingReferencePoint;
    myActiveTextFrame.textFramePreferences.autoSizingType = autoSizingType;
    myActiveTextFrame.textFramePreferences.firstBaselineOffset = FirstBaseline.CAP_HEIGHT;
    myActiveTextFrame.textFramePreferences.verticalJustification = verticalJustification;

    // Apply the paragraph style
    var myParagraphStyle = myDocument.paragraphStyles.item(paragraphStyle);
    myActiveTextFrame.parentStory.texts.item(0).applyParagraphStyle(myParagraphStyle, true);
    return myActiveTextFrame;
  }catch(e){
    alert("Error for createTextFrame \nName: " + name + "\nPod: " + itemNum + "\nLine: " + e.line + '\n' + e); // show error on screen or do something with the error
  }
}

// Function to create rectangles: http://jongware.mit.edu/idcs6js/pc_Rectangle.html
function createRectangle(itemNum, id, itemLayer, name, geometricBounds, contentType, strokeWeight, strokeAlignment, strokeColor, visible, fillColor, omsid) {
  var x = {
    "itemNum": itemNum,
    "id": id,
    "itemLayer": itemLayer,
    "name": name,
    "geometricBounds": geometricBounds,
    "contentType": contentType,
    "strokeWeight": strokeWeight,
    "strokeAlignment": strokeAlignment,
    "strokeColor": strokeColor,
    "visible": visible,
    "fillColor": fillColor
  };
  if (name === '' || name === undefined) {
    name = 'no name defined';
  }
  if (itemNum === '' || itemNum === undefined) {
    throw new TypeError("itemNum is undefined or zero for " + name);
  }
  if (id === undefined || id === '') {
    throw new TypeError("id is undefined for " + name);
  }
  if (itemLayer === '' || itemLayer === undefined) {
    throw new TypeError("itemLayer is undefined for " + name);
  }
  if (name === 'no name defined') {
    throw new TypeError("name is undefined for " + name);
  }
  if (geometricBounds === '' || geometricBounds === undefined) {
    throw new TypeError("geometricBounds is undefined for " + name);
  }
  if (contentType === '' || contentType === undefined) {
    throw new TypeError("contentType is undefined for " + name);
  }
  if (strokeWeight === '' || strokeWeight === undefined) {
    throw new TypeError("strokeWeight is undefined for " + name);
  }
  if (strokeAlignment === '' || strokeAlignment === undefined) {
    throw new TypeError("strokeAlignment is undefined for " + name);
  }
  if (strokeColor === '' || strokeColor === undefined) {
    throw new TypeError("strokeColor is undefined for " + name);
  }
  if (visible === '' || visible === undefined) {
    throw new TypeError("visible is undefined for " + name);
  }
  if (fillColor === '' || fillColor === undefined) {
    fillColor = "#EEEEEE";
  }
  try {
    var myPage = activePage(itemNum);
    var myRectangle = myPage.rectangles.add({
      itemLayer: itemLayer,
      name: name,
      geometricBounds: geometricBounds,
      contentType: contentType,
      strokeWeight: strokeWeight,
      strokeAlignment: strokeAlignment,
      strokeColor: strokeColor,
      visible: visible,
      fillColor: fillColor
    });
    // Possibly set rectangle to fit content proportionally
    myRectangle.frameFittingOptions.fittingOnEmptyFrame = EmptyFrameFittingOptions.PROPORTIONALLY;
    return myRectangle;
  } catch (e) {
    app.documents.item(0).close(SaveOptions.NO);
    alert("Error for rectangle named: " + name + " for OMSID:" + omsid + " \nLine: " + e.line + "\n" + e + "\n" + x.toSource()); // show error on screen or do something with the error
    exit();
  }
}

// Create color swatch if not already created
function createColor(colorValue, model, colorName, space) {
  var myNewSwatch = myDocument.colors.itemByName(colorName);
  myNewSwatch = myNewSwatch.isValid;
  if (myNewSwatch === false) {
    myNewSwatch = myDocument.colors.add({
      colorValue: colorValue,
      model: model,
      name: colorName,
      space: space
    });
    return myNewSwatch;
  }
  if (myNewSwatch === true) {
    var oldSwatch = myDocument.colors.itemByName(colorName);
    oldSwatch.remove();
    myNewSwatch = myDocument.colors.add({
      colorValue: colorValue,
      model: model,
      name: colorName,
      space: space
    });
    return myNewSwatch;
  }
}

// Function to create paragraph styles
function paragraphStyle(name, characterDirection, justification, hyphenation, pointSize, fontStyle, appliedFont, leading, fillColor, kerningMethod, tracking, capitalization, ligatures, rule) {
  if (rule === true) {
    myDocument.paragraphStyles.add({
      name: name,
      characterDirection: characterDirection,
      justification: justification,
      hyphenation: hyphenation,
      pointSize: pointSize,
      fontStyle: fontStyle,
      appliedFont: appliedFont,
      leading: leading,
      fillColor: fillColor,
      kerningMethod: kerningMethod,
      tracking: tracking,
      capitalization: capitalization,
      ligatures: ligatures,
      paragraphBorderBottomLineWeight: 3,
      paragraphBorderBottomOffset: 17,
      paragraphBorderTopOffset: 0,
      paragraphBorderLeftOffset: 0,
      paragraphBorderRightOffset: 0,
      paragraphBorderColor: '#F96302',
      paragraphBorderOn: true,
      paragraphBorderWidth: ParagraphBorderEnum.TEXT_WIDTH,
      paragraphBorderLeftLineWeight: 0,
      paragraphBorderRightLineWeight: 0,
      paragraphBorderTopLineWeight: 0,
      paragraphBorderBottomOrigin: ParagraphBorderBottomOriginEnum.BASELINE_BOTTOM_ORIGIN
    });
  } else {
    myDocument.paragraphStyles.add({
      name: name,
      characterDirection: characterDirection,
      justification: justification,
      hyphenation: hyphenation,
      pointSize: pointSize,
      fontStyle: fontStyle,
      appliedFont: appliedFont,
      leading: leading,
      fillColor: fillColor,
      kerningMethod: kerningMethod,
      tracking: tracking,
      capitalization: capitalization,
      ligatures: ligatures
    });
  }
}

// Create layers: http://jongware.mit.edu/idcs6js/pc_Layer.html
function createLayer(name, layerColor, ignoreWrap, visible, showGuides, printable) {
  var myLayer = myDocument.layers.add({
    name: name,
    layerColor: layerColor,
    ignoreWrap: ignoreWrap,
    visible: visible,
    showGuides: showGuides,
    printable: printable
  });
  return myLayer;
}

// Create Guides
function createGuide(count, itemLayer, locked, orientation, guideType, fitToPage, location) {
  var myPage = app.documents.item(0).pages.item(count);
  var myNewGuide = myPage.guides.add({
    itemLayer: itemLayer, // layer name
    locked: locked, // bool
    orientation: orientation, // HorizontalOrVertical.HORIZONTAL or VERTICAL
    guideType: guideType, // GuideTypeOptions.RULER or LIQUID
    fitToPage: fitToPage, // bool
    location: location
  });
  return myNewGuide;
}

// Create the initial brand banner if TRUE on CSV
function createBanner(count, origin, bottomRight, myBottomMargin, myLeftMargin, myRightMargin, pageWidth, pageHeight, bannerHeight, bannerName, bannerImage, omsid) {
  var myBannerArray = [];
  var myBanner, myBannerPage, myBannerGroup, myClearBox;
  bannerName = omsid + " " + bannerName;
  bannerName = fixSEO(bannerName, omsid, bannerName);
  var cf = false;
  if (bannerImage != '') {
    cf = checkImageFile(dataFileLocation, bannerImage, omsid);
  }
  myClearBox = createRectangle(count, count, "ARTWORK", "My Clear Box " + count, [origin, myLeftMargin, bottomRight, pageWidth - myRightMargin], ContentType.GRAPHIC_TYPE, 0, StrokeAlignment.INSIDE_ALIGNMENT, "None", true, "#EEEEEE", omsid);
  myBanner = createRectangle(count, count, "ARTWORK", bannerName, [origin, myLeftMargin, bottomRight, pageWidth - myRightMargin], ContentType.GRAPHIC_TYPE, 0, StrokeAlignment.INSIDE_ALIGNMENT, "None", true, "#EEEEEE", omsid);
  if (cf === true) {
    myBanner.place(dataFileLocation + bannerImage, false);
  }
  // Get the current page object
  myBannerPage = activePage(count);
  //alert_scroll("Details", myBanner.reflect.properties.sort());
  // Place the banner in an array
  myBannerArray.push(myClearBox, myBanner);
  // Create a group object for the current page and add the array items to the group object
  myBannerGroup = myBannerPage.groups.add(myBannerArray);
  // Name the group for further reference
  myBannerGroup.name = bannerName;
  return myBanner;
}

// Get active page based on item number
function activePage(itemNum) {
  var thePage = app.documents.item(0).pages.item(itemNum);
  return thePage;
}

// Create Document Page
function createDocumentPage(itemNum, atLocation, pageName, width, height) {

  var myNewPage = app.documents.item(0).pages.add({
    id: itemNum,
    bounds: [0, 0, height, width],
    at: atLocation,
    label: pageName,
    appliedMaster: NothingEnum.NOTHING
  });
  myNewPage.marginPreferences.properties = {
    top: 0,
    left: 0,
    right: 0,
    bottom: 0
  };
  return myNewPage;
}

// Check if file exists: http://jongware.mit.edu/idcs6js/pc_File.html
function checkImageFile(dataFileLocation, productImage, omsid) {
  if (productImage != '' || productImage != undefined || productImage != ' ') {
    var myImageFile = new File(dataFileLocation + productImage);
    if (myImageFile.exists) {
      return true;
    } else {
      errArray.push({
        "errMsg": 'Image Not Found',
        "OMSID": omsid,
        "errDesc": "Image not found or is named incorrectly for " + dataFileLocation + productImage
      });
      return false;
    }
  } else {
    return false;
  }
}

function fixSEO(seoText, omsid, seoWhere){
  try{
    var today = new Date();
    var thisYear = today.getFullYear();
    var thisMonth = today.getMonth() + 1;
    var fileName = seoText.replace(/[\W_]+/g, '-').toLowerCase();
    var length = 103;
    var truncatedString = fileName.substring(0, length);
    var longFileName = truncatedString + "-" + thisMonth + "-" + thisYear;
    return longFileName;
  }catch(e){
    alert("Error for SEO for OMSID:" + omsid + " \nLine: " + e.line + "\n" + e + "\nSEO Text: " + seoText + "\nWhere: " + seoWhere);
  }
}

// Check if color is HEX Color
function checkColor(string) {
  var isHex = trimText(string);
  var isHexLength = isHex.length;
  if (isHexLength === 7) {
    isHex = /^#[0-9A-F]{6}$/i.test(isHex);
    return isHex;
  } else {
    return false;
  }
}

// Count character length
function countChars(string, podType, omsid) {
  var myString = trimText(string);
  var myPodType = trimText(podType);
  myStringLength = myString.length;
  checkRowType(myPodType, omsid, null);
}

function createPod(count, origin, rowType, myPodCount, y1, x1, y2, x2, myRowMargin, rowHeight, myLeftMargin, myRightMargin, myTopMargin, myBottomMargin, omsid) {
  // TODO: Determine pod type then create pod and create headline and graphics as needed; End by returning final row height y2 as the result back to the createRow function. Make sure that you have access to the myArray object or create a new one that just has the pod information in it. Somehow create a group from all the things you create for each pod or find a way to make something so that you can export it as a JPG in the end when running the export to JPGs script that you still have to write.
  if (myPodCount === 0) {
    myPodCount = 1;
  }

  var myPodType = "Pod " + myPodCount + " Type";
  myPodType = myArray[count][myPodType];

  var myPodName = "pod" + myPodCount;

  var myPodGroupName = "Pod " + myPodCount + " SEO";
  myPodGroupName = myArray[count][myPodGroupName];
  if (myPodGroupName === '') {
    throw new TypeError('For OMSID: ' + omsid + ' it is required that for Pod ' + myPodCount + ' you have text in the Pod ' + myPodCount + ' SEO field to name the JPGs when exporting. Please revise your CSV file and try again.');
  }
  if (myPodGroupName === undefined) {
    throw new TypeError('For OMSID: ' + omsid + ' it is required that for Pod ' + myPodCount + ' you have text in the Pod ' + myPodCount + ' SEO field to name the JPGs when exporting. Please revise your CSV file and try again.');
  }
  var seoWhere = 'createPod for pod: ' + myPodCount;
  myPodGroupName = fixSEO(myPodGroupName, omsid, seoWhere);
  //if(myPodGroupName === ''){myPodGroupName = 'pod-' + count + '-group';}

  var myPodColor = "Pod " + myPodCount + " Color";
  myPodColor = myArray[count][myPodColor];
  // alert(checkColor(myPodColor));
  if (myPodColor === '') {
    myPodColor = "#EEEEEE";
  }
  if (checkColor(myPodColor) === false) {
    myPodColor = "FPO";
    errArray.push({
      "errMsg": 'Incorrect Color Format',
      "OMSID": omsid,
      "errDesc": "The color listed on the CSV is longer or shorter than 7 characters or is formatted incorrectly for pod " + myPodCount + ". The format should be like, #EEEEEE, on the CSV."
    });
  }

  var myPodHeadline = "Pod " + myPodCount + " Headline";
  myPodHeadline = myArray[count][myPodHeadline];
  if (myPodHeadline === '') {
    myPodHeadline = "Missing Headline";
    errArray.push({
      "errMsg": 'Missing Headline',
      "OMSID": omsid,
      "errDesc": "You are missing a headline for pod number " + myPodCount + "."
    });
  }

  var lastFrame;

  var myPodCopyHeadline = "Pod " + myPodCount + " Copy Headline";
  myPodCopyHeadline = trimText(myArray[count][myPodCopyHeadline]);

  var myPodCopy = "Pod " + myPodCount + " Copy";
  myPodCopy = trimText(myArray[count][myPodCopy]);

  var myPodSubhead = "Pod " + myPodCount + " Subhead";
  myPodSubhead = trimText(myArray[count][myPodSubhead]);

  var myPodBackground = "Pod " + myPodCount + " Background"
  myPodBackground = myArray[count][myPodBackground];
  if (myPodBackground === '') {
    myPodBackground = "No Background Image Found";
  }

  var myPodValue = "Pod " + myPodCount + " Value";
  myPodValue = trimText(myArray[count][myPodValue]);

  var myPodValue2 = "Pod " + myPodCount + " Value 2";
  myPodValue2 = trimText(myArray[count][myPodValue2]);

  var myPodValue3 = "Pod " + myPodCount + " Value 3";
  myPodValue3 = trimText(myArray[count][myPodValue3]);

  var myPodCaption = "Pod " + myPodCount + " Caption";
  myPodCaption = trimText(myArray[count][myPodCaption]);

  var captionParagraphStyle = "Caption Style";

  if (myPodColor === "#FFFFFF") {
    var strokeWeight = 3;
    var strokeColor = "#EEEEEE";
  } else {
    var strokeWeight = 0;
    var strokeColor = "None";
  }
  var headlineParagraphStyle = "Headline Style";
  var headTxtFrmY2 = 0;
  var headTxtFrmX2 = 0;

  if (rowType === "6-12") {
    headlineParagraphStyle = "Headline 6-12 Style";
    subheadParagraphStyle = "Subhead 6-12 Style";
    valueParagraphStyle = "Value 6-12 Style";
    headTxtFrmY2 = y2;
    headTxtFrmX2 = x2;
    if (myPodHeadline === 'Missing Headline') {
      headlineParagraphStyle = "Headline 6-12 Error Style";
    }
  }
  if (rowType === "4-12") {
    if (myPodColor === '#EEEEEE' || myPodColor === '#FFFFFF' || myPodColor === '#F5F2EA') {
      headlineParagraphStyle = "Headline 4-12 Style";
      subheadParagraphStyle = "Subhead 4-12 Style";
      valueParagraphStyle = "Value 4-12 Style";
    }
    if (myPodColor === '#333333' || myPodColor === 'FPO') {
      headlineParagraphStyle = "Headline 4-12 White Style";
      subheadParagraphStyle = "Subhead 4-12 White Style";
      valueParagraphStyle = "Value 4-12 White Style";
      captionParagraphStyle = 'Caption White Style';
    }
    headTxtFrmY2 = y2;
    headTxtFrmX2 = x2;
    if (myPodHeadline === 'Missing Headline') {
      headlineParagraphStyle = "Headline 4-12 Error Style";
    }
  }
  if (rowType === "3-12") {
    if (myPodColor === '#EEEEEE' || myPodColor === '#FFFFFF' || myPodColor === '#F5F2EA') {
      headlineParagraphStyle = "Headline 3-12 Style";
      subheadParagraphStyle = "Subhead 3-12 Style";
      valueParagraphStyle = "Value 3-12 Style";
    }
    if (myPodColor === '#333333' || myPodColor === 'FPO') {
      headlineParagraphStyle = "Headline 3-12 White Style";
      subheadParagraphStyle = "Subhead 3-12 White Style";
      valueParagraphStyle = "Value 3-12 White Style";
      captionParagraphStyle = "Caption White Style";
    }
    headTxtFrmY2 = y2;
    headTxtFrmX2 = x2;
    if (myPodHeadline === 'Missing Headline') {
      headlineParagraphStyle = "Headline 3-12 Error Style";
    }
  }
  if (rowType === "2-12") {
    if (myPodColor === '#EEEEEE' || myPodColor === '#FFFFFF' || myPodColor === '#F5F2EA') {
      headlineParagraphStyle = "Headline 2-12 Style";
      subheadParagraphStyle = "Subhead 2-12 Style";
      valueParagraphStyle = "Value 2-12 Style";
    }
    if (myPodColor === '#333333' || myPodColor === 'FPO') {
      headlineParagraphStyle = "Headline 2-12 White Style";
      subheadParagraphStyle = "Subhead 2-12 White Style";
      valueParagraphStyle = "Value 2-12 White Style";
      captionParagraphStyle = "Caption White Style";
    }
    headTxtFrmY2 = y2;
    headTxtFrmX2 = x2;
    if (myPodHeadline === 'Missing Headline') {
      headlineParagraphStyle = "Headline 2-12 Error Style";
    }
  }
  // ============================================== Create a version of the POD when Pod Type is blank or 'blank' ==================
  if (myPodType === '' || myPodType === 'blank' || myPodType === 'Blank') {
    var myClearPod = createRectangle(count, count, "ARTWORK", myPodName + "-clear-1", [y1, x1, y2, x2], ContentType.GRAPHIC_TYPE, strokeWeight, StrokeAlignment.INSIDE_ALIGNMENT, strokeColor, false, myPodColor, omsid);
    var myPod = createRectangle(count, count, "ARTWORK", myPodName + "-clear-2", [y1, x1, y2, x2], ContentType.GRAPHIC_TYPE, strokeWeight, StrokeAlignment.INSIDE_ALIGNMENT, strokeColor, false, myPodColor, omsid);
    var myPodGroupArray = [];
    myPodGroupArray.push(myClearPod, myPod);
    // Get the current page object
    var myPage = activePage(count);
    // Create a group object for the current page and add the array items to the group object
    var myGroup = myPage.groups.add(myPodGroupArray);
    // Name the group for further reference
    myGroup.name = myPodGroupName;
    // return the pod when the function is called to create the pod
    return myGroup;
  }
  // ============================================== End Blank Pod Type =============================================================
  // ============================================== Create the "A" version of the pod ==============================================
  if (myPodType === 'A') {
    var myClearPod = createRectangle(count, count, "ARTWORK", myPodName + "-clear", [y1, x1, y2, x2], ContentType.GRAPHIC_TYPE, strokeWeight, StrokeAlignment.INSIDE_ALIGNMENT, strokeColor, false, myPodColor, omsid);
    var myPod = createRectangle(count, count, "ARTWORK", myPodName, [y1, x1, y2, x2], ContentType.GRAPHIC_TYPE, strokeWeight, StrokeAlignment.INSIDE_ALIGNMENT, strokeColor, true, myPodColor, omsid);
    var myPodGroupArray = [];
    myPodGroupArray.push(myClearPod, myPod);
    // Get the current page object
    var myPage = activePage(count);
    // Create a group object for the current page and add the array items to the group object
    var myGroup = myPage.groups.add(myPodGroupArray);
    // Name the group for further reference
    myGroup.name = myPodGroupName;
    // return the pod when the function is called to create the pod
    return myGroup;
  } // ============================================== End Pod Type A ==============================================

  // ============================================== Create the "B" version of the pod ==============================================
  if (myPodType === 'B') {
    // TODO: Group all these items and possibly give it a name like "pod1"
    var myPod;
    // Create Array of Page Items to Group
    var myPodGroupArray = [];
    // How to use: createRectangle(itemNum, id, itemLayer, name, geometricBounds, contentType, strokeWeight, strokeAlignment, strokeColor, visible, fillColor)
    myPod = createRectangle(count, count, "ARTWORK", myPodName, [y1, x1, y2, x2], ContentType.GRAPHIC_TYPE, strokeWeight, StrokeAlignment.INSIDE_ALIGNMENT, strokeColor, true, myPodColor, omsid);
    // Place the background image if there is one
    if (myPodBackground === 'No Background Image Found') {
      var cf;
    } else {
      var cf = checkImageFile(dataFileLocation, myPodBackground, omsid);
      if (cf === true) {
        myPod.place(dataFileLocation + myPodBackground, false);
      }
    }
    // How to use: createTextFrame(itemNum, itemLayer, name, contentType, geometricBounds, contents, paragraphStyle, autoSizingReferencePoint, autoSizingType, verticalJustification)
    myHeadline = createTextFrame(count, "ARTWORK", "Pod Headline", ContentType.TEXT_TYPE, [y1 + 30, x1 + 30, y2 - 30, x2 - 30], myPodHeadline, headlineParagraphStyle, AutoSizingReferenceEnum.TOP_LEFT_POINT, AutoSizingTypeEnum.HEIGHT_ONLY, VerticalJustification.TOP_ALIGN);
    myPodGroupArray.push(myPod, myHeadline);
    // Get the location of the Headline in geometric bounds
    lastFrame = getTxtFrmGeometricBounds(myHeadline, omsid + ": headline");
    if (myPodSubhead != '') {
      // Create the subhead
      mySubhead = createTextFrame(count, "ARTWORK", "Pod Subhead", ContentType.TEXT_TYPE, [lastFrame.y2 + 33, x1 + 30, y2 - 30, x2 - 30], myPodSubhead, subheadParagraphStyle, AutoSizingReferenceEnum.TOP_LEFT_POINT, AutoSizingTypeEnum.HEIGHT_ONLY, VerticalJustification.TOP_ALIGN);
      lastFrame = getTxtFrmGeometricBounds(mySubhead, omsid + ": subhead");
      myPodGroupArray.push(mySubhead);
    }
    // Create the value text frame if it's not blank
    if (myPodValue != '') {
      //TODO: Figure out how to get the VALUE text to be 50% of the height of the pod
      var myValueOrigin = (rowHeight / 2 + y1);
      myValue = createTextFrame(count, "ARTWORK", "Pod Value", ContentType.TEXT_TYPE, [myValueOrigin, x1 + 30, y2 - 30, x2 - 30], myPodValue, valueParagraphStyle, AutoSizingReferenceEnum.TOP_LEFT_POINT, AutoSizingTypeEnum.HEIGHT_ONLY, VerticalJustification.TOP_ALIGN);
      lastFrame = getTxtFrmGeometricBounds(myValue, omsid + ": value");
      myPodGroupArray.push(myValue);
    }
    // Create the pod caption
    if (myPodCaption != '') {
      myCaption = createTextFrame(count, "ARTWORK", "Pod Caption", ContentType.TEXT_TYPE, [lastFrame.y2 + 30, x1 + 30, y2 - 30, x2 - 30], myPodCaption, captionParagraphStyle, AutoSizingReferenceEnum.BOTTOM_RIGHT_POINT, AutoSizingTypeEnum.HEIGHT_ONLY, VerticalJustification.BOTTOM_ALIGN);
      myPodGroupArray.push(myCaption);
    }
    // Get the current page object
    var myPage = activePage(count);
    // Create a group object for the current page and add the array items to the group object
    var myGroup = myPage.groups.add(myPodGroupArray);
    // Name the group for further reference
    myGroup.name = myPodGroupName;
    // return the pod when the function is called to create the pod
    return myGroup;
  } // ============================================== End Pod Type B ==============================================
  // ============================================== Create the "C" version of the pod ==============================================
  if (myPodType === 'C') {
    // TODO: Group all these items and possibly give it a name like "pod1"
    var myPod;
    // Create Array of Page Items to Group
    var myPodGroupArray = [];
    // How to use: createRectangle(itemNum, id, itemLayer, name, geometricBounds, contentType, strokeWeight, strokeAlignment, strokeColor, visible, fillColor)
    myPod = createRectangle(count, count, "ARTWORK", myPodName, [y1, x1, y2, x2], ContentType.GRAPHIC_TYPE, strokeWeight, StrokeAlignment.INSIDE_ALIGNMENT, strokeColor, true, myPodColor, omsid);
    // Place the background image if there is one
    if (myPodBackground === 'No Background Image Found') {
      var cf;
    } else {
      var cf = checkImageFile(dataFileLocation, myPodBackground, omsid);
      if (cf === true) {
        myPod.place(dataFileLocation + myPodBackground, false);
      }
    }
    // How to use: createTextFrame(itemNum, itemLayer, name, contentType, geometricBounds, contents, paragraphStyle, autoSizingReferencePoint, autoSizingType, verticalJustification)
    myHeadline = createTextFrame(count, "ARTWORK", "Pod Headline", ContentType.TEXT_TYPE, [y1 + 30, x1 + 30, y2 - 30, x2 - 30], myPodHeadline, headlineParagraphStyle, AutoSizingReferenceEnum.TOP_LEFT_POINT, AutoSizingTypeEnum.HEIGHT_ONLY, VerticalJustification.TOP_ALIGN);
    myPodGroupArray.push(myPod, myHeadline);
    // Get the location of the Headline in geometric bounds
    lastFrame = getTxtFrmGeometricBounds(myHeadline, omsid + ": value");
    // Create the pod caption
    if (myPodCaption != '') {
      myCaption = createTextFrame(count, "ARTWORK", "Pod Caption", ContentType.TEXT_TYPE, [lastFrame.y2 + 30, x1 + 30, y2 - 30, x2 - 30], myPodCaption, captionParagraphStyle, AutoSizingReferenceEnum.BOTTOM_RIGHT_POINT, AutoSizingTypeEnum.HEIGHT_ONLY, VerticalJustification.BOTTOM_ALIGN);
      myPodGroupArray.push(myCaption);
    }
    // Get the current page object
    var myPage = activePage(count);
    // Create a group object for the current page and add the array items to the group object
    var myGroup = myPage.groups.add(myPodGroupArray);
    // Name the group for further reference
    myGroup.name = myPodGroupName;
    // return the pod when the function is called to create the pod
    return myGroup;
  } // ============================================== End Pod Type C ==============================================
  // ============================================== Create the "D" version of the pod ==============================================
  if (myPodType === 'D') {
    // TODO: Group all these items and possibly give it a name like "pod1"
    var myPod;
    // Create Array of Page Items to Group
    var myPodGroupArray = [];
    // How to use: createRectangle(itemNum, id, itemLayer, name, geometricBounds, contentType, strokeWeight, strokeAlignment, strokeColor, visible, fillColor)
    myPod = createRectangle(count, count, "ARTWORK", myPodName, [y1, x1, y2, x2], ContentType.GRAPHIC_TYPE, strokeWeight, StrokeAlignment.INSIDE_ALIGNMENT, strokeColor, true, myPodColor, omsid);
    // Place the background image if there is one
    if (myPodBackground === 'No Background Image Found') {
      var cf;
    } else {
      var cf = checkImageFile(dataFileLocation, myPodBackground, omsid);
      if (cf === true) {
        myPod.place(dataFileLocation + myPodBackground, false);
      }
    }
    // How to use: createTextFrame(itemNum, itemLayer, name, contentType, geometricBounds, contents, paragraphStyle, autoSizingReferencePoint, autoSizingType, verticalJustification)
    myHeadline = createTextFrame(count, "ARTWORK", "Pod Headline", ContentType.TEXT_TYPE, [y1 + 30, x1 + 30, y2 - 30, x2 - 30], myPodHeadline, headlineParagraphStyle, AutoSizingReferenceEnum.TOP_LEFT_POINT, AutoSizingTypeEnum.HEIGHT_ONLY, VerticalJustification.TOP_ALIGN);
    myPodGroupArray.push(myPod, myHeadline);
    // Get the location of the Headline in geometric bounds
    lastFrame = getTxtFrmGeometricBounds(myHeadline, omsid + ": headline");
    if (myPodSubhead != '') {
      // Create the subhead
      mySubhead = createTextFrame(count, "ARTWORK", "Pod Subhead", ContentType.TEXT_TYPE, [lastFrame.y2 + 33, x1 + 30, y2 - 30, x2 - 30], myPodSubhead, subheadParagraphStyle, AutoSizingReferenceEnum.TOP_LEFT_POINT, AutoSizingTypeEnum.HEIGHT_ONLY, VerticalJustification.TOP_ALIGN);
      lastFrame = getTxtFrmGeometricBounds(mySubhead, omsid + ": subhead");
      myPodGroupArray.push(mySubhead);
    }
    // Create the pod caption
    if (myPodCaption != '') {
      myCaption = createTextFrame(count, "ARTWORK", "Pod Caption", ContentType.TEXT_TYPE, [lastFrame.y2 + 30, x1 + 30, y2 - 30, x2 - 30], myPodCaption, captionParagraphStyle, AutoSizingReferenceEnum.BOTTOM_RIGHT_POINT, AutoSizingTypeEnum.HEIGHT_ONLY, VerticalJustification.BOTTOM_ALIGN);
      myPodGroupArray.push(myCaption);
    }
    // Get the current page object
    var myPage = activePage(count);
    // Create a group object for the current page and add the array items to the group object
    var myGroup = myPage.groups.add(myPodGroupArray);
    // Name the group for further reference
    myGroup.name = myPodGroupName;
    // return the pod when the function is called to create the pod
    return myGroup;
  } // ============================================== End Pod Type D ==============================================
  // ============================================== Create the "E" version of the pod ==============================================
  if (myPodType === 'E') {
    // TODO: Group all these items and possibly give it a name like "pod1"
    var myPod;
    // Create Array of Page Items to Group
    var myPodGroupArray = [];
    // How to use: createRectangle(itemNum, id, itemLayer, name, geometricBounds, contentType, strokeWeight, strokeAlignment, strokeColor, visible, fillColor)
    myPod = createRectangle(count, count, "ARTWORK", myPodName, [y1, x1, y2, x2], ContentType.GRAPHIC_TYPE, strokeWeight, StrokeAlignment.INSIDE_ALIGNMENT, strokeColor, true, myPodColor, omsid);
    // Place the background image if there is one
    if (myPodBackground === 'No Background Image Found') {
      var cf;
    } else {
      var cf = checkImageFile(dataFileLocation, myPodBackground, omsid);
      if (cf === true) {
        myPod.place(dataFileLocation + myPodBackground, false);
      }
    }
    // How to use: createTextFrame(itemNum, itemLayer, name, contentType, geometricBounds, contents, paragraphStyle, autoSizingReferencePoint, autoSizingType, verticalJustification)
    myHeadline = createTextFrame(count, "ARTWORK", "Pod Headline", ContentType.TEXT_TYPE, [y1 + 30, x1 + 30, y2 - 30, x2 - 30], myPodHeadline, headlineParagraphStyle, AutoSizingReferenceEnum.TOP_LEFT_POINT, AutoSizingTypeEnum.HEIGHT_ONLY, VerticalJustification.TOP_ALIGN);
    myPodGroupArray.push(myPod, myHeadline);
    // Get the location of the Headline in geometric bounds
    lastFrame = getTxtFrmGeometricBounds(myHeadline, omsid + ": headline");
    // Create the pod caption
    if (myPodCaption != '') {
      myCaption = createTextFrame(count, "ARTWORK", "Pod Caption", ContentType.TEXT_TYPE, [lastFrame.y2 + 30, x1 + 30, y2 - 30, x2 - 30], myPodCaption, captionParagraphStyle, AutoSizingReferenceEnum.BOTTOM_RIGHT_POINT, AutoSizingTypeEnum.HEIGHT_ONLY, VerticalJustification.BOTTOM_ALIGN);
      myPodGroupArray.push(myCaption);
    }
    // Get the current page object
    var myPage = activePage(count);
    // Create a group object for the current page and add the array items to the group object
    var myGroup = myPage.groups.add(myPodGroupArray);
    // Name the group for further reference
    myGroup.name = myPodGroupName;
    // return the pod when the function is called to create the pod
    return myGroup;
  } // ============================================== End Pod Type E ==============================================
  // ============================================== Create the "F" version of the pod ==============================================
  if (myPodType === 'F') {
    // TODO: Group all these items and possibly give it a name like "pod1"
    var myPod;
    // Create Array of Page Items to Group
    var myPodGroupArray = [];
    // How to use: createRectangle(itemNum, id, itemLayer, name, geometricBounds, contentType, strokeWeight, strokeAlignment, strokeColor, visible, fillColor)
    myPod = createRectangle(count, count, "ARTWORK", myPodName, [y1, x1, y2, x2], ContentType.GRAPHIC_TYPE, strokeWeight, StrokeAlignment.INSIDE_ALIGNMENT, strokeColor, true, myPodColor, omsid);
    // Place the background image if there is one
    if (myPodBackground === 'No Background Image Found') {
      var cf;
    } else {
      var cf = checkImageFile(dataFileLocation, myPodBackground, omsid);
      if (cf === true) {
        myPod.place(dataFileLocation + myPodBackground, false);
      }
    }
    // How to use: createTextFrame(itemNum, itemLayer, name, contentType, geometricBounds, contents, paragraphStyle, autoSizingReferencePoint, autoSizingType, verticalJustification)
    myHeadline = createTextFrame(count, "ARTWORK", "Pod Headline", ContentType.TEXT_TYPE, [y1 + 30, x1 + 30, y2 - 30, x2 - 30], myPodHeadline, headlineParagraphStyle, AutoSizingReferenceEnum.TOP_LEFT_POINT, AutoSizingTypeEnum.HEIGHT_ONLY, VerticalJustification.TOP_ALIGN);
    myPodGroupArray.push(myPod, myHeadline);
    // Get the location of the Headline in geometric bounds
    lastFrame = getTxtFrmGeometricBounds(myHeadline, omsid + ": headline");
    // Create the value text frame if it's not blank
    if (myPodValue != '') {
      //TODO: Figure out how to get the VALUE text to be 50% of the height of the pod
      var myValueOrigin = (rowHeight / 3 + y1);
      myValue = createTextFrame(count, "ARTWORK", "Pod Value", ContentType.TEXT_TYPE, [myValueOrigin, x1 + 30, y2 - 30, x2 - 30], myPodValue, valueParagraphStyle, AutoSizingReferenceEnum.TOP_LEFT_POINT, AutoSizingTypeEnum.HEIGHT_ONLY, VerticalJustification.TOP_ALIGN);
      lastFrame = getTxtFrmGeometricBounds(myValue, omsid + ": value");
      myPodGroupArray.push(myValue);
    }
    // Create the value 2 text frame if it's not blank
    if (myPodValue2 != '') {
      var myValue2Origin = (lastFrame.y2 + 60);
      myValue2 = createTextFrame(count, "ARTWORK", "Pod Value 2", ContentType.TEXT_TYPE, [myValue2Origin, x1 + 30, y2 - 30, x2 - 30], myPodValue2, valueParagraphStyle, AutoSizingReferenceEnum.TOP_LEFT_POINT, AutoSizingTypeEnum.HEIGHT_ONLY, VerticalJustification.TOP_ALIGN);
      lastFrame = getTxtFrmGeometricBounds(myValue2, omsid + ": value 2");
      myPodGroupArray.push(myValue2);
    }
    // Create the value 3 text frame if it's not blank
    if (myPodValue3 != '') {
      var myValue3Origin = (lastFrame.y2 + 60);
      myValue3 = createTextFrame(count, "ARTWORK", "Pod Value 3", ContentType.TEXT_TYPE, [myValue3Origin, x1 + 30, y2 - 30, x2 - 30], myPodValue3, valueParagraphStyle, AutoSizingReferenceEnum.TOP_LEFT_POINT, AutoSizingTypeEnum.HEIGHT_ONLY, VerticalJustification.TOP_ALIGN);
      lastFrame = getTxtFrmGeometricBounds(myValue3, omsid + ": value 3");
      myPodGroupArray.push(myValue3);
    }
    // Create the pod caption
    if (myPodCaption != '') {
      myCaption = createTextFrame(count, "ARTWORK", "Pod Caption", ContentType.TEXT_TYPE, [lastFrame.y2 + 30, x1 + 30, y2 - 30, x2 - 30], myPodCaption, captionParagraphStyle, AutoSizingReferenceEnum.BOTTOM_RIGHT_POINT, AutoSizingTypeEnum.HEIGHT_ONLY, VerticalJustification.BOTTOM_ALIGN);
      myPodGroupArray.push(myCaption);
    }
    // Get the current page object
    var myPage = activePage(count);
    // Create a group object for the current page and add the array items to the group object
    var myGroup = myPage.groups.add(myPodGroupArray);
    // Name the group for further reference
    myGroup.name = myPodGroupName;
    // return the pod when the function is called to create the pod
    return myGroup;
  } // ============================================== End Pod Type F ==============================================
  // ============================================== Create the "G" version of the pod ==============================================
  if (myPodType === 'G') {
    // TODO: Group all these items and possibly give it a name like "pod1"
    var myPod;
    // Create Array of Page Items to Group
    var myPodGroupArray = [];
    // How to use: createRectangle(itemNum, id, itemLayer, name, geometricBounds, contentType, strokeWeight, strokeAlignment, strokeColor, visible, fillColor)
    myPod = createRectangle(count, count, "ARTWORK", myPodName, [y1, x1, y2, x2], ContentType.GRAPHIC_TYPE, strokeWeight, StrokeAlignment.INSIDE_ALIGNMENT, strokeColor, true, myPodColor, omsid);
    // Place the background image if there is one
    if (myPodBackground === 'No Background Image Found') {
      var cf;
    } else {
      var cf = checkImageFile(dataFileLocation, myPodBackground, omsid);
      if (cf === true) {
        myPod.place(dataFileLocation + myPodBackground, false);
      }
    }
    myPodGroupArray.push(myPod);
    // How to use: createTextFrame(itemNum, itemLayer, name, contentType, geometricBounds, contents, paragraphStyle, autoSizingReferencePoint, autoSizingType, verticalJustification)
    myHeadline = createTextFrame(count, "ARTWORK", "Pod Headline", ContentType.TEXT_TYPE, [y1 + 30, x1 + 30, y2 - 30, x2 - 30], myPodHeadline, headlineParagraphStyle, AutoSizingReferenceEnum.TOP_LEFT_POINT, AutoSizingTypeEnum.HEIGHT_ONLY, VerticalJustification.TOP_ALIGN);
    myPodGroupArray.push(myHeadline);
    // Get the location of the Headline in geometric bounds
    lastFrame = getTxtFrmGeometricBounds(myHeadline, omsid + ": headline");
    // Create the value text frame if it's not blank
    if (myPodValue != '') {
      //TODO: Figure out how to get the VALUE text to be 50% of the height of the pod
      var myValueOrigin = (rowHeight / 2.5 + y1);
      myValue = createTextFrame(count, "ARTWORK", "Pod Value", ContentType.TEXT_TYPE, [myValueOrigin, x1 + 30, y2 - 30, x2 - 30], myPodValue, valueParagraphStyle, AutoSizingReferenceEnum.TOP_LEFT_POINT, AutoSizingTypeEnum.HEIGHT_ONLY, VerticalJustification.TOP_ALIGN);
      lastFrame = getTxtFrmGeometricBounds(myValue, omsid + ": value");
      myPodGroupArray.push(myValue);
    }
    // Create the value 2 text frame if it's not blank
    if (myPodValue2 != '') {
      var myValue2Origin = (lastFrame.y2 + 60);
      myValue2 = createTextFrame(count, "ARTWORK", "Pod Value 2", ContentType.TEXT_TYPE, [myValue2Origin, x1 + 30, y2 - 30, x2 - 30], myPodValue2, valueParagraphStyle, AutoSizingReferenceEnum.TOP_LEFT_POINT, AutoSizingTypeEnum.HEIGHT_ONLY, VerticalJustification.TOP_ALIGN);
      lastFrame = getTxtFrmGeometricBounds(myValue2, omsid + ": value 2");
      myPodGroupArray.push(myValue2);
    }
    // Create the pod caption
    if (myPodCaption != '') {
      myCaption = createTextFrame(count, "ARTWORK", "Pod Caption", ContentType.TEXT_TYPE, [lastFrame.y2 + 30, x1 + 30, y2 - 30, x2 - 30], myPodCaption, captionParagraphStyle, AutoSizingReferenceEnum.BOTTOM_RIGHT_POINT, AutoSizingTypeEnum.HEIGHT_ONLY, VerticalJustification.BOTTOM_ALIGN);
      myPodGroupArray.push(myCaption);
    }
    // Get the current page object
    var myPage = activePage(count);
    // Create a group object for the current page and add the array items to the group object
    var myGroup = myPage.groups.add(myPodGroupArray);
    // Name the group for further reference
    myGroup.name = myPodGroupName;
    // return the pod when the function is called to create the pod
    return myGroup;
  } // ============================================== End Pod Type G ==============================================
  // ============================================== Create the "H" version of the pod ==============================================
  if (myPodType === 'H') {
    // TODO: Group all these items and possibly give it a name like "pod1"
    var myPod;
    // Create Array of Page Items to Group
    var myPodGroupArray = [];
    var myClearPod = createRectangle(count, count, "ARTWORK", myPodName + "-clear", [y1, x1, y2, x2], ContentType.GRAPHIC_TYPE, strokeWeight, StrokeAlignment.INSIDE_ALIGNMENT, strokeColor, false, myPodColor, omsid);
    // How to use: createRectangle(itemNum, id, itemLayer, name, geometricBounds, contentType, strokeWeight, strokeAlignment, strokeColor, visible, fillColor)
    myPod = createRectangle(count, count, "ARTWORK", myPodName, [y1, x1, y2, x2], ContentType.GRAPHIC_TYPE, strokeWeight, StrokeAlignment.INSIDE_ALIGNMENT, strokeColor, true, myPodColor, omsid);
    // Place the background image if there is one
    if (myPodBackground === 'No Background Image Found') {
      var cf;
    } else {
      var cf = checkImageFile(dataFileLocation, myPodBackground, omsid);
      if (cf === true) {
        myPod.place(dataFileLocation + myPodBackground, false);
      }
    }
    myPodGroupArray.push(myClearPod, myPod);
    // Get the current page object
    var myPage = activePage(count);
    // Create a group object for the current page and add the array items to the group object
    var myGroup = myPage.groups.add(myPodGroupArray);
    // Name the group for further reference
    myGroup.name = myPodGroupName;
    // return the pod when the function is called to create the pod
    return myGroup;
  } // ============================================== End Pod Type H ==============================================
  // ============================================== Create the "I" version of the pod ==============================================
  if (myPodType === 'I') {
    // TODO: Group all these items and possibly give it a name like "pod1"
    var myPod;
    var myCopyHeadline;
    var myCopy;
    // Create Array of Page Items to Group
    var myPodGroupArray = [];
    var myClearPod = createRectangle(count, count, "ARTWORK", myPodName + "-clear", [y1, x1, y2, x2], ContentType.GRAPHIC_TYPE, strokeWeight, StrokeAlignment.INSIDE_ALIGNMENT, strokeColor, false, myPodColor, omsid);
    // How to use: createRectangle(itemNum, id, itemLayer, name, geometricBounds, contentType, strokeWeight, strokeAlignment, strokeColor, visible, fillColor)
    myPod = createRectangle(count, count, "ARTWORK", myPodName, [y1, x1, y2, x2], ContentType.GRAPHIC_TYPE, strokeWeight, StrokeAlignment.INSIDE_ALIGNMENT, strokeColor, true, myPodColor, omsid);

    lastFrame = getTxtFrmGeometricBounds(myPod, omsid + ": " + myPodName);

    myCopyHeadline = createTextFrame(count, "ARTWORK", "Pod Copy Headline", ContentType.TEXT_TYPE, [lastFrame.y2 + myRowMargin, x1, lastFrame.y2 + 40, x2], myPodCopyHeadline, "Copy Headline Style", AutoSizingReferenceEnum.TOP_CENTER_POINT, AutoSizingTypeEnum.HEIGHT_ONLY, VerticalJustification.TOP_ALIGN);

    lastFrame = getTxtFrmGeometricBounds(myCopyHeadline, omsid + ": copy headline");

    myCopy = createTextFrame(count, "ARTWORK", "Pod Copy", ContentType.TEXT_TYPE, [lastFrame.y2 + myRowMargin, x1, lastFrame.y2 + 40, x2], myPodCopy, "Copy Style", AutoSizingReferenceEnum.TOP_CENTER_POINT, AutoSizingTypeEnum.HEIGHT_ONLY, VerticalJustification.TOP_ALIGN);
    // Place the background image if there is one
    if (myPodBackground === 'No Background Image Found') {
      var cf;
    } else {
      var cf = checkImageFile(dataFileLocation, myPodBackground, omsid);
      if (cf === true) {
        myPod.place(dataFileLocation + myPodBackground, false);
      }
    }
    myPodGroupArray.push(myClearPod, myPod, myCopyHeadline, myCopy);
    // Get the current page object
    var myPage = activePage(count);
    // Create a group object for the current page and add the array items to the group object
    var myGroup = myPage.groups.add(myPodGroupArray);

    lastFrame = getTxtFrmGeometricBounds(myGroup, omsid + " get the 4-12 row dimensions");

    //alert(lastFrame.y2);
    alert("I'm Sorry!");
    // Name the group for further reference
    myGroup.name = myPodGroupName;
    // return the pod when the function is called to create the pod
    return myGroup;
  } // ============================================== End Pod Type I ==============================================

}

function createRow(count, origin, rowType, rowCount, rowHeight, myRowMargin, myLeftMargin, myRightMargin, myTopMargin, myBottomMargin, omsid, myPodCount, myPodStart) {
  origin = Number(origin);
  rowHeight = Number(rowHeight);
  rowCount = Number(rowCount);
  var myRowGroupArray = [];
  var myRowGroup;
  var myPage = activePage(count);
  if (rowHeight === 0 && rowCount >= 1) {
    throw new TypeError('Your CSV file needs revision: Row Height cannot be "0" if Row Count is equal to or greater than "1" for pod #' + myPodCount + ' on OMSID: ' + omsid);
  }
  var lastPod;
  var finalRowHeight;
  var myLoopCount = 1;
  for (var i = 0; i < rowCount; i++) {
    // Create Rows for 6-12 Pods
    if (rowType === '6-12') {
      if (myLoopCount === 1) {
        // myPodStart is the name of the pod that includes the number, "Pod 1 Copy Headline" It's written this way so that it will count up as this loop runs through creating the pods in possible multiple rows, currently there's no cap on the amount of rows, just the limits of InDesign
        myPodStart = 1;
        //createPod(count, origin, rowType, myPodCount, y1, x1, y2, x2, myRowMargin, rowHeight, myLeftMargin, myRightMargin, myTopMargin, myBottomMargin, omsid)
        var pod1 = createPod(count, origin, rowType, myPodStart, origin, myLeftMargin, origin + rowHeight, myLeftMargin + 950, myRowMargin, rowHeight, myLeftMargin, myRightMargin, myTopMargin, myBottomMargin, omsid);

        lastPod = getTxtFrmGeometricBounds(pod1, omsid + ": create row 6-12 pod " + myPodStart);
        myPodStart++;
        var pod2 = createPod(count, origin, rowType, myPodStart, origin, lastPod.x2 + myRowMargin, origin + rowHeight, lastPod.x2 + myRowMargin + 465, myRowMargin, rowHeight, myLeftMargin, myRightMargin, myTopMargin, myBottomMargin, omsid);

        lastPod = getTxtFrmGeometricBounds(pod2, omsid + ": create row 6-12 pod " + myPodStart);
        myPodStart++;
        var pod3 = createPod(count, origin, rowType, myPodStart, origin, lastPod.x2 + myRowMargin, origin + rowHeight, lastPod.x2 + myRowMargin + 465, myRowMargin, rowHeight, myLeftMargin, myRightMargin, myTopMargin, myBottomMargin, omsid);

        finalRowHeight = getTxtFrmGeometricBounds(pod3, omsid + ": create row 6-12 pod " + myPodStart);
        finalRowHeight = finalRowHeight.y2;
        myPodStart++;
      }
    }
    // Create Rows for 4-12 Pods
    if (rowType === '4-12') {
      if (myLoopCount > 1) {
        origin = Number(finalRowHeight) + myRowMargin;
      } else {
        myPodStart++;
      }
      // myPodStart is the name of the pod that includes the number, "Pod 1 Copy Headline" It's written this way so that it will count up as this loop runs through creating the pods in possible multiple rows, currently there's no cap on the amount of rows, just the limits of InDesign
      var pod1 = createPod(count, origin, rowType, myPodStart, origin, myLeftMargin, origin + rowHeight, myLeftMargin + 627, myRowMargin, rowHeight, myLeftMargin, myRightMargin, myTopMargin, myBottomMargin, omsid);

      lastPod = getTxtFrmGeometricBounds(pod1, omsid + ": create row 4-12 pod " + myPodStart);
      myPodStart++;
      var pod2 = createPod(count, origin, rowType, myPodStart, origin, lastPod.x2 + myRowMargin, origin + rowHeight, lastPod.x2 + myRowMargin + 627, myRowMargin, rowHeight, myLeftMargin, myRightMargin, myTopMargin, myBottomMargin, omsid);

      lastPod = getTxtFrmGeometricBounds(pod2, omsid + ": create row 4-12 pod " + myPodStart);
      myPodStart++;
      var pod3 = createPod(count, origin, rowType, myPodStart, origin, lastPod.x2 + myRowMargin, origin + rowHeight, lastPod.x2 + myRowMargin + 627, myRowMargin, rowHeight, myLeftMargin, myRightMargin, myTopMargin, myBottomMargin, omsid);

      myRowGroupArray.push(pod1, pod2, pod3);
      myGroup = myPage.groups.add(myRowGroupArray);
      finalRowHeight = getTxtFrmGeometricBounds(myGroup, omsid + ": create row 4-12 pod " + myPodStart);
      finalRowHeight = finalRowHeight.y2;
      myGroup.ungroup();
      myPodStart++;
    }
    // Create Rows for 3-12 Pods
    if (rowType === '3-12') {
      if (myLoopCount > 1) {
        origin = Number(finalRowHeight) + myRowMargin;
      } else {
        myPodStart++;
      }
      var pod1 = createPod(count, origin, rowType, myPodStart, origin, myLeftMargin, origin + rowHeight, myLeftMargin + 465, myRowMargin, rowHeight, myLeftMargin, myRightMargin, myTopMargin, myBottomMargin, omsid);

      lastPod = getTxtFrmGeometricBounds(pod1, omsid + ": create row 3-12 pod " + myPodStart);
      myPodStart++;
      var pod2 = createPod(count, origin, rowType, myPodStart, origin, lastPod.x2 + myRowMargin, origin + rowHeight, lastPod.x2 + myRowMargin + 465, myRowMargin, rowHeight, myLeftMargin, myRightMargin, myTopMargin, myBottomMargin, omsid);

      lastPod = getTxtFrmGeometricBounds(pod2, omsid + ": create row 3-12 pod " + myPodStart);
      myPodStart++;
      var pod3 = createPod(count, origin, rowType, myPodStart, origin, lastPod.x2 + myRowMargin, origin + rowHeight, lastPod.x2 + myRowMargin + 465, myRowMargin, rowHeight, myLeftMargin, myRightMargin, myTopMargin, myBottomMargin, omsid);

      lastPod = getTxtFrmGeometricBounds(pod3, omsid + ": create row 3-12 pod " + myPodStart);
      myPodStart++;
      var pod4 = createPod(count, origin, rowType, myPodStart, origin, lastPod.x2 + myRowMargin, origin + rowHeight, lastPod.x2 + myRowMargin + 465, myRowMargin, rowHeight, myLeftMargin, myRightMargin, myTopMargin, myBottomMargin, omsid);

      myRowGroupArray.push(pod1, pod2, pod3, pod4);
      myGroup = myPage.groups.add(myRowGroupArray);
      finalRowHeight = getTxtFrmGeometricBounds(myGroup, omsid + ": create row 3-12 pod " + myPodStart);
      finalRowHeight = finalRowHeight.y2;
      myGroup.ungroup();
      myPodStart++;
    }
    // Create Rows for 2-12 Pods
    // TODO: You still need to fix the function calls to create the PODs in the below script for 2-12s
    if (rowType === '2-12') {
      if (myLoopCount > 1) {
        origin = Number(finalRowHeight) + myRowMargin;
      } else {
        myPodStart++;
      }
      var pod1 = createPod(count, origin, rowType, myPodStart, origin, myLeftMargin, origin + rowHeight, myLeftMargin + 303, myRowMargin, rowHeight, myLeftMargin, myRightMargin, myTopMargin, myBottomMargin, omsid);

      lastPod = getTxtFrmGeometricBounds(pod1, omsid + ": create row 2-12 pod " + myPodStart);
      myPodStart++;
      var pod2 = createPod(count, origin, rowType, myPodStart, origin, lastPod.x2 + myRowMargin, origin + rowHeight, lastPod.x2 + myRowMargin + 303, myRowMargin, rowHeight, myLeftMargin, myRightMargin, myTopMargin, myBottomMargin, omsid);

      lastPod = getTxtFrmGeometricBounds(pod2, omsid + ": create row 2-12 pod " + myPodStart);
      myPodStart++;
      var pod3 = createPod(count, origin, rowType, myPodStart, origin, lastPod.x2 + myRowMargin, origin + rowHeight, lastPod.x2 + myRowMargin + 303, myRowMargin, rowHeight, myLeftMargin, myRightMargin, myTopMargin, myBottomMargin, omsid);

      lastPod = getTxtFrmGeometricBounds(pod3, omsid + ": create row 2-12 pod " + myPodStart);
      myPodStart++;
      var pod4 = createPod(count, origin, rowType, myPodStart, origin, lastPod.x2 + myRowMargin, origin + rowHeight, lastPod.x2 + myRowMargin + 303, myRowMargin, rowHeight, myLeftMargin, myRightMargin, myTopMargin, myBottomMargin, omsid);

      lastPod = getTxtFrmGeometricBounds(pod4, omsid + ": create row 2-12 pod " + myPodStart);
      myPodStart++;
      var pod5 = createPod(count, origin, rowType, myPodStart, origin, lastPod.x2 + myRowMargin, origin + rowHeight, lastPod.x2 + myRowMargin + 303, myRowMargin, rowHeight, myLeftMargin, myRightMargin, myTopMargin, myBottomMargin, omsid);

      lastPod = getTxtFrmGeometricBounds(pod5, omsid + ": create row 2-12 pod " + myPodStart);
      myPodStart++;
      var pod6 = createPod(count, origin, rowType, myPodStart, origin, lastPod.x2 + myRowMargin, origin + rowHeight, lastPod.x2 + myRowMargin + 303, myRowMargin, rowHeight, myLeftMargin, myRightMargin, myTopMargin, myBottomMargin, omsid);

      myRowGroupArray.push(pod1, pod2, pod3, pod4, pod5, pod6);
      myGroup = myPage.groups.add(myRowGroupArray);
      finalRowHeight = getTxtFrmGeometricBounds(myGroup, omsid + ": create row 2-12 pod " + myPodStart);
      finalRowHeight = finalRowHeight.y2;
      myGroup.ungroup();
      myPodStart++;
    }
    myLoopCount++;
  } //end loop
  return finalRowHeight;
}

function calculatePageHeight(myTopMargin, myBottomMargin, myRowMargin, brandBannerHeight, brandFooterHeight, banner1Height, banner2Height, row1Height, row1Count, row1Type, row2Height, row2Count, brandBanner, banner1, banner2, brandFooter) {
  var bb, b1, b2, bf, r1H, r2H;
  // handle banners
  if (brandBanner === 'TRUE') {
    bb = brandBannerHeight + myRowMargin;
  } else {
    bb = 0;
  }
  if (banner1 === 'TRUE') {
    b1 = banner1Height + myRowMargin;
  } else {
    b1 = 0;
  }
  if (banner2 === 'TRUE') {
    b2 = banner2Height + myRowMargin;
  } else {
    b2 = 0;
  }
  if (brandFooter === 'TRUE') {
    bf = brandFooterHeight + myRowMargin;
  } else {
    bf = 0;
  }
  // handle row 1 if it exists and exclude multiples of 6-12 version
  if (row1Count >= 1 || row1Height > 0 || row1Height !== '') { // only calculate if there's at least one count of row 1, else return top margin only
    if (row1Type === '6-12') {
      r1H = row1Height + myRowMargin;
    }
    if (row1Type === '4-12' || row1Type === '3-12' || row1Type === '2-12') {
      r1H = ((row1Height + myRowMargin) * row1Count);
    }
  } else {
    r1H = 0;
  }
  // handle row 2 if it exists
  if (row2Count >= 1 || row2Height > 0 || row2Height !== '') {
    r2H = ((row2Height + myRowMargin) * row2Count);
  } else {
    r2H = 0;
  }
  return Number(myTopMargin + bb + r1H + r2H + b1 + b2 + bf);
}

// Create Slug
function createSlug(count, omsid, productName, brandName, productImage, pageNumber, pageCount, pageWidth, pageHeight, dataFileLocation) {
  // How to create a text frame: createTextFrame(itemNum, itemLayer, name, contentType, geometricBounds, contents, paragraphStyle, autoSizingReferencePoint, autoSizingType, verticalJustification)
  if (brandName === '') {
    brandName = "No Brand Name Listed";
  }
  var pageHeight = Number(pageHeight);
  var pageWidth = Number(pageWidth);
  var creationDate = new Date().toLocaleDateString();
  createRectangle(count, count, "SLUG", "Slug Background", [pageHeight, 0, pageHeight + 400, pageWidth], ContentType.UNASSIGNED, 0, StrokeAlignment.INSIDE_ALIGNMENT, "None", true, "#333333", omsid);
  var omsidTxtFrm = createTextFrame(count, "OMSID", "OMSID", ContentType.TEXT_TYPE, [pageHeight + 30, 30, pageHeight + 80, 360], omsid, "OMSID Style", AutoSizingReferenceEnum.TOP_LEFT_POINT, AutoSizingTypeEnum.OFF, VerticalJustification.TOP_ALIGN);
  //getTxtFrmGeometricBounds(omsidTxtFrm);
  //var omsidTxtFrmH = textFrameHeight(omsidTxtFrm);
  var omsidTxtFrmH = getTextFrmY2(omsidTxtFrm);
  var productNameTxtFrm = createTextFrame(count, "SLUG", "Product Name", ContentType.TEXT_TYPE, [omsidTxtFrmH + 30, 30, omsidTxtFrmH + 50, 800], productName, "Slug Style", AutoSizingReferenceEnum.TOP_LEFT_POINT, AutoSizingTypeEnum.OFF, VerticalJustification.TOP_ALIGN);
  var productNameTxtFrmH = getTextFrmY2(productNameTxtFrm);
  var brandNameTxtFrm = createTextFrame(count, "SLUG", "Brand Name", ContentType.TEXT_TYPE, [productNameTxtFrmH + 30, 30, productNameTxtFrmH + 50, 800], brandName, "Slug Style", AutoSizingReferenceEnum.TOP_LEFT_POINT, AutoSizingTypeEnum.OFF, VerticalJustification.TOP_ALIGN);
  var brandNameTxtFrmH = getTextFrmY2(brandNameTxtFrm);
  var productURLTxtFrm = createTextFrame(count, "SLUG", "Product URL", ContentType.TEXT_TYPE, [brandNameTxtFrmH + 30, 30, brandNameTxtFrmH + 50, 800], "https://www.homedepot.com/p/" + omsid, "Slug Style", AutoSizingReferenceEnum.TOP_LEFT_POINT, AutoSizingTypeEnum.OFF, VerticalJustification.TOP_ALIGN);
  var productURLTxtFrmH = getTextFrmY2(productURLTxtFrm);
  var creationDateTxtFrm = createTextFrame(count, "SLUG", "Creation Date", ContentType.TEXT_TYPE, [pageHeight + 400 - 30, pageWidth - 40, pageHeight + 400 - 60, pageWidth - 280], creationDate, "Slug Style", AutoSizingReferenceEnum.TOP_LEFT_POINT, AutoSizingTypeEnum.OFF, VerticalJustification.TOP_ALIGN);
  var pageNumberTxtFrm = createTextFrame(count, "SLUG", "Page Numbers", ContentType.TEXT_TYPE, [pageHeight + 400 - 60, pageWidth - 40, pageHeight + 400 - 120, pageWidth - 280], "Page " + pageNumber + " of " + pageCount, "Slug Style", AutoSizingReferenceEnum.TOP_LEFT_POINT, AutoSizingTypeEnum.OFF, VerticalJustification.TOP_ALIGN);
  // Check to see if the Product Image cell is blank, if blank then don't place an image
  if (productImage != "") {
    // Check if image file is actually found on system in the correct location
    var cf = checkImageFile(dataFileLocation, productImage, omsid);
    if (cf === true) {
      var productImageFrm = createRectangle(count, count, "SLUG", "Product Image", [pageHeight + 30, (pageWidth / 1.5) - 150, pageHeight + 30 + 300, (pageWidth / 1.5) + 150], ContentType.GRAPHIC_TYPE, 0, StrokeAlignment.INSIDE_ALIGNMENT, "#EEEEEE", true, "None", omsid);
      productImageFrm.place(dataFileLocation + productImage, false);
    }
  }
}

// Parse CSV Text
// This function solves the problem of a comma in an Excel cell. However, it does not solve the issue of special characters.
function parseCSV(sep, the_string) {
  for (var foo = the_string.split(sep = sep || ","), x = foo.length - 1, tl; x >= 0; x--) {
    if (foo[x].replace(/"\s+$/, '"').charAt(foo[x].length - 1) === '"') {
      if ((tl = foo[x].replace(/^\s+"/, '"')).length > 1 && tl.charAt(0) === '"') {
        foo[x] = foo[x].replace(/^\s*"|"\s*$/g, '').replace(/""/g, '"');
      } else if (x) {
        foo.splice(x - 1, 2, [foo[x - 1], foo[x]].join(sep));
      } else foo = foo.shift().split(sep).concat(foo);
    } else foo[x].replace(/""/g, '"');
  }
  return foo;
}

// Function to remove line breaks
function trimText(string) {
  if (string) {
    var trimString = string.toString();
    trimString = trimString.replace(/(\r\n|\n|\r)/gm, " ");
    return trimString;
  } else {
    return '';
  }
}

// Function to check if valid Row Type
function checkRowType(rowType, omsid, rowCount) {
  try{
    if (rowCount < 1 || rowCount !== 0 || rowCount !== '') {
      if (rowType !== '') {
        var myRowType = trimText(rowType);
        myRowType = myRowType.toString();
        if (myRowType === '6-12' || myRowType === '4-12' || myRowType === '3-12' || myRowType === '2-12') {
          return myRowType;
        } else {
          throw new TypeError('Your CSV file needs revision: You have specified row type: ' + rowType.toString() + '. \n\nRow Type needs to be one of the following: 6-12, 4-12, 3-12, or 2-12. Please check the row on your CSV for OMSID: ' + omsid + '.');
        }
      } else {
        throw new TypeError('Your CSV file needs revision: Row Type cannot be blank. Row Type needs to be one of the following: 6-12, 4-12, 3-12, or 2-12. Please check the row on your CSV for OMSID: ' + omsid + '.');
      }
    } else {
      var myRowType = trimText(rowType);
      myRowType = myRowType.toString();
      return myRowType;
    }
  }catch(e){
    alert("checkRowType: " + omsid + "\nError On Line: " + e.line + '\n' + e);
  }
}

// ================================================================= ^^^ FUNCTIONS ^^^ ============================================================================= //

// Error Array
var errArray = [];
var myArray = [];
var errObject = {
  errors: errArray
};

// prompt to open data file when script is first run: http://jongware.mit.edu/idcs6js/pc_File.html
var dataFile = File.openDialog("Please select your CSV File.", ".csv", false);
if (dataFile !== null) {
  var dataFileLocation = dataFile.parent.fsName;
  //dataFile.encoding = 'UTF8'; // set some encoding (this line did not allow special characters and screwed up the process)
  dataFile.open('r', undefined, undefined);
  var textLines = [];
  while (!dataFile.eof) {
    textLines[textLines.length] = dataFile.readln();
  }
  dataFile.close(); // close the file
} else {
  exit();
}
if (textLines.length < 1) {
  alert("ERROR Reading file");
  exit();
} else {
  var headers = parseCSV(",", textLines[0]);
  for (var i = 1; i < textLines.length; i++) {
    var obj = {};
    var currentline = parseCSV(",", textLines[i]);
    for (var j = 0; j < headers.length; j++) {
      obj[headers[j]] = currentline[j];
    }
    myArray.push(obj);
  }
}
// =================   Let's Make our Document with a Try/Catch   =================
try {
  // Check if any other documents are open, if so, close them or something
  if (app.documents.length > 0) {
    alert("You can't have any open documents in InDesign when using this script. Close all the open documents in InDesign and try again.");
    exit();
  }

  // Create the Document
  var myDocument = app.documents.add(false);

  // Set the document preferences
  var vp = myDocument.viewPreferences;

  // Set the page ruler origin
  vp.rulerOrigin = RulerOrigin.pageOrigin;
  vp.horizontalMeasurementUnits = MeasurementUnits.pixels;
  vp.verticalMeasurementUnits = MeasurementUnits.pixels;

  // Set Document Margin Presets
  var mp = myDocument.marginPreferences;
  mp.properties = {
    top: 0,
    left: 0,
    right: 0,
    bottom: 0
  };

  // Set Document Preferences
  var dp = myDocument.documentPreferences;

  // Intent: Web
  dp.intent = DocumentIntentOptions.WEB_INTENT;

  // Turn off Facing Pages
  dp.facingPages = false;

  // Set Document length; how many pages there are in the document
  dp.pagesPerDocument = myArray.length;

  // Set the Bleed
  dp.documentBleedBottomOffset = '0px';
  dp.documentBleedTopOffset = '0px';
  dp.documentBleedInsideOrLeftOffset = '0px';
  dp.documentBleedOutsideOrRightOffset = '0px';

  // Slug
  dp.slugBottomOffset = '400px';
  dp.slugTopOffset = '0px';
  dp.slugInsideOrLeftOffset = '0px';
  dp.slugRightOrOutsideOffset = '0px';

  // Set default page size then modify later
  dp.pageHeight = '1960px';
  dp.pageWidth = '1960px';

  // Set Metadata
  var copyrightDate = new Date();
  var copyrightYear = copyrightDate.getFullYear();
  var metaP = myDocument.metadataPreferences;
  metaP.author = "The Home Depot";
  metaP.copyrightInfoURL = "www.homedepot.com";
  metaP.copyrightNotice = copyrightYear + " Homer TLC, Inc.";
  metaP.copyrightStatus = CopyrightStatus.yes;
  metaP.description = "Document created for Rich Content. Created by a script written by Matthew Daniel.";
  metaP.documentTitle = "Rich Content Document";

  //<-------------------  CREATING THE DOCUMENT BELOW HERE ------------------------>

  // Set Document Swatches: createColor(colorValue, model, name, space)
  createColor([51, 51, 51], ColorModel.PROCESS, "#333333", ColorSpace.RGB);
  createColor([249, 99, 2], ColorModel.PROCESS, "#F96302", ColorSpace.RGB);
  createColor([238, 238, 238], ColorModel.PROCESS, "#EEEEEE", ColorSpace.RGB);
  createColor([119, 119, 119], ColorModel.PROCESS, "#777777", ColorSpace.RGB);
  createColor([255, 255, 255], ColorModel.PROCESS, "#FFFFFF", ColorSpace.RGB);
  createColor([255, 0, 255], ColorModel.PROCESS, "FPO", ColorSpace.RGB);
  createColor([228, 14, 0], ColorModel.PROCESS, "#E40E00", ColorSpace.RGB);
  createColor([245, 242, 234], ColorModel.PROCESS, "#F5F2EA", ColorSpace.RGB);

  // Set Document Text Defaults
  var td = myDocument.textDefaults;
  td.alignToBaseline = false;
  td.appliedFont = app.fonts.item("Helvetica Neue");
  td.fontStyle = "55 Roman";
  td.appliedLanguage = "English: USA";
  td.hyphenation = false;
  td.leading = Leading.AUTO;
  td.pointSize = 14;
  td.fillColor = "#333333";

  // Create Paragraph Styles
  // How to use: paragraphStyle(name, characterDirection, justification, hyphenation, pointSize, fontStyle, appliedFont, leading, fillColor, kerningMethod, tracking, capitalization, ligatures, rule)
  paragraphStyle("Caption Style", CharacterDirectionOptions.DEFAULT_DIRECTION, Justification.LEFT_ALIGN, false, 20, "55 Roman", "Helvetica Neue", 20, "#333333", "Optical", 0, Capitalization.NORMAL, false, false);

  paragraphStyle("Caption White Style", CharacterDirectionOptions.DEFAULT_DIRECTION, Justification.LEFT_ALIGN, false, 20, "55 Roman", "Helvetica Neue", 20, "#FFFFFF", "Optical", 0, Capitalization.NORMAL, false, false);

  paragraphStyle("Value 6-12 Style", CharacterDirectionOptions.DEFAULT_DIRECTION, Justification.LEFT_ALIGN, false, 80, "87 Heavy Condensed", "Helvetica Neue", 70, "#333333", "Optical", 0, Capitalization.ALL_CAPS, false, false);
  paragraphStyle("Value 4-12 Style", CharacterDirectionOptions.DEFAULT_DIRECTION, Justification.LEFT_ALIGN, false, 80, "87 Heavy Condensed", "Helvetica Neue", 70, "#333333", "Optical", 0, Capitalization.ALL_CAPS, false, false);
  paragraphStyle("Value 3-12 Style", CharacterDirectionOptions.DEFAULT_DIRECTION, Justification.LEFT_ALIGN, false, 60, "87 Heavy Condensed", "Helvetica Neue", 50, "#333333", "Optical", 0, Capitalization.ALL_CAPS, false, false);
  paragraphStyle("Value 2-12 Style", CharacterDirectionOptions.DEFAULT_DIRECTION, Justification.LEFT_ALIGN, false, 50, "87 Heavy Condensed", "Helvetica Neue", 50, "#333333", "Optical", 0, Capitalization.ALL_CAPS, false, false);

  paragraphStyle("Value 6-12 White Style", CharacterDirectionOptions.DEFAULT_DIRECTION, Justification.LEFT_ALIGN, false, 80, "87 Heavy Condensed", "Helvetica Neue", 70, "#FFFFFF", "Optical", 0, Capitalization.ALL_CAPS, false, false);
  paragraphStyle("Value 4-12 White Style", CharacterDirectionOptions.DEFAULT_DIRECTION, Justification.LEFT_ALIGN, false, 80, "87 Heavy Condensed", "Helvetica Neue", 70, "#FFFFFF", "Optical", 0, Capitalization.ALL_CAPS, false, false);
  paragraphStyle("Value 3-12 White Style", CharacterDirectionOptions.DEFAULT_DIRECTION, Justification.LEFT_ALIGN, false, 60, "87 Heavy Condensed", "Helvetica Neue", 50, "#FFFFFF", "Optical", 0, Capitalization.ALL_CAPS, false, false);
  paragraphStyle("Value 2-12 White Style", CharacterDirectionOptions.DEFAULT_DIRECTION, Justification.LEFT_ALIGN, false, 50, "87 Heavy Condensed", "Helvetica Neue", 50, "#FFFFFF", "Optical", 0, Capitalization.ALL_CAPS, false, false);

  paragraphStyle("Headline Style", CharacterDirectionOptions.DEFAULT_DIRECTION, Justification.LEFT_ALIGN, false, 50, "87 Heavy Condensed", "Helvetica Neue", 50, "#333333", "Optical", 0, Capitalization.ALL_CAPS, false, true);

  paragraphStyle("Subhead 6-12 Style", CharacterDirectionOptions.DEFAULT_DIRECTION, Justification.LEFT_ALIGN, false, 25, "67 Medium Condensed", "Helvetica Neue", 25, "#333333", "Optical", 0, Capitalization.ALL_CAPS, false, false);
  paragraphStyle("Subhead 4-12 Style", CharacterDirectionOptions.DEFAULT_DIRECTION, Justification.LEFT_ALIGN, false, 25, "67 Medium Condensed", "Helvetica Neue", 25, "#333333", "Optical", 0, Capitalization.ALL_CAPS, false, false);
  paragraphStyle("Subhead 3-12 Style", CharacterDirectionOptions.DEFAULT_DIRECTION, Justification.LEFT_ALIGN, false, 25, "67 Medium Condensed", "Helvetica Neue", 25, "#333333", "Optical", 0, Capitalization.ALL_CAPS, false, false);
  paragraphStyle("Subhead 2-12 Style", CharacterDirectionOptions.DEFAULT_DIRECTION, Justification.LEFT_ALIGN, false, 25, "67 Medium Condensed", "Helvetica Neue", 25, "#333333", "Optical", 0, Capitalization.ALL_CAPS, false, false);

  paragraphStyle("Subhead 6-12 White Style", CharacterDirectionOptions.DEFAULT_DIRECTION, Justification.LEFT_ALIGN, false, 25, "67 Medium Condensed", "Helvetica Neue", 25, "#FFFFFF", "Optical", 0, Capitalization.ALL_CAPS, false, false);
  paragraphStyle("Subhead 4-12 White Style", CharacterDirectionOptions.DEFAULT_DIRECTION, Justification.LEFT_ALIGN, false, 25, "67 Medium Condensed", "Helvetica Neue", 25, "#FFFFFF", "Optical", 0, Capitalization.ALL_CAPS, false, false);
  paragraphStyle("Subhead 3-12 White Style", CharacterDirectionOptions.DEFAULT_DIRECTION, Justification.LEFT_ALIGN, false, 25, "67 Medium Condensed", "Helvetica Neue", 25, "#FFFFFF", "Optical", 0, Capitalization.ALL_CAPS, false, false);
  paragraphStyle("Subhead 2-12 White Style", CharacterDirectionOptions.DEFAULT_DIRECTION, Justification.LEFT_ALIGN, false, 25, "67 Medium Condensed", "Helvetica Neue", 25, "#FFFFFF", "Optical", 0, Capitalization.ALL_CAPS, false, false);

  paragraphStyle("Headline 6-12 Style", CharacterDirectionOptions.DEFAULT_DIRECTION, Justification.LEFT_ALIGN, false, 50, "87 Heavy Condensed", "Helvetica Neue", 50, "#333333", "Optical", 0, Capitalization.ALL_CAPS, false, true);
  paragraphStyle("Headline 4-12 Style", CharacterDirectionOptions.DEFAULT_DIRECTION, Justification.LEFT_ALIGN, false, 50, "87 Heavy Condensed", "Helvetica Neue", 50, "#333333", "Optical", 0, Capitalization.ALL_CAPS, false, true);
  paragraphStyle("Headline 3-12 Style", CharacterDirectionOptions.DEFAULT_DIRECTION, Justification.LEFT_ALIGN, false, 40, "87 Heavy Condensed", "Helvetica Neue", 40, "#333333", "Optical", 0, Capitalization.ALL_CAPS, false, true);
  paragraphStyle("Headline 2-12 Style", CharacterDirectionOptions.DEFAULT_DIRECTION, Justification.LEFT_ALIGN, false, 40, "87 Heavy Condensed", "Helvetica Neue", 40, "#333333", "Optical", 0, Capitalization.ALL_CAPS, false, true);

  paragraphStyle("Headline 6-12 White Style", CharacterDirectionOptions.DEFAULT_DIRECTION, Justification.LEFT_ALIGN, false, 50, "87 Heavy Condensed", "Helvetica Neue", 50, "#FFFFFF", "Optical", 0, Capitalization.ALL_CAPS, false, true);
  paragraphStyle("Headline 4-12 White Style", CharacterDirectionOptions.DEFAULT_DIRECTION, Justification.LEFT_ALIGN, false, 50, "87 Heavy Condensed", "Helvetica Neue", 50, "#FFFFFF", "Optical", 0, Capitalization.ALL_CAPS, false, true);
  paragraphStyle("Headline 3-12 White Style", CharacterDirectionOptions.DEFAULT_DIRECTION, Justification.LEFT_ALIGN, false, 40, "87 Heavy Condensed", "Helvetica Neue", 40, "#FFFFFF", "Optical", 0, Capitalization.ALL_CAPS, false, true);
  paragraphStyle("Headline 2-12 White Style", CharacterDirectionOptions.DEFAULT_DIRECTION, Justification.LEFT_ALIGN, false, 40, "87 Heavy Condensed", "Helvetica Neue", 40, "#FFFFFF", "Optical", 0, Capitalization.ALL_CAPS, false, true);

  paragraphStyle("Headline 6-12 Error Style", CharacterDirectionOptions.DEFAULT_DIRECTION, Justification.LEFT_ALIGN, false, 50, "87 Heavy Condensed", "Helvetica Neue", 50, "FPO", "Optical", 0, Capitalization.ALL_CAPS, false, true);
  paragraphStyle("Headline 4-12 Error Style", CharacterDirectionOptions.DEFAULT_DIRECTION, Justification.LEFT_ALIGN, false, 50, "87 Heavy Condensed", "Helvetica Neue", 50, "FPO", "Optical", 0, Capitalization.ALL_CAPS, false, true);
  paragraphStyle("Headline 3-12 Error Style", CharacterDirectionOptions.DEFAULT_DIRECTION, Justification.LEFT_ALIGN, false, 40, "87 Heavy Condensed", "Helvetica Neue", 40, "FPO", "Optical", 0, Capitalization.ALL_CAPS, false, true);
  paragraphStyle("Headline 2-12 Error Style", CharacterDirectionOptions.DEFAULT_DIRECTION, Justification.LEFT_ALIGN, false, 40, "87 Heavy Condensed", "Helvetica Neue", 40, "FPO", "Optical", 0, Capitalization.ALL_CAPS, false, false);

  paragraphStyle("OMSID Style", CharacterDirectionOptions.DEFAULT_DIRECTION, Justification.LEFT_ALIGN, false, 60, "67 Medium Condensed", "Helvetica Neue", 60, "#F96302", "Optical", 0, Capitalization.ALL_CAPS, false, false);

  paragraphStyle("Slug Style", CharacterDirectionOptions.DEFAULT_DIRECTION, Justification.LEFT_ALIGN, false, 20, "67 Medium Condensed", "Helvetica Neue", 20, "#FFFFFF", "Optical", 0, Capitalization.NORMAL, false, false);

  paragraphStyle("Copy Headline Style", CharacterDirectionOptions.DEFAULT_DIRECTION, Justification.LEFT_ALIGN, false, 20, "67 Medium Condensed", "Helvetica Neue", 20, "#333333", "Optical", 0, Capitalization.NORMAL, false, false);

  paragraphStyle("Copy Style", CharacterDirectionOptions.DEFAULT_DIRECTION, Justification.LEFT_ALIGN, false, 14, "67 Medium Condensed", "Helvetica Neue", 16, "#333333", "Optical", 0, Capitalization.NORMAL, true, false);

  paragraphStyle("Error Style", CharacterDirectionOptions.DEFAULT_DIRECTION, Justification.LEFT_ALIGN, false, 20, "55 Roman", "Helvetica Neue", 20, "#333333", "Optical", 0, Capitalization.NORMAL, false, false);

  paragraphStyle("Error Headline Style", CharacterDirectionOptions.DEFAULT_DIRECTION, Justification.LEFT_ALIGN, false, 50, "87 Heavy Condensed", "Helvetica Neue", 50, "FPO", "Optical", 0, Capitalization.ALL_CAPS, false, false);

  // Add Artwork Layer: createLayer(name, layerColor, ignoreWrap, visible, showGuides, printable)
  var guidesLyr = createLayer("GUIDES", UIColors.LIGHT_BLUE, false, true, true, true);
  var artworkLyr = createLayer("ARTWORK", UIColors.BLUE, false, true, true, true);
  var omsidLyr = createLayer("OMSID", UIColors.ORANGE, false, true, true, true);
  var groupsLyr = createLayer("GROUPS", UIColors.RED, false, true, true, true);
  var headlinesLyr = createLayer("HEADLINES", UIColors.BLACK, false, true, true, true);
  var slugLyr = createLayer("SLUG", UIColors.BROWN, false, true, true, true);
  var titleLyr = createLayer("TITLE", UIColors.GREEN, false, true, true, true);
  var errorLyr = createLayer("ERRORS", UIColors.PINK, false, true, true, true);

  // Sort the Layers
  slugLyr.move(LocationOptions.AT_END);
  omsidLyr.move(LocationOptions.BEFORE, slugLyr);
  artworkLyr.move(LocationOptions.BEFORE, omsidLyr);
  headlinesLyr.move(LocationOptions.BEFORE, artworkLyr);
  guidesLyr.move(LocationOptions.AT_BEGINNING);
  groupsLyr.move(LocationOptions.BEFORE, guidesLyr);
  titleLyr.move(LocationOptions.BEFORE, slugLyr);
  errorLyr.move(LocationOptions.AT_BEGINNING);

  // Page constants
  var myTopMargin = 20;
  var myBottomMargin = 20;
  var myLeftMargin = 20;
  var myRightMargin = 20;
  var myRowMargin = 20;
  var pod12 = 1920;
  var pod6 = 950;
  var pod4 = 627;
  var pod3 = 465;
  var pod2 = 303;
  var brandBannerHeight = 126;
  var brandFooterHeight = 75;
  var banner1Height = 75;
  var banner2Height = 75;

  // Let's give the user an idea what's going on in the background
  var w = new Window("palette", "Creating " + myArray.length + " documents for Rich Content.");
  w.pbar = w.add('progressbar', undefined, 0, myArray.length);
  w.pbar.preferredSize.width = 600;
  w.show();

  // Create Master Pages with Document Pages based on looping through CSV file data
  var count = 0; // This helps provide a value for itemNum, counts through the rows on the CSV
  for (var i = 0; i < myArray.length; i++) {
    var omsid = myArray[i]["OMSID"];
    omsid = omsid.toString();
    var itemName = myArray[i]["OMSID"];
    var privateBrand = myArray[i]["Private Brand"];
    var row1Height = Number(myArray[i]["Row 1 Height"]);
    if (row1Height === '' || row1Height === undefined) {
      throw new TypeError("itemNum is undefined or zero for " + name);
    }
    var row1Height = Number(myArray[i]["Row 1 Height"]);
    var row2Height = Number(myArray[i]["Row 2 Height"]);
    var productName = trimText(myArray[i]["Product Name"]);
    var brandName = myArray[i]["Brand Name"];
    var productImage = myArray[i]["Product Image"];
    var brandBanner = myArray[i]["Brand Banner"];
    var brandBannerImage = myArray[i]["Brand Banner Image"];
    var brandFooterImage = myArray[i]["Brand Footer Image"];
    var banner1 = myArray[i]["Banner 1"];
    var banner1Image = myArray[i]["Banner 1 Image"];
    var banner2 = myArray[i]["Banner 2"];
    var banner2Image = myArray[i]["Banner 2 Image"];
    var brandFooter = myArray[i]["Brand Footer"];
    var row1Count = Number(myArray[i]["Row 1 Count"]);
    var row1Type = checkRowType(myArray[i]["Row 1 Type"], omsid, myArray[i]["Row 1 Count"]);
    var row2Count = Number(myArray[i]["Row 2 Count"]);
    var row2Type = checkRowType(myArray[i]["Row 2 Type"], omsid, myArray[i]["Row 2 Count"]);
    var pageNumber = count + 1;
    var pageCount = Number(myArray.length);
    var rowOrigin;

    // Locking in the width to 1960px wide
    var pageWidth = 1960;
    var pageHeight = calculatePageHeight(myTopMargin, myBottomMargin, myRowMargin, brandBannerHeight, brandFooterHeight, banner1Height, banner2Height, row1Height, row1Count, row1Type, row2Height, row2Count, brandBanner, banner1, banner2, brandFooter);

    // Resize the pages accordingly
    var myPage = activePage(count);
    myPage.label = omsid;
    myPage.appliedMaster = NothingEnum.NOTHING;
    myPage.marginPreferences.properties = {
      top: 0,
      left: 0,
      right: 0,
      bottom: 0
    };
    var curPageBounds = myPage.bounds;
    var curPageYmin = curPageBounds[0];
    var curPageXmin = curPageBounds[1];
    var curPageYmax = curPageYmin + Number(pageHeight);
    var curPageXmax = curPageXmin + Number(pageWidth);
    myPage.reframe(CoordinateSpaces.INNER_COORDINATES, [
      [curPageXmin, curPageYmin],
      [curPageXmax, curPageYmax]
    ]);
    var totalPodCount = 0;
    var totalPodCount1 = 0;
    var totalPodCount2 = 0;

    // Start Counting the pods
    if (row1Count >= 1) {
      if (row1Type === "6-12") {
        totalPodCount1 = (totalPodCount1 + 3);
      }
      if (row1Type === "4-12") {
        totalPodCount1 = (totalPodCount1 + 3) * row1Count;
      }
      if (row1Type === "3-12") {
        totalPodCount1 = (totalPodCount1 + 4) * row1Count;
      }
    } else {
      totalPodCount1 = 0;
    }
    if (row2Count >= 1) {
      if (row2Type === "4-12") {
        totalPodCount2 = (totalPodCount2 + 3) * row2Count;
      }
      if (row2Type === "3-12") {
        totalPodCount2 = (totalPodCount2 + 4) * row2Count;
      }
      if (row2Type === "2-12") {
        totalPodCount2 = (totalPodCount2 + 6) * row2Count;
      }
    } else {
      totalPodCount2 = 0;
    }

    totalPodCount = {
      "tp1": Number(totalPodCount1),
      "tp2": Number(totalPodCount2)
    };

    var myPodCount = 0;
    var myPodStart = 0;
    if (brandBanner === 'TRUE') {
      // createBanner(count, origin, bottomRight, myBottomMargin, myLeftMargin, myRightMargin, pageWidth, pageHeight, bannerHeight, bannerName)
      var myBrandBanner = createBanner(count, myTopMargin, myTopMargin + brandBannerHeight, myBottomMargin, myLeftMargin, myRightMargin, pageWidth, pageHeight, brandBannerHeight, "Brand Banner", brandBannerImage, omsid);
      rowOrigin = getTextFrmY2(myBrandBanner) + myRowMargin;
      createGuide(count, "GUIDES", false, HorizontalOrVertical.HORIZONTAL, GuideTypeOptions.RULER, true, rowOrigin);
      createGuide(count, "GUIDES", false, HorizontalOrVertical.HORIZONTAL, GuideTypeOptions.RULER, true, rowOrigin - myRowMargin);
    } else {
      rowOrigin = myTopMargin;
      createGuide(count, "GUIDES", false, HorizontalOrVertical.HORIZONTAL, GuideTypeOptions.RULER, true, rowOrigin);
      createGuide(count, "GUIDES", false, HorizontalOrVertical.HORIZONTAL, GuideTypeOptions.RULER, true, rowOrigin - myRowMargin);
    }
    if (row1Count >= 1) {
      myPodCount = totalPodCount1;
      var row1 = createRow(count, rowOrigin, row1Type, row1Count, row1Height, myRowMargin, myLeftMargin, myRightMargin, myTopMargin, myBottomMargin, omsid, myPodCount, myPodStart);
      rowOrigin = row1 + myRowMargin;
      createGuide(count, "GUIDES", false, HorizontalOrVertical.HORIZONTAL, GuideTypeOptions.RULER, true, rowOrigin);
      createGuide(count, "GUIDES", false, HorizontalOrVertical.HORIZONTAL, GuideTypeOptions.RULER, true, rowOrigin - myRowMargin);
    }
    if (row2Count >= 1) {
      myPodCount = totalPodCount1 + totalPodCount2;
      myPodStart = myPodCount - totalPodCount2;
      var row2 = createRow(count, rowOrigin, row2Type, row2Count, row2Height, myRowMargin, myLeftMargin, myRightMargin, myTopMargin, myBottomMargin, omsid, myPodCount, myPodStart);
      rowOrigin = row2 + myRowMargin;
      createGuide(count, "GUIDES", false, HorizontalOrVertical.HORIZONTAL, GuideTypeOptions.RULER, true, rowOrigin);
      createGuide(count, "GUIDES", false, HorizontalOrVertical.HORIZONTAL, GuideTypeOptions.RULER, true, rowOrigin - myRowMargin);
    }
    if (banner1 === 'TRUE') {
      // (count, origin, bottomRight, myBottomMargin, myLeftMargin, myRightMargin, pageWidth, pageHeight, bannerHeight, bannerName)
      var b1 = createBanner(count, rowOrigin, rowOrigin + banner1Height, myBottomMargin, myLeftMargin, myRightMargin, pageWidth, pageHeight, banner1Height, "Banner 1", banner1Image, omsid);
      rowOrigin = Number(getTextFrmY2(b1)) + myRowMargin;
      createGuide(count, "GUIDES", false, HorizontalOrVertical.HORIZONTAL, GuideTypeOptions.RULER, true, rowOrigin);
      createGuide(count, "GUIDES", false, HorizontalOrVertical.HORIZONTAL, GuideTypeOptions.RULER, true, rowOrigin - myRowMargin);
    }
    if (banner2 === 'TRUE') {
      var b2 = createBanner(count, rowOrigin, rowOrigin + banner2Height, myBottomMargin, myLeftMargin, myRightMargin, pageWidth, pageHeight, banner2Height, "Banner 2", banner2Image, omsid);
      rowOrigin = Number(getTextFrmY2(b2)) + myRowMargin;
      createGuide(count, "GUIDES", false, HorizontalOrVertical.HORIZONTAL, GuideTypeOptions.RULER, true, rowOrigin);
      createGuide(count, "GUIDES", false, HorizontalOrVertical.HORIZONTAL, GuideTypeOptions.RULER, true, rowOrigin - myRowMargin);
    }
    if (brandFooter === 'TRUE') {
      var bf = createBanner(count, rowOrigin, rowOrigin + brandFooterHeight, myBottomMargin, myLeftMargin, myRightMargin, pageWidth, pageHeight, brandFooterHeight, "Brand Footer", brandFooterImage, omsid);
      rowOrigin = Number(getTextFrmY2(bf)) + myRowMargin;
      createGuide(count, "GUIDES", false, HorizontalOrVertical.HORIZONTAL, GuideTypeOptions.RULER, true, rowOrigin);
      createGuide(count, "GUIDES", false, HorizontalOrVertical.HORIZONTAL, GuideTypeOptions.RULER, true, rowOrigin - myRowMargin);
    }
    createGuide(count, "GUIDES", false, HorizontalOrVertical.HORIZONTAL, GuideTypeOptions.RULER, true, myTopMargin);
    createGuide(count, "GUIDES", false, HorizontalOrVertical.VERTICAL, GuideTypeOptions.RULER, true, myLeftMargin);
    createGuide(count, "GUIDES", false, HorizontalOrVertical.VERTICAL, GuideTypeOptions.RULER, true, pageWidth - myRightMargin);
    // TODO: possibly reset the page size here on this line before creating the slug and after you place the Copy Headline and Copy to determine the actual page size
    myPage.resize(CoordinateSpaces.INNER_COORDINATES, AnchorPoint.TOP_LEFT_ANCHOR, ResizeMethods.REPLACING_CURRENT_DIMENSIONS_WITH, [1960, rowOrigin]);
    // createSlug(count, omsid, productName, brandName, productImage, pageNumber, pageCount, pageWidth, pageHeight, dataFileLocation)
    pageHeight = rowOrigin;
    createSlug(count, omsid, productName, brandName, productImage, pageNumber, pageCount, pageWidth, pageHeight, dataFileLocation);
    count++;
    w.pbar.value = count;
    $.sleep(20);
  } // End Loop

  // Run this when the loop is finished running
  if (count === myArray.length) {
    var objectCheck = isEmptyObject(errObject.errors);
    if (objectCheck === 'nothing') { // turning off printing errors for now to get a huge project completed, change "nothing" back to "false"
      var zCount = 0;
      var myErrArray = errObject.errors;
      var myErrorPage = createDocumentPage(count, LocationOptions.AT_END, "Error Report", pageWidth, pageHeight);
      createTextFrame(count, "ERRORS", "Error Headline", ContentType.TEXT_TYPE, [30, 30, 80, 360], "ERRORS", "Error Headline Style", AutoSizingReferenceEnum.TOP_LEFT_POINT, AutoSizingTypeEnum.OFF, VerticalJustification.TOP_ALIGN);
      var myErrorTxtFrm = createTextFrame(count, "ERRORS", "Error Table", ContentType.TEXT_TYPE, [100, 80, pageHeight - 80, pageWidth - 80], "", "Error Style", AutoSizingReferenceEnum.TOP_LEFT_POINT, AutoSizingTypeEnum.OFF, VerticalJustification.TOP_ALIGN);
      var myTable = myErrorTxtFrm.tables.add({
        alternatingFills: AlternatingFillsTypes.ALTERNATING_ROWS,
        bodyRowCount: myErrArray.length,
        columnSpan: 3,
        leftBorderStrokeColor: "None",
        rightBorderStrokeColor: "None",
        topBorderStrokeColor: "None",
        bottomBorderStrokeColor: "None",
        headerRowCount: 1,
        startRowFillColor: "#F96302",
        startColumnStrokeColor: "None",
        endColoumnStrokeColor: "None",
        startRowStrokeColor: "None",
        endRowStrokeColor: "None"
      });
      var myRows = myTable.rows.everyItem();
      myRows.bottomEdgeStrokeColor = "None";
      myRows.leftEdgeStrokeColor = "None";
      myRows.rightEdgeStrokeColor = "None";
      myRows.topEdgeStrokeColor = "None";
      myRows.innerColumnStrokeColor = "None";
      var myHeader = myTable.rows.item(0);
      myHeader.bottomEdgeStrokeColor = "#F96302";
      myHeader.cells.item(0).contents = "OMSID";
      myHeader.cells.item(1).contents = "Error Message";
      myHeader.cells.item(2).contents = "Error Description";
      for (var z = 0; z < myErrArray.length; z++) {
        // Loop through error array and creat table rows
        myTable.rows.item(z + 1).cells.item(0).contents = myErrArray[z]["OMSID"];
        myTable.rows.item(z + 1).cells.item(1).contents = myErrArray[z]["errMsg"];
        myTable.rows.item(z + 1).cells.item(2).contents = myErrArray[z]["errDesc"];
        zCount++;
      }
      if (myErrArray.length === zCount) {
        // Do something when the loop is complete
      }
    }
  }
  // Create the window and show the document
  myDocument.layers.item("Layer 1").remove(); //removes the default layer
  var myLayoutWindow = myDocument.windows.add();
  if (isEmptyObject(errObject.errors)) {
    app.select(app.documents.item(0).pages.firstItem());
  } else {
    app.select(app.documents.item(0).pages.lastItem());
    // alert("Oh snap! You have errors. See the last page of your document for an error report.");
  }
} catch (e) {
  // If there is an error, close the document created and don't save, otherwise it will be open in Indesign without a display window
  var myClose = myDocument.close(SaveOptions.NO);
  alert("Error On Line: " + e.line + '\n' + e); // show error on screen or do something with the error
}
Tags: