/*********************************************************************/
/*                                                                   */
/* IBM Confidential                                                  */
/*                                                                   */
/* OCO Source Materials                                              */
/*                                                                   */
/* Copyright IBM Corp. 2005, 2008                                    */
/*                                                                   */
/* The source code for this program is not published or otherwise    */
/* divested of its trade secrets, irrespective of what has been      */
/* deposited with the U.S. Copyright Office.                         */
/*                                                                   */
/*********************************************************************/

// SPR #TEDS6N6RZY: load controls from external script file, to avoid need for user activation (MS workaround for KB912945).
// See http://msdn.microsoft.com/library/default.asp?url=/workshop/author/dhtml/overview/activating_activex.asp
// 04/04/06 Bill Rodrick

function _qp_WriteHtml(theHTML)
{
	document.write(theHTML);
	return true;
}


var qp_ImageProcessText = "";

/****************************************
* Used by the Dojo controls to write
* the new image controls in the popup
* form.
****************************************/
function qp_writeDojoNewImageControls(sProgText) {

	this.qp_ImageProcessText = sProgText;
	
	var uri = dojo.uri.dojoUri("../dojowidgets/widget/templates/newimagecontrols.html");
	qp_writeDojoExternalHtml(uri);
}
function qp_writeDojoExternalHtml(sFile) {

	if (typeof(dojo) != "undefined") {
		dojo.require("dojo.widget.ContentPane");
		document.write("<div dojoType=\"ContentPane\" href=\"" + sFile + "\" executeScripts=\"true\"></div>");
	}
}

function getFiles(){
	var sFiles = '';
	if (h_ClientBrowser.hasActiveX ()) {
		sFiles = theForm.UploadControl.Attachment_Names.toLowerCase();
	}else{
		var oSelect = document.getElementById('SelID');
		var aOption = oSelect.getElementsByTagName("option");
		for (i = 0; i < aOption.length; i++){
			sValue = aOption[i].value.toLowerCase();
			iLS = sValue.lastIndexOf('\\') + 1;
			if(i != 0){
				sFiles += ',';
			}
			sFiles += sValue.substring(iLS,sValue.length);
		}
	}
	return sFiles;
}

function getWidgetId(){
	var sLocation = location.href;
	iWL = sLocation.lastIndexOf('=') + 1;
	return sLocation.substring(iWL,sLocation.length);
}

function checkFields(theForm){
	var isOk = true;
	var alertText = '';
	
	if(theForm.h_Name.value == ''){
		isOk = false;
		alertText += top.MSG_TITLE + '\n';
	}
	
	var sFiles = getFiles();
	if(sFiles.indexOf(',') > -1){
		alertText += top.MSG_ATTACH_ONE_IMAGE_FILE;
		isOk = false;
	}else if(sFiles == '' || (sFiles.indexOf('.gif') == -1 && sFiles.indexOf('.png') == -1 && sFiles.indexOf('.jpg') == -1 && sFiles.indexOf('.jpeg') == -1)){
		alertText += top.MSG_ATTACH_ONE_IMAGE_FILE;
		isOk = false;
	}
		
	if(!isOk){
		alert(top.MSG_COMPLETE_FIELDS + '\n\n' + alertText);
	}else{
		
	}
	return isOk;
}

function QDK_HTMLImageForm_OnSubmitHandlerCallback(theForm){
	return checkFields(theForm);
}

function QDK_HTMLImageForm_OnLoadHandlerCallback(theForm){
	document.getElementById('titleHL').style.display = 'block';
	document.getElementById('attachmentRead').style.display = 'none';
	document.getElementById('attachmentEdit').style.display = 'block';
	document.getElementById('attachmentControlTR').style.display = 'block';
}

