//airtight gallery creator

AOM.AmgAirtightGalleryCreator = function (images, destinationFolder, taskManager, document, createMode, viewerMode, jpegQuality)
{
	try
	{
	    AOM.AmgAirtightGalleryCreator.currentDocument = document;

		var imageMaximumDimension = AOM.AmgAirtightGalleryCreator.initializeSizesList(viewerMode);
		var galleryFolder = AOM.AmgAirtightGalleryCreator.initializeAirtightGalleryFolder(destinationFolder, viewerMode);
		var copyright = AOM.AmgAirtightGalleryCreator.get("copyrightView");
		AOM.AmgAirtightGalleryCreator.transformFiles(galleryFolder);
        AOM.AmgAirtightGalleryCreator.currentDocument = undefined;
	    
	    var callback = function ()
		{
			AOM.AmgAirtightGalleryCreator.currentDocument = document;
            var xmlFile = new File(galleryFolder + "gallery.xml");
            if (viewerMode == "simple") {
				AOM.AmgAirtightGalleryCreator.simpleViewerMakeXml(images, xmlFile, galleryFolder);
			}
			if (viewerMode == "postcard") {
				AOM.AmgAirtightGalleryCreator.postcardViewerMakeXml(images, xmlFile, galleryFolder);
			}
			if (viewerMode == "auto") {
				AOM.AmgAirtightGalleryCreator.autoViewerMakeXml(images, xmlFile, galleryFolder);
			}
			AOM.AmgAirtightGalleryCreator.currentDocument = undefined;
		};
		AOM.AmgGalleryCreator.processImages(images, AOM.AmgAirtightGalleryCreator.sizesList,
            imageMaximumDimension, galleryFolder, copyright, taskManager, createMode,
            {action:callback, title: AOM.ZStringDialogTitle, description: AOM.ZStringGroupFile}, jpegQuality);
	}
	catch(e)
	{
	    taskManager.showProgressOnStop = false;
	    taskManager.stop({title: AOM.ZStringGroupFile,
                          description: AOM.AMG.localize("$$$/MediaGallery/JavaScript/FlashGallery/AccessDenied=Error creating gallery. Access denied."),
                          button: AOM.AMG.localize("$$$/MediaGallery/JavaScript/FlashGallery/OK=OK")});
	    AOM.AMG.Log.writeError("AOM.AmgFlashGalleryCreator caught - " + e);
	}
}

AOM.AmgAirtightGalleryCreator.initializeSizesList = function (viewerMode)
{
	var preview = AOM.AmgAirtightGalleryCreator.get("largeSizeSlider");
	if (preview == undefined)
		AOM.AMG.Log.writeError("AOM.AmgHtmlGalleryCreator.sizesList - missing previewSize");
	
	AOM.AmgAirtightGalleryCreator.sizesList = {};	
	var sizesList = AOM.AmgAirtightGalleryCreator.sizesList;		
	sizesList.large = {}
	sizesList.large.width = preview;
	sizesList.large.height = preview;
	sizesList.large.size = "large";
	
	if (viewerMode == "simple") {
		sizesList.thumb = {}
	    sizesList.thumb.width = 100;
		sizesList.thumb.height = 100;
		sizesList.thumb.size = "thumb";
	}
	return preview;
}

AOM.AmgAirtightGalleryCreator.initializeAirtightGalleryFolder = function (destinationFolder, viewerMode)
{
	var subFolders = new Array();
	subFolders.push("/images");
	subFolders.push("/images/large");
	
	if (viewerMode == "simple") {
		subFolders.push("/images/thumb");
	}
	
	var source;
	var sourcePath;
	if (viewerMode == "simple") {
		sourcePath = AOM.AMG.Paths.app + "/resources/airtightgallery/simpleviewer/";
	}
	if (viewerMode == "postcard") {
		sourcePath = AOM.AMG.Paths.app + "/resources/airtightgallery/postcardviewer/";
	}
	if (viewerMode == "auto") {
		sourcePath = AOM.AMG.Paths.app + "/resources/airtightgallery/autoviewer/";
	}
	
	var filePath;
	var file;
	var sourceDestinationList = new Array();
	
	file = "viewer.swf";
	filePath = destinationFolder + "/" + file;
	sourceDestinationList.push({'source' : sourcePath + file, 'destination' : filePath});
	
	file = "swfobject.js";
	filePath = destinationFolder + "/" + file;
	sourceDestinationList.push({'source' : sourcePath + file, 'destination' : filePath});
	
	file = "index.html";
	filePath = destinationFolder + "/" + file;
	sourceDestinationList.push({'source' : sourcePath + file, 'destination' : filePath});
	
	file = "readme.html";
	filePath = destinationFolder + "/" + file;
	sourceDestinationList.push({'source' : sourcePath + file, 'destination' : filePath});
	
	AOM.AMG.createFolderContents(destinationFolder, subFolders, sourceDestinationList);
	
	return destinationFolder + "/";
}


