// ----------------------------------------------------
//
<!--
/*************************************************************************
*
* ADOBE CONFIDENTIAL
* ___________________
*
* Copyright 2006 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.
**************************************************************************/
-->
// ----------------------------------------------------
//
// InsertOfficeDocAsPDF.js
//
// ----------------------------------------------------



// ----------------------------------------------------
// globals
// ----------------------------------------------------

var g_file = null;
var g_retVal = null;
var g_insertmode = null;

// ----------------------------------------------------
// public functions
// ----------------------------------------------------

function receiveArguments()
{
	g_file = arguments[0];
	g_retVal = arguments[1];
	g_insertmode = arguments[2];
}

function run()
{
	var result = insertOfficeDocAsPDF( g_file, g_insertmode );
	if (g_retVal != null)
		g_retVal[0] = result;
}

function isAcroElementsAvailable(warnUserIfNotAvailable)
{
	if (dw.isPDFConverterAvailable())
	{	
		
		return true;
	}
	else
	{
		if (warnUserIfNotAvailable)
		{
				alert(dw.loadString("acroelements/acroelements install error"));
		}
		return false;
	}
}

function insertOfficeDocAsPDF(sourceURL, insertmode)
{
	/*const*/ var warnUserIfNotAvailable = true;
	if (!isAcroElementsAvailable(warnUserIfNotAvailable))
	{
		return false;
	}

	if (sourceURL == null || sourceURL == "") 
	{
		return false;
	}

	var prefsAccessibilityOption;
	if (dw.appName == "Contribute")
	{
		prefsAccessibilityOption = dw.getAdminEnforceAccessibilityPref();
	}
	else
	{
		prefsAccessibilityOption = dw.getPreferenceString("Accessibility", "Accessibility Image Options", "");
	}
	
	var isBlogSite = false;
	if (dw.appName == "Contribute")
	{
		
		var dom = dw.getDocumentDOM();
	        if(dom)
	        {
	             if(CCWorkspaceManager.getManager(dom))
	              { // if its a blog, do not display the accessibility warning
	                    if(CCWorkspaceManager.getManager(dom).isBlogSite())        
	                        isBlogSite = true;
	              }
	        }
         }
	

	//  "real" pathname from fileURL
	var sourceFile_s = MMNotes.localURLToFilePath(dw.doURLDecoding(sourceURL));
	
	
	var destURL = dw.doURLEncoding(calcUniqueDestURL(sourceURL));
	
	if (destURL == null || destURL == "")
	{
		alert(dw.loadString("acroelements/pdf conversion error"));
		return false;
	}

	// package up the info we need to save in the progress callback.
	var destFile_s = MMNotes.localURLToFilePath(dw.doURLDecoding(destURL));
	
	
	
	if(dw.isFilelocked(sourceFile_s))
	{
		var tempsourceFile_s = dw.getTempFilename(sourceFile_s);
		dw.convertOfficetoPDF( tempsourceFile_s, destFile_s );
		dw.delTempfile(tempsourceFile_s);
	}
	else
	{
		dw.convertOfficetoPDF( sourceFile_s, destFile_s );
	}
	
	
	
	if(!(DWfile.exists(MMNotes.filePathToLocalURL(destFile_s))))
	{
		alert(dw.loadString("acroelements/pdf conversion error"));
		return false;
	
	}
	
	if( insertmode == "linkpdf")
	{
		
		result = dw.insertLinkToDocument(destFile_s);
		return true;
	}
	else
	{
	
		var width = 70;
		var height = 99;

		var winWidth = dw.getDocumentDOM().parentWindow.innerWidth;
		if(isBlogSite)
		{
			winWidth = 200;
		}
		if (width > 0 && height > 0 && winWidth > 0)
		{
			/*const*/ var PERCENT_OF_WIDTH = 0.90;
			var aspectRatio = width / height;
			width = Math.round(winWidth * PERCENT_OF_WIDTH);
			height = Math.round(width / aspectRatio);
		}
		
		
		var rtnStr = '<OBJECT CLASSID="clsid:CA8A9780-280D-11CF-A24D-444553540000" ' + 
					'WIDTH="' + width.toString() + '" HEIGHT="' + height.toString() + '">\n' + 
					'<PARAM NAME="src" VALUE="' + destURL +  '"> \n' +
					'<EMBED SRC="' + destURL + 
					'" PLUGINSPAGE="http://www.adobe.com/products/acrobat/readstep2.html" ' +
					'TYPE="application/pdf" WIDTH="' + width.toString() + '" HEIGHT="' + height.toString() + '">'+
					'</EMBED></OBJECT>';

		prefsAccessibilityOption = dw.getPreferenceString("Accessibility", "Accessibility Media Options", "");

		if (prefsAccessibilityOption == 'TRUE')
		{
			rtnStr = addAccessibility(rtnStr);
		}
		
	
		/*const*/ var bReplaceCurrentSelection = true;
		dw.getDocumentDOM().insertHTML(rtnStr, bReplaceCurrentSelection);
		return true;
	}
}



// ----------------------------------------------------
// private functions
// ----------------------------------------------------

function getLeafName(url)
{
	if (url.length > 0 && url[url.length-1] == '/')
		url = url.substr(0, url.length-1);

	var lastSlash = url.lastIndexOf("/");
	if (lastSlash != -1)
		return url.substr(lastSlash+1);
	else
		return url;
}

function stripExtension(url)
{
	var lastDot = url.lastIndexOf(".");
	if (lastDot >= 1)
		return url.slice(0, lastDot);
	else
		return url;
}

function calcUniqueDestURL(sourceURL)
{	
	if (typeof(FileStateManager.getLocalAssetsDirURLForSite) == "undefined")
	{
		return "";
	}

	var destDir = FileStateManager.getLocalAssetsDirURLForSite("");
	if (destDir[destDir.length-1] != "/")
		destDir += "/";
	var destLeafName = stripExtension(getLeafName(sourceURL));

	// if there are any double-byte chars, make up a new name.
	// we can do this quietly (and sloppily) since the filename
	// doesn't really have to be user-friendly, just unique.
	var tester = dw.doURLDecoding(destLeafName);
	for (i = 0; i < tester.length; i++) 
	{
		var charCode = tester.charCodeAt(i);
		if (charCode > 255) 
		{
			// it's a doublebyte char. 
			// since we're going to uniquify the name below, just
			// give it a bland base name.
			destLeafName = "untitled";
			break;
		}
	}

	var destURL = "";
	for (var i = 0; i < 99999; ++i)
	{
		destURL = destDir;
		destURL += destLeafName;
		if (i != 0)
			destURL += i.toString();
		destURL += ".pdf";
		// strangely, DWfile.exists() doesn't decode urls (eg, %20->space), 
		// so we must do that ourselves.
		destURL = dw.doURLDecoding(destURL);
		if (!DWfile.exists(destURL))
		{
			return destURL;
		}
	}

	return "";
}


function addAccessibility(rtnStr) 
{
   var cmdFile = dreamweaver.getConfigurationPath() + "/Commands/Object Options.htm";
   var cmdDOM = dreamweaver.getDocumentDOM(cmdFile);
 
   cmdDOM.parentWindow.setFormItem(rtnStr);
   dreamweaver.popupCommand("Object Options.htm");
   return (cmdDOM.parentWindow.returnAccessibilityStr(rtnStr));	
}