function submitImageForm(){
	if(checkFields(theForm)){
		//Set global widget name
		parent.g_CurrentWidget = getWidgetId();
		
		abPreSubmitCalled = true;
		theForm.h_SetEditNextScene.value="";
		var publishOption = new Array ("","","","","");
		var bNeedsPublishLocation = false;
		var bIsNewDoc = (h_IsNewDoc == "1");
		var folderName = theForm.h_CurrentFolderName.value;
		
		var s = 'h_Jump';

		for (var i=0;i<formObj.fieldDef.length;i++) {
			s = formObj.fieldDef[i].submitLogic(self, s, i, publishOption);
			if (s == false) {
				return;
			}
		}
		
		for (var i=0; i<publishOption.length; i++) {
			if (publishOption[i] != ""){
				theForm.h_PublishOptions.value = (theForm.h_PublishOptions.value == "") ? publishOption[i] : theForm.h_PublishOptions.value + ", " + publishOption[i];
			}
		}
		
		theForm.h_NoSceneTrail.value = "0";
			
		setAnimation("h_StdPageAnimation");
		if (putAway.publishFolderName == "" && (h_Form!="0AD3FAE32A9296D10525670800167241" && h_Form!="BD931F9B1EE77301852567D6006AF8B4")) {
			publishToCurrentFolder();
		}
		
		putAway.publishAction = "h_Publish";
		s = "h_Next";
		
		theForm.h_EditAction.value = s;
		CommonFormPreSubmit( theForm);
		
		
		//hide the main frame
		var divMain = parent.dojo.byId("qp_newimage_mainpage");
		divMain.style.visibility = "hidden";
		
		//show the progress bar
		var divProg = parent.dojo.byId("qp_newimage_progress");
		divProg.innerHTML = this.qp_ImageProcessText;
		divProg.style.display = "block";
		
		
		setTimeout("theForm.submit();",200);
		

	
		return;
	}
}

function cancelImageForm(){
	abPreSubmitCalled = true;
	theForm.h_SetEditNextScene.value="";
	var publishOption = new Array ("","","","","");
	var bNeedsPublishLocation = false;
	var folderName = theForm.h_CurrentFolderName.value;
	
	theForm.h_SetPublishAction.value = "h_Discard";
	s = "h_Next";
	theForm.h_SetReturnURL.value = '<script type="text/javascript">location.href="' + "../../"+(h_Context_InFolder==1 && h_Context_InFolderProxyDocUnid==h_ReturnToPage?'h_Toc':(h_Context_InFolder==1?h_Context_InFolderName:'h_Toc'))+"/"+h_ReturnToPage+"/?OpenDocument&Form=h_PrintUI" + "" + '";<\/script>';
	
	theForm.h_EditAction.value = s;
	CommonFormPreSubmit( theForm);
	theForm.submit();
	parent.dojo.widget.byId('NewImage').hide();
	
	return;
}

function qp_adjustRTEText(sText) {
	/* Code automatically adds the default font face so that it shows properly in the font name
	* selection list */
	
	if ( h_ClientBrowser.isIE() ) {
		return sText;
		
	} else {
		var sFontPad = "<font face=\"Times New Roman\" size=\"3\">&nbsp;</font>";

		sRet = sText;

		if (sText == "") {
			sRet = sFontPad;
		}

		return sRet;
	}
	
}

function qp_adjustRTESelection(rte) {
	/* Manually check if the height is less than minHeight in ie since it does't truely support minheight
	* Also another fix for IE so you click to focus the rte anywhere in the editor (not just the first line of content
	* From here: http://dojotoolkit.org/pipermail/dojo-contributors/2007-February/006367.html
	*/
	if ( typeof(rte) != "undefined" ) {
		if ( dojo.render.html.ie60 || dojo.render.html.ie70 ) {
			var getLengthInPixels = function(element, value) {
				if (/px$/.test(value)) return parseInt(value);
				var sLeft = element.style.left;
				var rsLeft = element.runtimeStyle.left;
				element.runtimeStyle.left = element.currentStyle.left;
				element.style.left = value || 0;
				value = element.style.pixelLeft;
				element.style.left = sLeft;
				element.runtimeStyle.left = rsLeft;
				return value;
			};

			var minHeightInPx = getLengthInPixels( rte.domNode , rte.minHeight );

			var newHeight = (rte._lastHeight > minHeightInPx)?rte._lastHeight+"px":rte.minHeight;
			rte.editorObject.style.height = newHeight;
			var divWrapper = rte.document.body.getElementsByTagName('div')[0]; //dojo only puts the div rte content wrapper in IE
			divWrapper.style.height = newHeight;

			//let's change the replaceEditorContent function.  It's having some trouble.. --> SPR #RELS76JQG5.
			rte.replaceEditorContent =	function(html) {
								if(this._inSourceMode){
									this._htmlEditNode.value = html;
									return;
								}
							};
		} else {
		
			//let's change the toggleHtmlEditing function.  It's having some trouble with height.. --> SPR #JHHO79PDTW
			rte.toggleHtmlEditing =		function() {
								// summary: toggle between WYSIWYG mode and HTML source mode
								if(this===dojo.widget.Editor2Manager.getCurrentInstance()){
									if(!this._inSourceMode){
										var html = this.getEditorContent();
										this._inSourceMode = true;

										if(!this._htmlEditNode){
											this._htmlEditNode = dojo.doc().createElement("textarea");
											dojo.html.insertAfter(this._htmlEditNode, this.editorObject);
										}

										this._htmlEditNode.style.display = "";
										this._htmlEditNode.style.width = "100% ! important";
										this._htmlEditNode.style.height = "300px";
										this._htmlEditNode.value = html;

										//activeX object (IE) doesn't like to be hidden, so move it outside of screen instead
										with(this.editorObject.style){
											position = "absolute";
											left = "-2000px";
											top = "-2000px";
										}
									}else{
										this._inSourceMode = false;

										//In IE activeX mode, if _htmlEditNode is focused,
										//when toggling, an error would occur, so unfocus it
										this._htmlEditNode.blur();

										with(this.editorObject.style){
											position = "";
											left = "";
											top = "";
										}
										var html = this._htmlEditNode.value;

										dojo.lang.setTimeout(this, "replaceEditorContent", 1, html);
										this._htmlEditNode.style.display = "none";
										this.focus();
									}
									this.onDisplayChanged(null, true);
								}
							};
			}
	}
	
		
	//hide the spellcheck icon if we're offline --> SPR #DDZG777AS8
	if (drF_isOffline()) {
		dojo.addOnLoad(function(){
			var interval;
			if (dojo.render.html.ie60 || dojo.render.html.ie70) {
				interval = 1;
			} else {
				interval = 500;
			}

			setTimeout("qp_hideSpellCheckIcon()", interval);	

		});
	}


}