AOM.AmgAirtightGalleryCreator.get = function(id)
{
	if (id == undefined)
	{
		AOM.AMG.Log.writeError("HtmlGalleryCreator.get - unknown field (" + id + ")");
		return "field_" + id;
	}
	var value = AOM.AMG.userInput(AOM.AmgAirtightGalleryCreator.currentDocument).get(id);
	if (value == undefined)
	{
		return "";
	}

	if (AOM.AMG.Tests.isNumber(value)) {
		return value;
	} else {
		return AOM.AmgUserInput.htmlEncoding(value);
	}
}

AOM.AmgAirtightGalleryCreator.transformFiles = function (galleryFolder)
{
	var replaceList = {};
	replaceList["%_airtight_windowtitle%"] = AOM.AmgAirtightGalleryCreator.get("siteTitle");
	replaceList["%_airtight_appearance.airTight.backgroundColor%"] = AOM.AmgAirtightGalleryCreator.get("backgroundColor");
	replaceList["%_airtight_openimage%"] = AOM.AMG.localize("$$$/MediaGallery/JavaScript/FlashGallery/OpenImage=Open Image in New Window");
	replaceList["%_airtight_about%"] = AOM.AMG.localize("$$$/MediaGallery/JavaScript/FlashGallery/About=About");
	replaceList["%_airtight_noimages%"] = AOM.AMG.localize("$$$/MediaGallery/JavaScript/FlashGallery/NoImages=No images");
	replaceList["%_airtight_pneedflash%"] = AOM.AMG.localize("$$$/MediaGallery/JavaScript/FlashGallery/PostNeedFlash=PostcardViewer requires Adobe Flash.");
	replaceList["%_airtight_aneedflash%"] = AOM.AMG.localize("$$$/MediaGallery/JavaScript/FlashGallery/AutoNeedFlash=AutoViewer requires Adobe Flash.");
	replaceList["%_airtight_sneedflash%"] = AOM.AMG.localize("$$$/MediaGallery/JavaScript/FlashGallery/SimpleNeedFlash=SimpleViewer requires Adobe Flash.");
	replaceList["%_airtight_getflash%"] = AOM.AMG.localize("$$$/MediaGallery/JavaScript/FlashGallery/GetFlash=Get Adobe Flash.");
	replaceList["%_airtight_haveflash%"] = AOM.AMG.localize("$$$/MediaGallery/JavaScript/FlashGallery/HaveFlash=If you have Flash installed,");
	replaceList["%_airtight_viewgallery%"] = AOM.AMG.localize("$$$/MediaGallery/JavaScript/FlashGallery/ViewGallery=click to view gallery");
	var regex = /%_airtight_[^%\s]*?%/;
	AOM.AmgAirtightGalleryCreator.searchReplaceFile(new File(galleryFolder + "index.html"), regex, replaceList);
	
	//AOM.AMG.localizeFile(new File(galleryFolder + "/resources/localText.xml"));
}

