/*************************************************************************
*
* ADOBE CONFIDENTIAL
* ___________________
*
*  Copyright 2008 Adobe Systems Incorporated
*  All Rights Reserved.
*
* NOTICE:  All information contained herein is, and remains
* the property of Adobe Systems Incorporated and its suppliers,
* if any.  The intellectual and technical concepts contained
* herein are proprietary to Adobe Systems Incorporated and its
* suppliers and may be covered by U.S. and Foreign Patents,
* patents in process, and are protected by trade secret or copyright law.
* Dissemination of this information or reproduction of this material
* is strictly forbidden unless prior written permission is obtained
* from Adobe Systems Incorporated.
*
* $DateTime: 2008/04/10 13:35:00 $
*
* Adobe Output Module 2.0
*
* MediaGallery Originally Written by Quality Process Incorporated, Enhanced by
* Adobe System China. Contact Sheet written by Adobe System China.
* 
*
**************************************************************************/

AOM.CS.PDFMaker = function(document) {
	//this.controllerObj = controllerObj;
	
	this.errorMsg = undefined;
	this.errorNo = undefined;
	this.document = document;
	
	//init
}


AOM.CS.PDFMaker.prototype.destroy = function() {
	//this.controllerObj = undefined;
	this.errorMsg = undefined;
	this.errorNo = undefined;
}


AOM.CS.PDFMaker.prototype.alertMsg = function(msg) {
	AOM.alert(AOM.localize(msg));
}

AOM.CS.PDFMaker.prototype.confirmMsg = function(msg) {
	return AOM.confirm(AOM.localize(msg));
}

AOM.CS.PDFMaker.prototype.initWatermark = function() {
	this.watermark = new Object();
	var userInput = AOM.userInput(this.document);
	this.hasWatermark = userInput.getBoolean("hasWatermark");
	if (!this.hasWatermark) return;
	
	this.watermark.insertText = userInput.getBoolean("hasTextWatermark");
	this.watermark.insertImage = userInput.getBoolean("hasImageWatermark");
	
	if (this.watermark.insertText) {
		// Insert text as watermark.
		var watermarkText = userInput.get("watermarkText");
		this.watermark.text = AOM.CS.CString.trim(watermarkText);
		
		if (this.watermark.text == undefined || this.watermark.text.length == 0) {
			this.watermark.insertText= false;
			return;
		}
		
		this.watermark.fontFamily = userInput.get("watermarkFontFamily");
		this.watermark.fontFace = userInput.get("watermarkFontFace");
		this.watermark.fontSize = parseInt(userInput.get("watermarkFontSize"));
		this.watermark.fontColor = AOM.CS.CString.strToColor(userInput.get("watermarkFontColorPicker"));
	}
	else {
		// Insert image as watermark.
		this.watermark.imagePath = userInput.get("wmImagePath");

		if (!this.watermark.imagePath || this.watermark.imagePath.length == 0) {
			this.watermark.insertImage = false;
			return;
		}
		
		this.watermark.imageScale = parseInt(userInput.get("watermarkImageScale"));
	}
	
	this.watermark.placeOnEachImage = userInput.getBoolean("wmOnEachImage");
	
	this.watermark.offset = new Object();
	this.watermark.offset.x = parseInt(userInput.get("wmHOffset"));
	this.watermark.offset.y = parseInt(userInput.get("wmVOffset"));
	this.watermark.opacity = userInput.get("watermarkOpacity") / 100;
	this.watermark.isBackground = (userInput.get("wmLayer") == "Background");
	this.watermark.rotation = userInput.get("wmRotation") ? Number(userInput.get("wmRotation")) : 0;
}


