/////////////////////////////////////////////////////////////////////////////////////////////
//
// This is a Javascript library to write multi-browser pages comprising CS ChemDraw Plugin/ActiveX.
//
//
// You will use following three functions in your web pages:
//   cd_insertObjectStr()
//   cd_insertObject()
//   cd_includeWrapperFile()
//  
// To support other browsers outside IE and Netscape, you should change following function:
//   cd_figureOutUsing()
//
// When changing file name of ActiveX package (CAB file) or having these file in different URL address,
// change following four variables:
//   CD_CONTROL70CAB
//   CD_CONTROL60CAB
//
// Usually no need for you to change other variables or functions.
//
//
// All Rights Reserved.
// (version 1.018) NOV 13, 2001
/////////////////////////////////////////////////////////////////////////////////////////////



// ------------------------------------- GLOBAL DATA -------------------------------------------
// Global data. Very IMPORTANT, never never change them.


var CD_CONTROL70CLSID = "clsid:AF2D2DC1-75E4-4123-BC0B-A57BD5C5C5D2";
var CD_CONTROL60CLSID = "clsid:FA549D21-6F54-11D2-B61B-00C04F736BDF";

// MOST IMPORTANT!!! To indicate use which Plugin/ActiveX
// 1 - Control/ActiveX;  2 - old Plugin;  3 - new Plugin.
var cd_currentUsing = 0;

// Place following two files in the same folder as cdlib_ns.js and cdlib_ie.js
var CD_PLUGIN_JAR = "camsoft.jar";
var CD_PLUGIN_CAB = "camsoft.cab";



// ------------------------------------- TODO AREA -------------------------------------------
// You may change this part when using for your website.


/////////////////////////////////////////////////////////////////////////////////////////////
// TODO: Change following four variables when you have different file names or path for this files

var CD_CONTROL70CAB = "ChemDrawCtl70.cab";
var CD_CONTROL60CAB = "ChemDrawCtl.cab";


/////////////////////////////////////////////////////////////////////////////////////////////
// TODO: change following two variables to support ActiveX 7.0 or 6.0
// For 7.0 activex, set CONTROL_CLSID = CONTROL70CLSID and CONTROL_CAB = CONTROL70CAB
// For 6.0 activex, set CONTROL_CLSID = CONTROL60CLSID and CONTROL_CAB = CONTROL60CAB

var CD_CONTROL_CLSID = CD_CONTROL70CLSID;
var CD_CONTROL_CAB   = CD_CONTROL70CAB;


/////////////////////////////////////////////////////////////////////////////////////////////
// This function is the most important function !!! It must be ran before all other functions.
// To figure out which Plugin/ActiveX should be used.

function cd_figureOutUsing() {
	// Only 1, 2, 3 are used. Other codes make no sense.
	// 1 - Control/ActiveX;  2 - old Plugin;  3 - new Plugin.
	
	var version = cd_getBrowserVersion();

	// CURRENT SETTING:
	//    ActiveX Control (1) - IE 5.5 or higher versions
	//    old Plugin      (2) - IE 5.0 or lower versions, Netscape 4.x or lower versions
	//    new Plugin      (3) - Netscape 6.0 or higher versions
	if (cd_testBrowserType("Microsoft Internet Explorer")) {
		if (version < 5.5)
			cd_currentUsing = 2;
		else
			cd_currentUsing = 1;
	}
	else if (cd_testBrowserType("Netscape")) {
		if (version < 5.0)
			cd_currentUsing = 2;
		else if (version >= 5.0)
			cd_currentUsing = 3;
	}


	// TODO: add code to support other browsers outside IE and Netscape
	// else if (...)
	//		cd_currentUsing = 1 or 2 or 3;


	// Other unknow browser types.
	else
		cd_currentUsing = 0;
}




// ------------------------------------- FUNCTIONS USED IN WEB PAGES -------------------------------------------
// Following three functions will be used in web pages


/////////////////////////////////////////////////////////////////////////////////////////////
// This function to insert a browser-specific Plugin/ActiveX object.
// Parameter - tagStr - should like following sample:
// cd_insertObjectStr("<EMBED src='HTML/blank.cdx' align='baseline' border= '0' width='267' height='128' type= 'chemical/x-cdx' name= 'myCDX'>");