AOM.AmgAirtightGalleryCreator.searchReplaceFile = function (file, regex, replaceList)
{
	if (!file.open("r"))
	{
		AOM.AMG.Log.writeError("searchReplaceFile - could not open file for read ("+file.fsName+")");
		throw({action:"stop", title: AOM.ZStringDialogTitle,
               description: AOM.AMG.localize("$$$/MediaGallery/JavaScript/FlashGallery/FailOpenReadFile=Could not open/read file - gallery creation stopped.") });
	}
	var contents = file.read();
	file.close();
	
	var match;
	while((match = contents.match(regex)) != null)
	{
			var replacement = replaceList[match];
			if (replacement == undefined)
			{
				AOM.AMG.Log.writeError("searchReplaceFile - no entry in replaceList for '" + match + "'");
				throw({action:"stop", title: AOM.ZStringDialogTitle,
                       description: AOM.AMG.localize("$$$/MediaGallery/JavaScript/FlashGallery/FailPerformOperation=Could not perform operation - gallery creation stopped.") });
			}
			contents = contents.replace(new RegExp(match, "g"), replacement);
	}
	file.encoding = "UTF8";
	if (!file.open("w", "TEXT", "????"))
	{
		AOM.AMG.Log.writeError("searchReplaceFile - could not open file for write ("+file.fsName+")");
		throw({action:"stop", title: AOM.ZStringDialogTitle,
               description: AOM.AMG.localize("$$$/MediaGallery/JavaScript/FlashGallery/FailOpenWriteFile=Could not open/write file - gallery creation stopped.") });
	}
	file.write("\uFEFF");
	file.write(contents);
	file.close();
}
AOM.AmgAirtightGalleryCreator.simpleViewerMakeXml = function (images, file, galleryFolder)
{
	if (file instanceof File == false)
		return AOM.AMG.Log.writeError("AOM.AmgHtmlGalleryCreator.makeXml - file is not File");
	var siteTitle = AOM.AmgAirtightGalleryCreator.get("siteTitle");
	var frameWidth = AOM.AmgAirtightGalleryCreator.get("frameWidth");
	var frameColor = AOM.AmgAirtightGalleryCreator.get("frameColor");
	
	var textColor = AOM.AmgAirtightGalleryCreator.get("textColor");
	var stagePadding = AOM.AmgAirtightGalleryCreator.get("stagePadding");
	var thumbnailColumns = AOM.AmgAirtightGalleryCreator.get("thumbnailColumns");
	var thumbnailRows = AOM.AmgAirtightGalleryCreator.get("thumbnailRows");
	var navPosition = AOM.AmgAirtightGalleryCreator.get("navPosition");
	var enableRightClickOpen = AOM.AmgAirtightGalleryCreator.get("enableRightClickOpen");
	var customtext = AOM.AmgAirtightGalleryCreator.get("customtext");
	
	file.encoding = "UTF8";
	file.lineFeed = "unix";
	if (file.open("w", "TEXT", "????"))
	{
		file.write("\uFEFF");
		file.writeln("<?xml version='1.0' encoding='UTF-8'?>");
		file.write("<simpleviewerGallery backgroundImagePath=\"\" maxImageWidth=\"1500\" maxImageHeight=\"1500\" imagePath=\"images/large/\" thumbPath=\"images/thumb/\" ");
		file.write("frameColor=\"0x" + frameColor + "\" ");
		file.write("textColor=\"0x" + textColor + "\" ");
		file.write("frameWidth=\"" + frameWidth + "\" ");
		file.write("stagePadding=\"" + stagePadding + "\" ");
		file.write("thumbnailColumns=\"" + thumbnailColumns + "\" ");
		file.write("thumbnailRows=\"" + thumbnailRows + "\" ");
		file.write("navPosition=\"" + navPosition + "\" ");
		file.writeln("enableRightClickOpen=\"" + enableRightClickOpen + "\"> ");
		var imageCount = 0;
		for (var i = 0; i < images.length; i++) {
			if (!images[i].amgSkip())
				imageCount++;
		}
		var number = 1;
		for (var i = 0; i < images.length; i++) {
			if (!images[i].amgSkip()) {
				var alteredName = AOM.AmgHtmlGalleryCreator.processSpecialChars(images[i].amg.alteredName, true);
				var subName = AOM.AmgFlashGalleryCreator.escapeSpecialChars(images[i].name, true);
				var displayName = AOM.PDFGenerator.combineDiacriticMarks(subName);
				displayName = AOM.AmgGalleryCreator.removeImageExtension(displayName);
				file.writeln("<image>");
				file.writeln("<filename>" + alteredName + "</filename>");
				file.write("<caption>");
				var caption = AOM.AmgAirtightGalleryCreator.get("caption");
				var selected = AOM.AmgAirtightGalleryCreator.get("captiondropdown");
				var metadata = images[i].metadata;
				if (metadata != undefined)
					metadata.namespace = "http://purl.org/dc/elements/1.1/";
				var title = (metadata != undefined && metadata.title != undefined) ? metadata.title : "";
				var description = (metadata != undefined && metadata.description != undefined) ? metadata.description : "";
				var fulldate = images[i].bestCreationDate;
				var date = AOM.AmgAirtightGalleryCreator.getAlignedNumber(fulldate.getFullYear(), 4) + "/" 
					+ AOM.AmgAirtightGalleryCreator.getAlignedNumber(fulldate.getMonth() + 1, 2) + "/" 
					+ AOM.AmgAirtightGalleryCreator.getAlignedNumber(fulldate.getDate(), 2);
				if (caption == "true") {
					switch (selected) {
						case "Caption":
							file.write(description);
							break;
						case "Custom Text":
							file.write(customtext);
							break;
						case "Date":
							file.write(date);
							break;
						case "Equipment":
							file.write(AOM.AmgAirtightGalleryCreator.getMetadata(images[i], "Equipment"));
							break;
						case "Exposure":
							file.write(AOM.AmgAirtightGalleryCreator.getMetadata(images[i], "Exposure"));
							break;
						case "Filename":
							file.write(displayName);
							break;
						case "Sequence":
							file.write(number + " / " + imageCount);
							number++;
							break;
						case "Title":
							file.write(title);
							break;
						default:break;
					}
				}
				file.writeln("</caption>");
				file.writeln("</image>");
			}
		}
		file.writeln("</simpleviewerGallery>");
		file.close();
	}
	else
	{
		AOM.AMG.Log.writeError(AOM.AMG.localize("$$$/MediaGallery/htmlGallery/couldntOpen=Could not open ") + file.fsName);
		throw({title:AOM.ZStringHtmlDialogTitle, description:AOM.AMG.localize("$$$/MediaGallery/htmlGallery/couldntOpen=Could not open ") + file.fsName});
	}
}