AOM.CS.PDFMaker.prototype.initOtherValues = function() {
	var userInput = AOM.userInput(this.document);
		
	//set resolution
	this.resolution = Number(userInput.get("pdfPreset"));
	this.jpegQuality = Number(userInput.get("jpegQualitySlider"));
	
	//set backgroundColor
	var bgColor = eval(userInput.get("pageBackgroundFontColorPicker"));
	for (var i = 0; i < bgColor.length; i++) {
		bgColor[i] = Math.round(bgColor[i] * 255);
	}
	this.bgColor = bgColor;
	
	//set rotateTofit
	this.hasRotateToFit = userInput.getBoolean("hasRotate");
		
	//set filename and fileextension
	this.hasFileName = userInput.getBoolean("hasFileName");
	this.hasExtension = userInput.getBoolean("hasExtension");
	var imagePlacement = userInput.get("imagePlacement");
	if (imagePlacement != undefined && imagePlacement == "column") {
		this.imagePlacement = true;
	} else {
		this.imagePlacement = false;
	}

	//set userPassword and print permission
	this.hasDocPass = AOM.CS.CString.strToBoolean(userInput.get("hasDocPass"));
	this.docPass = userInput.get("docPass");
	this.hasDocOwnerPass = userInput.getBoolean("hasDocOwnerPass");
	this.docOwnerPass = userInput.get("docOwnerPass");
	
	var disablePrint = userInput.getBoolean("disablePrint");
	if (disablePrint == true && this.hasDocOwnerPass == true) {
		this.hasPrintPermission = false;
	} else {
		this.hasPrintPermission = true;
	}

	//set fullscreen and transition
	this.hasFullScreen = userInput.getBoolean("hasFullScreen");
	var transition = userInput.get("transition");
	if(transition=="None") {
		transition = undefined ; 
	} else {
		var direction = userInput.get("direction");
		if (direction != undefined && direction != "undefined") {
			transition += direction;
		}
	}
	this.transition = transition;
	var speed = userInput.get("speed");
	var speedValue;
	if (speed == AOM.CSConstant.SPEED_FAST) {
		speedValue = AOM.CSConstant.SPEED_FAST_VALUE; 
	} else if (speed == AOM.CSConstant.SPEED_MEDIUM) {
		speedValue = AOM.CSConstant.SPEED_MEDIUM_VALUE;
	} else if (speed == AOM.CSConstant.SPEED_SLOW) {
		speedValue = AOM.CSConstant.SPEED_SLOW_VALUE;
	} else {
		speedValue = AOM.CSConstant.SPEED_MEDIUM_VALUE;
	}
	this.speed = speedValue;
	
	this.hasDuration = userInput.getBoolean("hasAdvance");
	this.duration = AOM.CS.CString.strToNumber(userInput.get("advanceSeconds"));
	this.hasLoop = userInput.getBoolean("hasLoop");
	
	//set font
	this.fileNameFontFamily = userInput.get("fileNameFontFamily");
	this.fileNameFontFamilyDisplay = userInput.get("fileNameFontFamily_display");
	this.fileNameFontFace = userInput.get("fileNameFontFace");
	if (this.hasFileName) {
		this.fontSize = parseInt(userInput.get("fileNameFontSize"));
	} else {
		this.fontSize = 0;
	}
	var fontColor = eval(userInput.get("fileNameFontColorPicker"));
	for (var i = 0; i < fontColor.length; i++) {
		fontColor[i] = Math.round(fontColor[i] * 255);
	}
	this.fontColor = fontColor;
	
    this.hasRepeatPerPage = userInput.getBoolean("hasRepeatPerPage");
    
    this.headerOccupancy = this.footerOccupancy = 0;
	
	//add pageNumber
	var pageNumberLocation = userInput.get("pageNumberLocation");
	if (pageNumberLocation == AOM.CSConstant.PAGENUMBER_LOCATION_NONE) {
		this.hasPageNumber = false;
	} else {
		this.hasPageNumber = true;
		this.pageNumberLocation = pageNumberLocation;
		this.pageNumberAlignment = AOM.CS.CString.strToNumber(userInput.get("pageNumberAlignment"));
		this.pageNumberFontFamily = userInput.get("pageNumberFontFamily");
		this.pageNumberFontFamilyDisplay = userInput.get("pageNumberFontFamily_display");
		this.pageNumberFontFace = userInput.get("pageNumberFontFace");
		this.pageNumberFontSize = userInput.get("pageNumberFontSize");
		this.pageNumberFontColor = AOM.CS.CString.strToColor(userInput.get("pageNumberFontColorPicker"));
		
		if(this.pageNumberLocation == AOM.CSConstant.PAGENUMBER_LOCATION_HEADER) {
			this.headerOccupancy = Number(this.pageNumberFontSize);
		}
		else {
			this.footerOccupancy = Number(this.pageNumberFontSize);
		}
	}

	//add header
	this.hasHeader = userInput.getBoolean("hasHeader");
	if (this.hasHeader) {
		this.headerAlignment = AOM.CS.CString.strToNumber(userInput.get("headerAlignment"));
		this.headerText = userInput.get("headerText");
		if (AOM.CS.CString.trim(this.headerText).length == 0) {
			this.headerText = "";
		}
		this.headerFontFamily = userInput.get("headerFontFamily");
		this.headerFontFamilyDisplay = userInput.get("headerFontFamily_display");
		this.headerFontFace = userInput.get("headerFontFace");
		this.headerFontSize = userInput.get("headerFontSize");
		this.headerFontColor = AOM.CS.CString.strToColor(userInput.get("headerFontColorPicker"));
		if(this.headerText != undefined && this.headerText.length)
			this.headerOccupancy = Math.max(this.headerOccupancy, this.headerFontSize);
		
		var headerDLWidth = userInput.get("headerDLWidth");
		if (headerDLWidth == "None") {
			this.hasHeaderDL = false;
		} else {
			this.hasHeaderDL = true;
			this.headerDLWidth = AOM.CS.CString.strToNumber(headerDLWidth);
			this.headerDLColor = AOM.CS.CString.strToColor(userInput.get("headerDLFontColorPicker"));
			this.headerOccupancy += Number(this.headerDLWidth);
		}
	}
	//add footer
	this.hasFooter = userInput.getBoolean("hasFooter");
	if (this.hasFooter) {
		this.footerAlignment = AOM.CS.CString.strToNumber(userInput.get("footerAlignment"));
		this.footerText = userInput.get("footerText");
		if (AOM.CS.CString.trim(this.footerText).length == 0) {
			this.footerText = "";
		}
		this.footerFontFamily = userInput.get("footerFontFamily");
		this.footerFontFamilyDisplay = userInput.get("footerFontFamily_display");
		this.footerFontFace = userInput.get("footerFontFace");
		this.footerFontSize = userInput.get("footerFontSize");
		this.footerFontColor = AOM.CS.CString.strToColor(userInput.get("footerFontColorPicker"));
		if(this.footerText != undefined && this.footerText.length)
			this.footerOccupancy = Math.max(this.footerOccupancy, this.footerFontSize);
		
		var footerDLWidth = userInput.get("footerDLWidth");
		if (footerDLWidth == "None") {
			this.hasFooterDL = false;
		} else {
			this.hasFooterDL = true;
			this.footerDLWidth = AOM.CS.CString.strToNumber(footerDLWidth);
			this.footerDLColor = AOM.CS.CString.strToColor(userInput.get("footerDLFontColorPicker"));
			this.footerOccupancy += Number(this.footerDLWidth);
		}
	}
}