function cd_insertObjectStr(tagStr) {
	var paraArray = {"type" : "", "width" : "", "height" : "", "name" : "", "src" : "", "viewonly" : "", "shrinktofit" : "", "dataurl" : ""};
	
	cd_parsePara(tagStr, paraArray);

	cd_insertObject(paraArray["type"], paraArray["width"], paraArray["height"], paraArray["name"],
				 paraArray["src"], paraArray["viewonly"], paraArray["shrinktofit"], paraArray["dataurl"]);
}


/////////////////////////////////////////////////////////////////////////////////////////////
// This function to insert a browser-specific Plugin/ActiveX object. 
// The first 3 parameters [mimeType, objWidth, objHeight] is required, and the last 5 is optional.

function cd_insertObject(mimeType, objWidth, objHeight, objName, srcFile, viewOnly, shrinkToFit, dataURL) {
	document.write( cd_getSpecificObjectTag(mimeType, objWidth, objHeight, objName, srcFile, viewOnly, shrinkToFit, dataURL) );
}


/////////////////////////////////////////////////////////////////////////////////////////////
// Use this function to insert Plugin/ActiveX wrapper file.

function cd_includeWrapperFile(basePath) {
	if (basePath == null)
		basePath = "";
	else if (basePath.length > 0) {
		var lastChar = basePath.charAt(basePath.length - 1);
		if (!(lastChar == "\\" || lastChar == "/"))
			basePath += "\\";

		CD_PLUGIN_JAR = basePath + CD_PLUGIN_JAR;
		CD_PLUGIN_CAB = basePath + CD_PLUGIN_CAB;
	}

	var wrapperfile = "<script language=JavaScript src=\"";
	
	if (cd_currentUsing == 2 || cd_currentUsing == 3) // Plugin
		wrapperfile += basePath + "cdlib_ns.js";
	else if (cd_currentUsing ==  1) // ActiveX
		wrapperfile += basePath + "cdlib_ie.js";
		
	wrapperfile += "\"></script>";

	document.write(wrapperfile);
}




// ------------------------------------- INTERNAL FUNCTIONS DEFINATION -------------------------------------------
// You may never change following codes.


/////////////////////////////////////////////////////////////////////////////////////////////
// At first, run figureOutUsing() to initilize *currentUsing*.

cd_figureOutUsing();


/////////////////////////////////////////////////////////////////////////////////////////////
// According to browser type and version, choose its corresponding ChemDraw Plugin/ActiveX tag.
// The first 3 parameters [mimeType, objWidth, objHeight] is required, and the last 5 is optional.

var cd_pluginID = 1000;
function cd_getSpecificObjectTag(mimeType, objWidth, objHeight, objName, srcFile, viewOnly, shrinkToFit, dataURL) {
	var buf = "";
	
	if (cd_currentUsing == 1) { // ActiveX
		buf =	"<OBJECT classid=\"" + CD_CONTROL_CLSID + "\" codeBase=\"" + CD_CONTROL_CAB + "\" " +
				"style=\"HEIGHT: " + objHeight + "px; WIDTH: " + objWidth + "px\"";
				
		if (objName != null && objName != "")
			buf += " name=\"" + objName + "\"";
			
		buf += ">\n";

		if (srcFile != null && srcFile != "")			
			buf += "<param NAME=\"SourceURL\" VALUE=\"" + srcFile + "\">\n";

		if (dataURL != null && dataURL != "")
			buf += "<param NAME=\"DataURL\" VALUE=\"" + dataURL + "\">\n";
		
		if (viewOnly != null && viewOnly != "")
			buf += "<param NAME=\"ViewOnly\" VALUE=\"" + viewOnly + "\">\n";

		if (shrinkToFit != null && shrinkToFit != "")
			buf += "<param NAME=\"ShrinkToFit\" VALUE=\"" + shrinkToFit + "\">\n";
		
		buf += "</OBJECT>\n";
	}
	else if (cd_currentUsing == 2 || cd_currentUsing == 3) { // Plugin
		var pluginID = ++cd_pluginID;
		if (cd_currentUsing == 2) {
			// old Plugin needs CDPHelper

			if (objName == null)
				objName == "";
			
			buf =	"<APPLET NAME=\"" + objName + "\" CODE=\"camsoft.cdp.CDPHelperAppSimple\" WIDTH=0 HEIGHT=0 ARCHIVE=\"" + CD_PLUGIN_JAR + "\">" +
				"<PARAM NAME=ID VALUE=\"" + pluginID + "\">" +
				"<PARAM NAME=cabbase value=\"" + CD_PLUGIN_CAB + "\"></APPLET>\n";

		}

		if (srcFile == null)
			srcFile == "";
					
		buf +=	"<EMBED " +
				"src=\"" + srcFile + "\"" + 
				" width=\"" + objWidth + "\"" +
				" height=\"" + objHeight + "\"" +
				" type=\"" + mimeType + "\"";
				
		if (objName != null && objName != "")
			buf += " name=\"" + objName + "\"";

		if (cd_currentUsing == 2) 
			buf += " id=\"" + pluginID + "\"";
			
		if (dataURL != null && dataURL != "")
			buf += " dataurl=\"" + dataURL + "\"";
		
		if (viewOnly != null && viewOnly != "")
			buf += " viewonly=\"" + viewOnly + "\"";

		if (shrinkToFit != null && shrinkToFit != "")
			buf += " shrinktofit=\"" + shrinkToFit + "\"";
			
		buf += ">\n";
	}
	
	return buf;	
}