function qp_hideSpellCheckIcon() {
	//loop through the images and hide the spellcheck icons if we're offline --> SPR #DDZG777AS8
	for (var i = document.images.length - 1; i >= 0; i--) {
		var img = document.images[i];

		if (img.src.indexOf("spellcheck.gif") > -1) {

			//hide the containing table
			var pnode = img;
			while (pnode && pnode.tagName.toLowerCase() != "table") {
				pnode = pnode.parentNode;
			}

			if (pnode.tagName.toLowerCase() == "table") {
				pnode.style.display = "none";
			}

		}
	}
}



function qp_useDojoEditor() {
	/* Used for the Wikis and Blogs to flag whether to use a textarea or the dojo rt editor */	
	return (!usesAccessibleTheme_ClientBrowserObject() && (h_ClientBrowser.isIE() || h_ClientBrowser.isGecko()));
	
}




/*************************************************
* Code to correct the actions menu for the wikis
*************************************************/
var CONST_WIKIPAGE = '8E5E3E1C13061E71062572A4005896ED';

dojo.addOnLoad(function(){
	
	if (typeof(h_FavoredForm) != "undefined" && h_FavoredForm != null && h_FavoredForm == CONST_WIKIPAGE) {
		//it's a wiki page, need to massage the actions
		try{
			var sHREF = "";
			var oParent;
			var aElements = document.getElementsByTagName("a");
			for (var i=0; i < aElements.length; i++){
				sHREF = aElements[i].getAttribute("href");

				if (sHREF != null) {
					// Remove Delete item from menu
					if(sHREF.indexOf(":abPreSubmit('h_Discard')") > -1 ||
						sHREF.indexOf("FM.view.removeChecked") > -1) {
						aElements[i].parentNode.removeChild(aElements[i]);
					}
				}
			}
		}catch(e){}		
	
	}
	
});






/***********************************
* Code to put in a scroller for the 
* ToC if it is too long
***********************************/
function qp_getElementsByClassName(className, tag, elm){
	var testClass = new RegExp("(^|\\s)" + className + "(\\s|$)");
	var tag = tag || "*";
	var elm = elm || document;
	var elements = (tag == "*" && elm.all)? elm.all : elm.getElementsByTagName(tag);
	var returnElements = [];
	var current;
	var length = elements.length;
	for(var i=0; i<length; i++){
		current = elements[i];
		if(testClass.test(current.className)){
			returnElements.push(current);
		}
	}
	return returnElements;
}