AOM.CS.PDFMaker.prototype.createPDFGenerator = function(preview) {
	var imageCache = AOM.ImageCache.getInstance();	
	var g = new AOM.PDFGenerator(this.document, true, imageCache);
	g.setPageLayout(this.dimension, this.arrange, this.margins, this.spacings, this.headerHeight, this.footerHeight);
	g.setFontSize(this.fontSize);
	g.setFontStyle(this.fileNameFontFamily, this.fileNameFontFace);
	g.setFontColor(this.fontColor[0], this.fontColor[1], this.fontColor[2]);
	
	g.setBackgroundColor(this.bgColor[0], this.bgColor[1], this.bgColor[2]);
	g.setResolution(this.resolution);
	g.setJpegQuality(this.jpegQuality);
	g.setRotateToFit(this.hasRotateToFit);
	
	if(AOM.DebugInterface != undefined && AOM.DebugInterface.testGenerator != undefined) {
		AOM.DebugInterface.testGenerator(g);
	}
	
	if (this.hasFileName) {
		g.setFilename(true);
		g.setFileExtension(this.hasExtension);
	} else {
		g.setFilename(false);
		g.setFileExtension(false);
	}
	
	//TODO 
	if (this.imagePlacement) {
		g.setPlaceByColumn(true);
	}

    if (!preview) {
		if (this.hasDocPass) {
			g.setUserPassword(this.docPass);
		}
		if (this.hasDocOwnerPass) {
			g.setOwnerPassword(this.docOwnerPass);
		}
	
		if (this.hasPrintPermission == false) {
			g.setPrintPermission(this.hasPrintPermission);
		}
	}
    
    g.setFullScreenMode(this.hasFullScreen);
    
	if (this.transition!= undefined) {
		g.setTransitionMode(this.transition, this.speed);
	}

	if (this.hasDuration) {
		g.setPageDuration(this.duration);
	}
	g.setLoop(this.hasLoop);
	g.setRepeatOnPage(this.hasRepeatPerPage);
	
	if (this.hasWatermark) {
		g.watermarkStatus = g.setWatermark(this.watermark);
		if(g.watermarkStatus != AOM.PDFGenerator.WATERMARK_SUCCESS)
			return g;
	} 
	
	//add pageNumber
	if (this.hasPageNumber) {
		var pageNumberAsFooter = (this.pageNumberLocation == AOM.CSConstant.PAGENUMBER_LOCATION_FOOTER);
		g.setPageNumber(
			this.pageNumberFontFamily, this.pageNumberFontFace, 
			this.pageNumberFontSize, this.pageNumberFontColor, 
			this.pageNumberAlignment, pageNumberAsFooter);
	}
	
	//add header
	if (this.hasHeader) {
		if(this.headerText && this.headerText.length) {		
			g.setHeaderText(
				this.headerText, this.headerFontFamily, 
				this.headerFontFace, this.headerFontSize, 
				this.headerFontColor, this.headerAlignment);				
		}
		if (this.hasHeaderDL) {
			g.setDivideLine(false, this.headerDLWidth, this.headerDLColor);
		}	
	}
	//add footer
	if (this.hasFooter) {
		if(this.footerText && this.footerText.length) {		
			g.setFooterText(
				this.footerText, this.footerFontFamily, 
				this.footerFontFace, this.footerFontSize, 
				this.footerFontColor, this.footerAlignment);			
		}
		if (this.hasFooterDL) {
			g.setDivideLine(true, this.footerDLWidth, this.footerDLColor);
		}	
	}
	
	return g;
}