/////////////////////////////////////////////////////////////////////////////////////////////
// This function to return the reference of ChemDraw Plugin/ActiveX by its name.

function cd_getSpecificObject(nm) {
	var r = null;

	if (cd_currentUsing == 1) // ActiveX Control
		r = document.all(nm);
	else if (cd_currentUsing == 2) // old Plugin + CDPHelper
		r = document.applets[nm];
	else if (cd_currentUsing == 3) // new Plugin (XPCOM)
		r = document.embeds[nm];

	if (r == null)
		alert("ERROR: You have the wrong name [" + nm + "] to refer to the Plugin/ActiveX !!!");

	return r;
}


/////////////////////////////////////////////////////////////////////////////////////////////
// To get Browser's version.

function cd_getBrowserVersion() {
	if (cd_testBrowserType("Microsoft Internet Explorer")) {
		var str = navigator.appVersion;
		var i = str.indexOf("MSIE");
		if (i >= 0) {
			str = str.substr(i + 4);
			return parseFloat(str);
		}
		else
			return 0;
	}
	else if (cd_testBrowserType("Netscape") && parseFloat(navigator.appVersion) >= 5.0 && navigator.vendorSub != null && parseFloat(navigator.vendorSub) != NaN) {
		return parseFloat(navigator.vendorSub);
	}
	else
		return parseFloat(navigator.appVersion);
}


/////////////////////////////////////////////////////////////////////////////////////////////
// To test browser's type.

function cd_testBrowserType(brwType) {
	return (navigator.appName.indexOf(brwType) != -1);
}


/////////////////////////////////////////////////////////////////////////////////////////////
// This function to parse all useful parameter from <EMBED> string. Return values is
// stored an array.
// <embed width="200" HEIGHT="200" type="chemical/x-cdx" src="mols/blank.cdx" dataurl="mols/toluene.mol" viewonly="TRUE">

function cd_parsePara(str, paraArray) {
	str = str.toLowerCase();
	
	for (var p in paraArray)
		paraArray[p] = cd_getTagValue(p, str);
}


/////////////////////////////////////////////////////////////////////////////////////////////
// This function return the tag value from <EMBED> string.

function cd_getTagValue(tag, str) {
	var r = "";
	var pos = str.indexOf(tag, 0);
	var taglen = tag.length;
	
	// make sure tag is a whole word
	while (pos >= 0 && !(pos == 0 && (str.charAt(taglen) == " " || str.charAt(taglen) == "=") ||
		pos > 0 && str.charAt(pos - 1) == " " && (str.charAt(pos + taglen) == " " || str.charAt(pos + taglen) == "=")) ) {
		pos += taglen;
		pos = str.indexOf(tag, pos);
	}

	if (pos >= 0) {		
		// skip the space chars following tag
		pos += taglen;
		while (str.charAt(pos) == " ")
			pos++;
		
		// following char must be '='
		if (str.charAt(pos) == "=") {
			pos++;
			
			// skip the space chars following '='
			while (str.charAt(pos) == " ")
				pos++;
			
			var p2 = pos;
			if (str.charAt(pos) == "\"") {
				pos++;
				p2 = str.indexOf("\"", pos);
			}
			else if (str.charAt(pos) == "\'") {
				pos++;
				p2 = str.indexOf("\'", pos);
			}
			else {
				p2 = str.indexOf(" ", pos);
			}
			
			if (pos > p2)
				p2 = str.length - 1;

			r = str.substring(pos, p2);
		}
	}
	
	return r;
}