function qp_adjustTocWidth() {

	var alltags = qp_getElementsByClassName("qpg_tocBackground");
	
	for (var i = 0; i < alltags.length; i++) {
		var node = alltags[i];
		
		var nodewidth = 0;
		var windowwidth = document.body.clientWidth;
		
		windowwidth = windowwidth *.90;
		
		if (h_ClientBrowser && h_ClientBrowser.isIE()) {
			nodewidth = node.offsetWidth;
		}

		if (nodewidth == 0) {
			nodewidth = 800;
		}
	
	
		var isNewTag = false;

		var divtag = node.parentNode;
		if (divtag.nodeName.toLowerCase() != "div") {
			divtag = document.createElement("div");
			divtag.id = "qp_TocSlider";
			isNewTag = true;
		}

		if (nodewidth > windowwidth) {

			divtag.style.overflowX = "scroll";
			divtag.style.overflowY = "auto";
			divtag.style.width = windowwidth + "px";
			
			if (isNewTag) {
				var subtag = node.cloneNode(true);
				divtag.appendChild(subtag);		
				node.parentNode.insertBefore(divtag, node);
				node.parentNode.removeChild(node);
			}
			
		} else if (!isNewTag) {
			divtag.style.overflowX = "auto";
			divtag.style.overflowY = "auto";
			divtag.style.width = "100%";
		
		}
	}	
}


function qp_setOnResize() {

	var qp_prev_resize = window.onresize;
	if (typeof(qp_prev_resize) == "function") {
		window.onresize = function() {
			qp_prev_resize();
			qp_adjustTocWidth();
		}
	} else {
		window.onresize = qp_adjustTocWidth;
	}

}


//qp_setOnResize();
//setTimeout("qp_adjustTocWidth();", 2000);





/****************************************
* This is used to tell Quickr to always 
* use the legacy rich text editor.
* 
* When set to false (default): The Dojo
* editor will show for IE and Firefox
*
* When set to true: The legacy 
* proprietary editors will show.
*
* NOTE - For IE7, setting this to true
* will result in a simple textarea since 
* IE7 no longer supports the DHTML 
* controls.
****************************************/
var QPUseLegacyRichTextEditor = false;









/********************************************
* Code to add Javlin cards to member names
* in Quickr.
*
* pre-alpha code - lots of hacks!!!
********************************************/

//supporting functions
function getElementsByClassName(className, tag, elm){
	var testClass = new RegExp("(^|\\s)" + className + "(\\s|$)");
	var tag = tag || "*";
	var elm = elm || document;
	var elements = (tag == "*" && elm.all)? elm.all : elm.getElementsByTagName(tag);
	var returnElements = [];
	var current;
	var length = elements.length;
	for(var i=0; i<length; i++){
		current = elements[i];
		if(testClass.test(current.className)){
			returnElements.push(current);
		}
	}
	return returnElements;
}
//map object for pseudo-cache
function KeyValue( key, value ) {
	this.key = key;
	this.value = value;
}
function Map() {
	this.array = new Array();
}
Map.prototype.put = function( key, value ) {
	if( ( typeof key != "undefined" ) && ( typeof value != "undefined" ) ) {
		var found = false;
		for( var k = 0 ; k < this.array.length ; k++ ) {
		    if( this.array[k].key == key ) {
			this.array[k].value = value;
			found = true;
			break;
		    }
		}
		if (!found) {
			this.array[this.array.length] = new KeyValue( key, value );
		}
	}
}
Map.prototype.get = function( key ) {
	for( var k = 0 ; k < this.array.length ; k++ ) {
		if( this.array[k].key == key ) {
			return this.array[k].value;
		}
	}
	return null;
}
Map.prototype.length = function() {
	return this.array.length;
}

//cache to store already downloaded names
var mapJavlin = new Map();

function qp_makeJavlinName(cn,dn,url,mail,bMenu)
{
	bCM = (typeof(bMenu)=="undefined" ? true : bMenu);
	var html='<span class="vcard" title="'+dn+'">';
	html += (url ? '<a class="fn" href="'+url+'">'+cn+'</a>' : cn);
	if (bCM) {
		html += '<img class="h-contextMenu-icon" width="16" height="16" src="/qphtml/html/common/clear_pixel.gif"/>';
	}
	html += '<span class="email" style="display: none;">'+mail+'</span></span>';
	return html;
}

// Find default member HTML on page, request data to get email addresses as necessary
function qp_setJavelinNames(elm) {
	
	var elm = elm || document;
	
	var baseurl = window.location.href + "&";
	baseurl = baseurl.substring(0, baseurl.indexOf("&"));
	
	//we need to get all of the person tags	
	var alltags = getElementsByClassName("h-user-anchor", "*", elm);
	
	for (var i = alltags.length - 1; i >= 0; i--) {
		var node = alltags[i];
		
		var atag = node.getElementsByTagName("A")[0];
		if (atag != null)
		{
			atag.className += " fn";
		
			var span = document.createElement("span");
			span.className = "email";
			span.style.display = "none";
		
			var key = atag.href;
			if (key.indexOf("&") > -1) {
				key = key.substring(key.indexOf("&"));		
			}
			var suffixurl = key;
		
			if (key.indexOf(";") > -1) {
				key = key.substring(key.lastIndexOf(";")+1);		
			}
			key = unescape(key);
		
			var result = mapJavlin.get(key);
			
			if (result == null) {
				try {
					dojo.io.bind (
						{
							url:		atag.href + "&Form=h_MemberXml&nowebcaching",
							method: 	"get",
							mimetype:	"text/xml",
							load:		function (type, data, evt) {
										qp_processJavlinRequest(data, span, key, node, true);
									},
							transport:	"XMLHTTPTransport",
							sync:		true
						}
					);
				}
				catch(e) {
					this.Error(e);
				}
			
			} else {
		
				qp_processJavlinRequest(result, span, key, node, false)
			
			}
		}
		
	}
	
	if (alltags.length > 0) {
		qp_loadJavelinJs();
	}
}