AOM.CS.PDFMaker.prototype.hasAutoLayout = function() {
	var isAutoLayout = AOM.userInput(this.document).getBoolean("hasUseAutoSpacing");
	
	return isAutoLayout;
}

AOM.CS.PDFMaker.prototype.validateHeaderFooter = function() {
	var userInput = AOM.userInput(this.document);
	var neatHeight = this.dimension[1] - this.margins[0] - this.margins[1];
	var pageUnit = AOM.userInput(this.document).get("pageUnit");

	// do validate
	var doValidate = function(distance, min, max, isHeader) {
		var headerOrFooter;
		if(isHeader) {
			headerOrFooter = "$$$/ContactSheet/javascript/validation/headerValidation=header";
		}
		else {
			headerOrFooter = "$$$/ContactSheet/javascript/validation/footerValidation=footer";
		}
		if(min > max) {
			userInput.alertMsg(
				"$$$/ContactSheet/javascript/validation/distanceNoRange=Cannot find a proper value for (1) distance. Please change page height, or change (1) font size, divider size or page number font size.",
				[headerOrFooter]);
			return false;
		}
		if(min == max && min != distance) {	
			userInput.alertMsg(
				"$$$/ContactSheet/javascript/validation/distanceSettingNotEqual=According to current settings, the only allowed value of (1) distance is (2) (3).", 
				[
					headerOrFooter, 
					AOM.CS.Locale.toLocaleString(minHeight), 
					AOM.CS.UIUtils.getUnitZString(pageUnit),
				]
			);
			return false;
		}
		if(distance > max || distance < min) {
			userInput.alertMsg(
				"$$$/ContactSheet/javascript/validation/distanceSettingOutOfRange=According to current settings, (1) distance should range from (2) to (3) (4).",
				[
					headerOrFooter, 
					AOM.CS.Locale.toLocaleString(minHeight), 
					AOM.CS.Locale.toLocaleString(maxHeight), 
					AOM.CS.UIUtils.getUnitZString(pageUnit),
				]
			);
			return false;
		}
		return true;
	}
	
	// the maximum of H/F distance is 10% of the neat height.
	var maxHeight = AOM.CS.UIUtils.getUnitDisplayValue(0.1*neatHeight, pageUnit);
	
	// check header distance
	if(this.headerHeight != undefined) {
		var minHeight = AOM.CS.UIUtils.getUnitDisplayValue(this.headerOccupancy, pageUnit);
		var headerHeight = AOM.CS.UIUtils.getUnitDisplayValue(this.headerHeight, pageUnit);
		if(!doValidate(headerHeight, minHeight, maxHeight, true))
			return false;
	}
	
	// check footer distance
	if(this.footerHeight != undefined) {
		var minHeight = AOM.CS.UIUtils.getUnitDisplayValue(this.footerOccupancy, pageUnit);
		var footerHeight = AOM.CS.UIUtils.getUnitDisplayValue(this.footerHeight, pageUnit);
		if(!doValidate(footerHeight, minHeight, maxHeight, false))
			return false;
	}
	return true;
}