AOM.AmgAirtightGalleryCreator.autoViewerMakeXml = function (images, file, galleryFolder)
{
	if (file instanceof File == false)
		return AOM.AMG.Log.writeError("AOM.AmgHtmlGalleryCreator.makeXml - file is not File");
	var siteTitle = AOM.AmgAirtightGalleryCreator.get("siteTitle");
	var frameWidth = AOM.AmgAirtightGalleryCreator.get("frameWidth");
	var frameColor = AOM.AmgAirtightGalleryCreator.get("frameColor");
	var imagePadding = AOM.AmgAirtightGalleryCreator.get("imagePadding");
	var displayTime = AOM.AmgAirtightGalleryCreator.get("displayTime");
	var customtext = AOM.AmgAirtightGalleryCreator.get("customtext");
	
	file.encoding = "UTF8";
	file.lineFeed = "unix";
	if (file.open("w", "TEXT", "????"))
	{
		file.write("\uFEFF");
		file.writeln("<?xml version='1.0' encoding='UTF-8'?>");
		file.write("<gallery title=\"" + siteTitle + "\" ");
		file.write("frameColor=\"0x" + frameColor + "\" ");
		file.write("frameWidth=\"" + frameWidth + "\" ");
		file.write("imagePadding=\"" + imagePadding + "\" ");
		file.writeln("displayTime=\"" + displayTime + "\"> ");
		var imageCount = 0;
		for (var i = 0; i < images.length; i++) {
			if (!images[i].amgSkip())
				imageCount++;
		}
		var number = 1;
		for (var i = 0; i < images.length; i++) {
			if (!images[i].amgSkip()) {
				var alteredName = AOM.AmgHtmlGalleryCreator.processSpecialChars(images[i].amg.alteredName, true);
				var subName = AOM.AmgFlashGalleryCreator.escapeSpecialChars(images[i].name, true);
				var displayName = AOM.PDFGenerator.combineDiacriticMarks(subName);
				displayName = AOM.AmgGalleryCreator.removeImageExtension(displayName);
				file.writeln("<image>");
				file.writeln("<url>images/large/" + alteredName + "</url>");
				file.write("<caption>");
				var caption = AOM.AmgAirtightGalleryCreator.get("caption");
				var selected = AOM.AmgAirtightGalleryCreator.get("captiondropdown");
				var metadata = images[i].metadata;
				if (metadata != undefined)
					metadata.namespace = "http://purl.org/dc/elements/1.1/";
				var title = (metadata != undefined && metadata.title != undefined) ? metadata.title : "";
				var description = (metadata != undefined && metadata.description != undefined) ? metadata.description : "";
				var fulldate = images[i].bestCreationDate;
				var date = AOM.AmgAirtightGalleryCreator.getAlignedNumber(fulldate.getFullYear(), 4) + "/" 
					+ AOM.AmgAirtightGalleryCreator.getAlignedNumber(fulldate.getMonth() + 1, 2) + "/" 
					+ AOM.AmgAirtightGalleryCreator.getAlignedNumber(fulldate.getDate(), 2);
				if (caption == "true") {
					switch (selected) {
						case "Caption":
							file.write(description);
							break;
						case "Custom Text":
							file.write(customtext);
							break;
						case "Date":
							file.write(date);
							break;
						case "Equipment":
							file.write(AOM.AmgAirtightGalleryCreator.getMetadata(images[i], "Equipment"));
							break;
						case "Exposure":
							file.write(AOM.AmgAirtightGalleryCreator.getMetadata(images[i], "Exposure"));
							break;
						case "Filename":
							file.write(displayName);
							break;
						case "Sequence":
							file.write(number + " / " + imageCount);
							number++;
							break;
						case "Title":
							file.write(title);
							break;
						default:break;
					}
				}
				file.writeln("</caption>");
				file.write("<width>");
				file.write(images[i].amg.sizes["large"].width);
				file.writeln("</width>");
				file.write("<height>");
				file.write(images[i].amg.sizes["large"].height);
				file.writeln("</height>");
				file.writeln("</image>");
			}
		}
		file.writeln("</gallery>");
		file.close();
	}
	else
	{
		AOM.AMG.Log.writeError(AOM.AMG.localize("$$$/MediaGallery/htmlGallery/couldntOpen=Could not open ") + file.fsName);
		throw({title:AOM.ZStringHtmlDialogTitle, description:AOM.AMG.localize("$$$/MediaGallery/htmlGallery/couldntOpen=Could not open ") + file.fsName});
	}
}