function qp_processJavlinRequest(data, span, key, node, forceStore) {
	// got member data - store email addr and modify member HTML on page
	if (forceStore) {
		mapJavlin.put(key, data);
	}
	
	var email = getTagValue(data, "qp_member", "email");
	
	//only update the link if we found an email address
	if (email != "") {
		span.innerHTML = email;
		node.className = "vcard";
		node.appendChild(span);
	}
}

var qp_javlinloop = 0;

var c_PROFILESERVER = "";
var c_SEMATICTAGSERVICELOCATION = "";
var c_JAVLINTAGLOCATION = "";

var defSTSvcLoc = "/profiles/ibm_semanticTagServlet/javascript/semanticTagService.js";
var defJTLoc = "/profiles/html/personTag?template=personTag.jsp";

/* enable/disable the javlin cards for people in Quickr Domino */
var QPEnableJavlinTags = false;

function qp_loadProfileLocations() {

	window.c_PROFILESERVER = (G_ProfileServer=="" ? "" : "http://"+G_ProfileServer);
	if (window.c_PROFILESERVER != "")
		QPEnableJavlinTags = true;

	var semanticTagServiceLocation = (G_SemanticTagServiceLoc=="" ? defSTSvcLoc : G_SemanticTagServiceLoc);
	var javelinTagLocation = (G_JavelinTagLoc=="" ? defJTLoc : G_JavelinTagLoc);

	window.c_SEMATICTAGSERVICELOCATION = window.c_PROFILESERVER + semanticTagServiceLocation;
	window.c_JAVLINTAGLOCATION = window.c_PROFILESERVER + javelinTagLocation;
}


function qp_loadJavelinJs() {

	if (c_PROFILESERVER == "") {
		qp_loadProfileLocations();
	}

	var headtag = document.getElementsByTagName("HEAD")[0];
	var scripttag;
	
	if (typeof(SemTagSvc) == "undefined") {
		if (qp_javlinloop == 0) {
			scripttag = document.createElement("script");
			scripttag.setAttribute("type", "text/javascript");
			scripttag.setAttribute("src", c_SEMATICTAGSERVICELOCATION);
			headtag.appendChild(scripttag);
		}
		
		//too many loops, it isn't loaded in 5 seconds.  just abort it.
		if (qp_javlinloop <= 25) setTimeout("qp_loadJavelinJs()",200);
	
	} else {
		SemTagSvc.init();
		
		scripttag = document.createElement("script");
		scripttag.setAttribute("type", "text/javascript");
		scripttag.setAttribute("src", c_JAVLINTAGLOCATION);
		headtag.appendChild(scripttag);
	}
	qp_javlinloop++;
}



/******************************************
 *
 * Person menu functions to override those
 * in qp_context_menu.js
 * 
 * FOR PROTOTYPE ONLY!!!
 *
 *****************************************/
function QP_PersonMenu_javlin(szDN, szCN)
{ 
	var fixedName = QP_ContextMenu_fixName(szDN);
	// Inherit from QP_ContextMenu
	this.base				= QP_ContextMenu;
	this.base(fixedName);
}



/******************************************
 *
 * If this flag is set, it will override
 * the functions and start pulling data
 * 
 *****************************************/
if (G_ProfileServer != "") {
	QP_PersonMenu.prototype = new QP_ContextMenu;
	QP_PersonMenu = QP_PersonMenu_javlin;
	dojo.addOnLoad(function(){
		setTimeout("qp_setJavelinNames();",750);
	});
	
}


dojo.addOnLoad(function(){
	if (h_CurrentSkinName == 'h_R8GenevaSkin' && h_CurrentSkinType == 'h_Edit') {
		var el = document.getElementById("workspace");
		if (el) el.style.width = "900px";
	}
});