//main function
AOM.CS.PDFMaker.prototype.generatePDF = function(preview) {

	var taskManager = AOM.TaskManager.find("GeneratePDF" + this.document.id);
	if(taskManager != undefined &&
	   (taskManager.state == "running" || taskManager.state == "paused"))
		return AOM.CSConstant.LAYOUT_DO_NOTHING;

	//check if select file
	var selLength = this.document.selectionLength;
	if (selLength == 0) {
		return AOM.CSConstant.SELECT_NONE;
	}
	// check password editbox
	if(!preview) {
		var currentUserInput = AOM.userInput(this.document);
		var hasDocPass = currentUserInput.getBoolean("hasDocPass");
		var docPass = currentUserInput.get("docPass");
		var hasDocOwnerPass = currentUserInput.getBoolean("hasDocOwnerPass");
		var docOwnerPass = currentUserInput.get("docOwnerPass");
		
		if(hasDocPass && (docPass == undefined || docPass.length == 0)) {
			return AOM.CSConstant.NEED_DOCPASS;
		}
		if(hasDocOwnerPass && (docOwnerPass == undefined || docOwnerPass.length == 0)) {
			return AOM.CSConstant.NEED_OWNERPASS;
		}
		if (hasDocPass && hasDocOwnerPass && (docPass == docOwnerPass)) {
			return AOM.CSConstant.PASSWD_IDENTICAL;
		}
	} 
	//init other values
	this.initOtherValues();
	
	//init pagelayout
	this.initPageLayout();	
	
	// init watermark
	this.initWatermark();
	
	//create pdfgenerator
	var g = this.createPDFGenerator(preview);
	if(g.watermarkStatus != AOM.PDFGenerator.WATERMARK_SUCCESS) {
		switch(g.watermarkStatus) {
			case AOM.PDFGenerator.WATERMARK_IMAGE_NOT_EXIST:
				return AOM.CSConstant.WATERMARK_IMAGE_NOT_EXIST;
			case AOM.PDFGenerator.WATERMARK_IMAGE_UNSUPPORT:
				return AOM.CSConstant.WATERMARK_IMAGE_UNSUPPORT;
			default:
		}
	}

	//validate page layout
	var layoutError = AOM.CSConstant.LAYOUT_OK;
	if (AOM.CSConstant.LAYOUT_OK != (layoutError = g.validatePageLayout())) 
		return layoutError;
	
	// validate header/footer
	if(!this.validateHeaderFooter()) {
		return AOM.CSConstant.HEADERFOOTER_ERROR;
	}

	// get path of the file to save
	var saveFile = File(AOM.CS.Paths.userData + "preview.pdf");
	if (preview == undefined || !preview) {
    	//call save dialog
		saveFile = File.saveDialog(AOM.localize("$$$/ContactSheet/javascript/pdfGenerator/savebutton=Save..."), "*.pdf");
		
		if (saveFile == null)  return ;
		
		if (File.fs == "Macintosh") {
			var saveFileFullPath = AOM.CS.CString.trim(saveFile.fsName);
			if(saveFileFullPath.search(/\.pdf$/i) < 0) {
				function xtractFile_sans(data){
					var m = data.match(/(.*)[\/\\]([^\/\\]+)$/);
					return {path: m[1], file: m[2]};
				}
				var mypaths = xtractFile_sans(saveFileFullPath);
				var newSaveFileName = mypaths.path + "/" +  AOM.CS.CString.trim(mypaths.file) + ".pdf";
				
				saveFile = new File(newSaveFileName);
			}
		}
	
		if (saveFile.exists == true) {
			var hasConfirm = this.confirmMsg("$$$/ContactSheet/javascript/pdfGenerator/overwriteExistFile=File already exists. Do you want to overwrite it?");
			if (hasConfirm == false) {
				return AOM.CSConstant.LAYOUT_DO_NOTHING;
			}
		}
	}
	
	this.dumpAll();
	
	//var controller = this.controllerObj;
	var pdfMaker = this;
	
	g.viewPDF = AOM.userInput(this.document).getBoolean("hasViewPdf");
	g.onStopDetail = function() {
	    return pdfMaker.processStatus(g, g.viewPDF, preview);
    }
	g.onStop = function() { 
		pdfMaker.processAction(g, g.viewPDF, preview);
	}
	
    var count = preview ? Math.min((AOM.userInput(this.document).get("pageRows")*AOM.userInput(this.document).get("pageColumns")), selLength) : selLength;
    g.exportPDF(AOM.CS.CString.trim(saveFile.fsName), 1, 6, count, preview);

	return AOM.CSConstant.LAYOUT_OK;
}