AOM.AmgAirtightGalleryCreator.postcardViewerMakeXml = function (images, file, galleryFolder)
{
	if (file instanceof File == false)
		return AOM.AMG.Log.writeError("AOM.AmgHtmlGalleryCreator.makeXml - file is not File");
	var width = parseInt(AOM.AmgAirtightGalleryCreator.get("largeSizeSlider"), 10);
	var padding = parseInt(AOM.AmgAirtightGalleryCreator.get("stagePadding"), 10);
	var cellDimension = width + padding;
	var columns = AOM.AmgAirtightGalleryCreator.get("thumbnailColumns");
	var zoomOutPerc = AOM.AmgAirtightGalleryCreator.get("zoomOutPerc");
	var zoomInPerc = AOM.AmgAirtightGalleryCreator.get("zoomInPerc");
	var frameWidth = AOM.AmgAirtightGalleryCreator.get("frameWidth");
	var customtext = AOM.AmgAirtightGalleryCreator.get("customtext");
	file.encoding = "UTF8";
	file.lineFeed = "unix";
	if (file.open("w", "TEXT", "????"))
	{
		file.write("\uFEFF");
		file.writeln("<?xml version='1.0' encoding='UTF-8'?>");
		file.write("<gallery cellDimension=\"" + cellDimension + "\" ");
		file.write("columns=\"" + columns + "\" ");
		file.write("zoomOutPerc=\"" + zoomOutPerc + "\" ");
		file.write("zoomInPerc=\"" + zoomInPerc + "\" ");
		file.write("frameWidth=\"" + frameWidth + "\" ");
		file.writeln("captionColor=\"0xFFFFFF\" enableRightClickOpen=\"true\">");
		var imageCount = 0;
		for (var i = 0; i < images.length; i++) {
			if (!images[i].amgSkip())
				imageCount++;
		}
		var number = 1;
		for (var i = 0; i < images.length; i++) {
			if (!images[i].amgSkip()) {
				var alteredName = AOM.AmgHtmlGalleryCreator.processSpecialChars(images[i].amg.alteredName, true);
				var subName = AOM.AmgFlashGalleryCreator.escapeSpecialChars(images[i].name, true);
				var displayName = AOM.PDFGenerator.combineDiacriticMarks(subName);
				displayName = AOM.AmgGalleryCreator.removeImageExtension(displayName);
				file.writeln("<image>");
				file.writeln("<url>images/large/" + alteredName + "</url>");
				file.write("<caption>");
				var caption = AOM.AmgAirtightGalleryCreator.get("caption");
				var selected = AOM.AmgAirtightGalleryCreator.get("captiondropdown");
				var metadata = images[i].metadata;
				if (metadata != undefined)
					metadata.namespace = "http://purl.org/dc/elements/1.1/";
				var title = (metadata != undefined && metadata.title != undefined) ? metadata.title : "";
				var description = (metadata != undefined && metadata.description != undefined) ? metadata.description : "";
				var fulldate = images[i].bestCreationDate;
				var date = AOM.AmgAirtightGalleryCreator.getAlignedNumber(fulldate.getFullYear(), 4) + "/" 
					+ AOM.AmgAirtightGalleryCreator.getAlignedNumber(fulldate.getMonth() + 1, 2) + "/" 
					+ AOM.AmgAirtightGalleryCreator.getAlignedNumber(fulldate.getDate(), 2);
				if (caption == "true") {
					switch (selected) {
						case "Caption":
							file.write(description);
							break;
						case "Custom Text":
							file.write(customtext);
							break;
						case "Date":
							file.write(date);
							break;
						case "Equipment":
							file.write(AOM.AmgAirtightGalleryCreator.getMetadata(images[i], "Equipment"));
							break;
						case "Exposure":
							file.write(AOM.AmgAirtightGalleryCreator.getMetadata(images[i], "Exposure"));
							break;
						case "Filename":
							file.write(displayName);
							break;
						case "Sequence":
							file.write(number + " / " + imageCount);
							number++;
							break;
						case "Title":
							file.write(title);
							break;
						default:break;
					}
				}
				file.writeln("</caption>");
				file.writeln("</image>");
			}
		}
		file.writeln("</gallery>");
		file.close();
	}
	else
	{
		AOM.AMG.Log.writeError(AOM.AMG.localize("$$$/MediaGallery/htmlGallery/couldntOpen=Could not open ") + file.fsName);
		throw({title:AOM.ZStringHtmlDialogTitle, description:AOM.AMG.localize("$$$/MediaGallery/htmlGallery/couldntOpen=Could not open ") + file.fsName});
	}
}
AOM.AmgAirtightGalleryCreator.getMetadata = function(thumb, kind)
{	
	AOM.XMPUtil.loadXMPLib();
	
	var text = "";
	
	try {
		if(thumb.hasMetadata)
		{	
			var myXmp = new XMPMeta(thumb.metadata.serialize());
			
			switch (kind) {
				case "Equipment":
					var prop = myXmp.getProperty(XMPConst.NS_TIFF, "Model", XMPConst.STRING);
					if (prop != undefined)
						text = prop.value;
					else
						text = "-";
					break;
				case "Exposure":
					expos = myXmp.getProperty(XMPConst.NS_EXIF, "ExposureTime", XMPConst.STRING);
					fnum = myXmp.getProperty(XMPConst.NS_EXIF, "FNumber", XMPConst.STRING);
					var state = 0;
					var f = 0;
					if (expos == undefined) {
						state = 1;
					}
					if (fnum != undefined) {
						try {
							eval("f = (" + fnum.value + ").toFixed(1);");
						} catch (e) {
							if (state == 1)
								state = 2;
							else
								state = 3;
						}
					} else {
						if (state == 1)
							state = 2;
						else
							state = 3;
					}
					switch (state) {
						case 0:
							text = AOM.localizeWithArgs("$$$/MediaGallery/htmlGallery/ExposureDisplay=(1) sec at f / (2)", [expos.value, f]);
							break;
						case 1:
							text = AOM.localizeWithArgs("$$$/MediaGallery/htmlGallery/ExposureWithFnum=f / (1)", f);
							break;
						case 3:
							text = AOM.localizeWithArgs("$$$/MediaGallery/htmlGallery/ExposureWithExpos=(1) sec", expos.value);
							break;
						default:break;
					}
					break;
				default:break;
			}
		}
	} catch(e) {
	
	}
	return text;
}

AOM.AmgAirtightGalleryCreator.getAlignedNumber = function(num, length)
{
	var s = new String(num);
	if(s.length >= length)
		return s;

	var prefix = "";
	for(var i = 0; i < length - s.length; ++i)
		prefix += "0";

	return prefix + s;
}