AOM.CS.PDFMaker.prototype.processStatus = function(g, viewPDF, previewPDF) {
    var hasError =((g.errorList != undefined) && (g.errorList.length > 0));

	if (g.onStopCode > 0) {
		if(hasError) {
			return AOM.localize("$$$/ContactSheet/javascript/pdfGenerator/selectSomeNoneImageFile=Some of the selected files are not supported image files.");
		}
		return AOM.localize("$$$/ContactSheet/javascript/pdfGenerator/pdfGenerated=PDF generated successfully.")
	} else if (g.onStopCode == 0) {
		if (hasError) {
			return AOM.localize("$$$/ContactSheet/javascript/pdfGenerator/selectAllNoneImageFile=None of the selected files are supported image files.");
		} else {
			return AOM.localize("$$$/ContactSheet/javascript/pdfGenerator/noSelectThumbnail=No item is selected. Please select at least one item and try again.");
		}
	} else if (g.onStopCode == -1) {
		return AOM.localize("$$$/ContactSheet/javascript/pdfGenerator/specFileCannotOverwrite=Specified file cannot be overwritten.");
	} else if (g.onStopCode == -2) {
		return AOM.localize("$$$/ContactSheet/javascript/pdfGenerator/specDirectoryNotExist=Specified directory does not exist.");
	} else if (g.onStopCode == -3) {
		return AOM.localize("$$$/ContactSheet/javascript/pdfGenerator/notInvokeSetPageLayoutInAdvance=The function setPageLayout is not invoked in advance.");
	} else if (g.onStopCode == -4) {
		return AOM.localize("$$$/ContactSheet/javascript/pdfGenerator/unknownReason=Generate PDF failed due to unknown reason.");
	} else if (g.onStopCode == -5) {
		// A font is not found in system.
		return g.onStopErr;
	} else {
		return AOM.localize("$$$/ContactSheet/javascript/pdfGenerator/unknownReason=Generate PDF failed due to unknown reason.");
	}
}

AOM.CS.PDFMaker.prototype.processAction = function(g, viewPDF, previewPDF) {
	if (g.onStopCode > 0) {
		if (viewPDF && !previewPDF) {
			try {
				var t = new Thumbnail(File(g.filename));
				t.open();
			} catch(e) {
				AOM.alert(AOM.localize("$$$/ContactSheet/javascript/pdfGenerator/launchPDFViewerFailed=The PDF file has been generated successfully, but Bridge can not open the file through the configured PDF viewer. Please open the file manually."));
            }
		}
	}
}


AOM.CS.PDFMaker.prototype.dumpPageLayout = function() {
	AOM.CS.Log.writeError("dimension:" + this.dimension + ",arrange:" + this.arrange + ",margins:" + this.margins + ",spacing:" + this.spacings);
	AOM.CS.Log.writeError("headerDistance:" + this.headerHeight + ", footerDistance:" + this.footerHeight);
	AOM.CS.Log.writeError("fontSize:" + this.fontSize + ",fontStyle:" + this.fileNameFontFamily + "," + this.fileNameFontFace + ",fontColor:" + this.fontColor);
}


AOM.CS.PDFMaker.prototype.dumpAll = function() {
	if (AOM.CS.Log.debugVerbose == false) {
		return;
	}

	this.dumpPageLayout();
	
	AOM.CS.Log.writeError("backgroundColor" + this.bgColor);
	AOM.CS.Log.writeError("resolutionValue = " + this.resolution);
	AOM.CS.Log.writeError("hasRotate:" + (this.hasRotateToFit == true) + ", hasRepeatPerPage=" + this.hasRepeatPerPage);
	AOM.CS.Log.writeError("hasFileName:" + (this.hasFileName == true) + ",	hasExtension:" + (this.hasExtension == true) + ", imagePlacement:" +this.imagePlacement);
	AOM.CS.Log.writeError("hasDocPass:" + this.hasDocPass + ",docpass=" + this.docPass + ",printpermission:" + this.hasPrintPermission);
	AOM.CS.Log.writeError("hasFullScreen:" + this.hasFullScreen + ",transiton:" + this.transition + ",speed=" + this.speed );
	AOM.CS.Log.writeError(",hasAdvance=" + this.hasDuration + ",duration=" + this.duration + ", hasLoop=" +this.hasLoop);
	
	AOM.CS.Log.writeError("hasWatermark?" + this.hasWatermark);
	if (this.hasWatermark) {
		if (this.watermark.insertText) {
			AOM.CS.Log.writeError("	watermarkText=" + this.watermark.text);
			AOM.CS.Log.writeError("	font_family=" + this.watermark.fontFamily);
			AOM.CS.Log.writeError("	font_face=" + this.watermark.fontFace);
			AOM.CS.Log.writeError("	font_size=" + this.watermark.fontSize);
			AOM.CS.Log.writeError("	font_color=" + this.watermark.fontColor);
			
		} else {
			AOM.CS.Log.writeError("	watermarkImage=" + this.watermark.imagePath);
			AOM.CS.Log.writeError("	imagescale=" + this.watermark.imageScale);
		}
		AOM.CS.Log.writeError("	offset_x=" + this.watermark.offset.x);
		AOM.CS.Log.writeError("	offset_y=" + this.watermark.offset.y);
		AOM.CS.Log.writeError("	opacity=" + this.watermark.opacity);
		AOM.CS.Log.writeError("	isBackground=" + this.watermark.isBackground);
		AOM.CS.Log.writeError("	rotation=" + this.watermark.rotation);
	} 

	//output header info.
	AOM.CS.Log.writeError("hasHeader?" + this.hasHeader);
	if (this.hasHeader) {
		AOM.CS.Log.writeError("	headerAlignment:" + this.headerAlignment);
		AOM.CS.Log.writeError("	headerText:" + this.headerText);
		AOM.CS.Log.writeError("	family:" + this.headerFontFamily + ",face:" + this.headerFontFace);
		AOM.CS.Log.writeError("	size:" + this.headerFontSize + ",color:" + this.headerFontColor);
		AOM.CS.Log.writeError("	has divider line?" + this.hasHeaderDL);
		if (this.hasHeaderDL) {
			AOM.CS.Log.writeError("		width:" + this.headerDLWidth + ",color:" + this.headerDLColor);
		}
	}
	//output footer info.
	AOM.CS.Log.writeError("hasFooter?" + this.hasFooter);
	if (this.hasFooter) {
		AOM.CS.Log.writeError("	footerAlignment:" + this.footerAlignment);
		AOM.CS.Log.writeError("	footerText:" + this.footerText);
		AOM.CS.Log.writeError("	family:" + this.footerFontFamily + ",face:" + this.footerFontFace);
		AOM.CS.Log.writeError("	size:" + this.footerFontSize + ",color:" + this.footerFontColor);
		AOM.CS.Log.writeError("	has divider line?" + this.hasFooterDL);
		if (this.hasFooterDL) {
			AOM.CS.Log.writeError("		width:" + this.footerDLWidth + ",color:" + this.footerDLColor);
		}
	}
	//ouput page number info
	AOM.CS.Log.writeError("hasPageNumber?" + this.hasPageNumber);
	if (this.hasPageNumber) {
		AOM.CS.Log.writeError("	pageNumberAlignment:" + this.pageNumberAlignment);
		AOM.CS.Log.writeError("	pageNumberLocation:" + this.pageNumberLocation);
		AOM.CS.Log.writeError("	family:" + this.pageNumberFontFamily + ",face:" + this.pageNumberFontFace);
		AOM.CS.Log.writeError("	size:" + this.pageNumberFontSize + ",color:" + this.pageNumberFontColor);
	}
}


AOM.CS.PDFMaker.prototype.computeFontMinimizeSize = function(gfx, fontName, fontSize) {
	var currentFont = ScriptUI.newFont (fontName,ScriptUI.FontStyle.REGULAR, fontSize);
	var minFontSize = gfx.measureString("aaaaa", currentFont);
	
	return minFontSize;
}


AOM.CS.PDFMaker.prototype.initPageLayout = function() {
	var userInput = AOM.userInput(this.document);
	var toUnit = AOM.CSConstant.UNIT_PIXELS;
	var fromUnit = userInput.get("pageUnit");
	
	// get params from userinput
	var width = userInput.getFloat("pageWidth");
	var height = userInput.getFloat("pageHeight");
	var headerDistance = this.hasHeader? userInput.getFloat("headerDistance") : 0;
	var footerDistance = this.hasFooter? userInput.getFloat("footerDistance") : 0;
	var rows = Number(userInput.get("pageRows"));
	var cols = Number(userInput.get("pageColumns"));
	var top = userInput.getFloat("topMargin");
	var bottom = userInput.getFloat("bottomMargin"); 
	var left = userInput.getFloat("leftMargin");
	var right = userInput.getFloat("rightMargin");
	var vspace = userInput.getFloat("verticalSpacing");
	var hspace = userInput.getFloat("horizontalSpacing"); 
	
	// auto layout
	if (this.hasAutoLayout()) {
		var vBaseMarginRatio = 0.06 * (height / width);
		var hBaseMarginRatio = 0.06 * (width / height);
		var vBaseSpacingRatio = 0.04 * (height / width);
		var hBaseSpacingRatio = 0.04 * (width / height);
		
		var topRatio = (vBaseMarginRatio - (this.hasHeader ? vBaseMarginRatio * 0.5 : 0)) / (0.4 + 0.3 * rows);
		var bottomRatio = (vBaseMarginRatio - (this.hasFooter ? vBaseMarginRatio * 0.5 : 0)) / (0.4 + 0.3 * rows);
		var hMarginRatio = hBaseMarginRatio / (0.4 + 0.3 * cols);
		var hSpacingRatio = hBaseSpacingRatio / (0.3 + 0.35 * cols);
		var vSpacingRatio = vBaseSpacingRatio / (0.3 + 0.35 * rows);
		
		left = right = Math.round(hMarginRatio * width);
		top = Math.round(topRatio * height);
		bottom = Math.round(bottomRatio * height);
		hspace = Math.round(hSpacingRatio * width);
		vspace = Math.round(vSpacingRatio * height);
	}

	// save page layout values
	this.dimension = [width, height];
	this.arrange = [cols, rows];
	this.margins = [top, bottom, left, right];
	this.spacings = [vspace, hspace];
	this.headerHeight = this.hasHeader? headerDistance : undefined;
	this.footerHeight = this.hasFooter? footerDistance : undefined;
	
	this.outputLayout();
	return true;
}

AOM.CS.PDFMaker.prototype.outputLayout = function() {
	if (AOM.CS.Log.debugVerbose) {
		AOM.CS.Log.writeLine("Margins(top, bottom, left, right): " + this.margins.toString());
		AOM.CS.Log.writeLine("Spacings(vertical, horizontal): " + this.spacings.toString());
		AOM.CS.Log.writeLine("Arrange(cols, rows): " + this.arrange.toString());
		AOM.CS.Log.writeLine("Dimension(width, height): " + this.dimension.toString());
	}
}
