/*********************************************************************/
/*                                                                   */
/* IBM Confidential                                                  */
/*                                                                   */
/* OCO Source Materials                                              */
/*                                                                   */
/* Copyright IBM Corp. 2005, 2007                                    */
/*                                                                   */
/* 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.                         */
/*                                                                   */
/*********************************************************************/

//-------------------------------------------------------------
// Quickr Versions library
//-------------------------------------------------------------




/****************************************
* This is used to tell Quickr to disable 
* the versioning code.
* Set to false to disable this code
****************************************/
var QPUseDocumentVersioning;

if (typeof(h_VersionType) != "undefined" && h_VersionType == "explicit") {
	QPUseDocumentVersioning = true;
} else {
	QPUseDocumentVersioning = false;
}




dojo.require("dojo.date.common");

var UNID_VERSION             = 0;
var VERSION_UNID             = 1;
var VERSION_FROM_DOC_UNID    = 2;
var VERSION_NUMBER           = 3;
var CREATED                  = 4;
var MODIFIED	             = 5;
var LAST_EDITOR              = 6;
var LAST_EDITOR_DISPLAY_NAME = 7;
var COMMENT                  = 8;
var UNID                     = 9;

function _qp_getVersionColumnValue(node) {
	try {
		return node.childNodes[1].childNodes[0].nodeValue;
	} catch (e) {
		return node.text;
	}
}



Date.prototype.parseDominoDateTime = function (dominoDateString) {

	var comps = dominoDateString.split('T');
	var xDate = comps[0];
	var sYear = xDate.substring(0,4);
	var sMonth = xDate.substring(4,6);
	var sDay = xDate.substring(6,8);
	var sDate = sMonth + '/' + sDay + '/' + sYear;
	var sTime = '';
	var sTimezone = '';
	if(comps.length == 2){
		var compsTime = comps[1].split(',');
		var xTime = compsTime[0];
		var sHour = xTime.substring(0,2);
		var sMinute = xTime.substring(2,4);
		var sSecond = xTime.substring(4,6);
		sTime = ' ' + sHour + ':' + sMinute + ':' + sSecond;
		var xTimeZone = compsTime[1];
		var utcHours = xTimeZone.substring(2,5);
		var utcMinutes = '00';
		if(xTimeZone.length > 5){
			utcMinutes = xTimeZone.substring(5,7);
		}
		sTimezone = ' UTC' + utcHours + utcMinutes;
	}
	return new Date(sDate + sTime + sTimezone);
	
}




function _qp_openVersionList(sId, targetDivId) {

	//if it is disabled, don't show it.
	if (typeof(QPUseDocumentVersioning) == "undefined" || QPUseDocumentVersioning == false) {
		return "";
	}
	
	
	if (typeof(targetDivId) == "undefined") {
		targetDivId = "VersionList";
	}
	
	dojo.require("dojo.date.format");

	dojo.io.bind({
		url: getAbsoluteRoomURL(self) + '/h_Versions/' + sId + '/?ReadViewEntries&Count=100000&StartKey=' + sId,
		method: 'get',
		sync: true,
		load: function(type,data,evt) {
			

			var versionListHTML = '';
			
			var relevantEntries = 0;
			

			var root = data.getElementsByTagName('viewentries')[0];
			
			var entries = root.getElementsByTagName("viewentry");
			
			for (var i=0; i<entries.length; i++) {
				var entrydata = entries[i].getElementsByTagName("entrydata");

				var unid = entries[i].getAttribute('unid');

				var unidVersion = _qp_getVersionColumnValue(entrydata[UNID_VERSION]);
				
				
				if (unidVersion.indexOf(" ") > -1 && unid != h_PageUnid && h_PageUnid == _qp_getVersionColumnValue(entrydata[VERSION_FROM_DOC_UNID])) {

					var versionNumber = parseFloat(_qp_getVersionColumnValue(entrydata[VERSION_NUMBER]));
					
					relevantEntries++;

					var comm = _qp_getVersionColumnValue(entrydata[COMMENT]);
					var dispname = _qp_getVersionColumnValue(entrydata[LAST_EDITOR_DISPLAY_NAME]);	
					
					var sDateTime = _qp_getVersionColumnValue(entrydata[CREATED]);
					
					var xdate = new Date().parseDominoDateTime(sDateTime);
					
					var sDate = dojo.date.format(xdate, {formatLength:"short"});
					
					var sTime = sDate.substring(sDate.indexOf(" ") + 1);
					var sDate = sDate.substring(0, sDate.indexOf(" "));
					


					var newloc = window.location.href;
					newloc = newloc.replace(h_PageUnid, unid);



					versionListHTML += "<div class=\"VersionListEntry\">";
					
					var temp = _qp_getLocalString("S_VersionListRevertAction");
					versionListHTML += "<a class=\"VersionListEntryRevertLink\" href=\"javascript:void _qp_revertVersion('" + unid + "');\">"
					versionListHTML += "<img src=\"/qphtml/skins/quickr8/doc_revert.gif\" border=\"0\" alt=\"" + temp + "\" title=\"" + temp + "\">";
					versionListHTML += "</a>";

					
					temp = _qp_getLocalString("S_VersionListViewAction");
					versionListHTML += "<a title=\"" + temp + "\" class=\"VersionListEntryDocLink\" href=\"" + newloc + "\">";


					versionListHTML += _qp_getLocalString("S_VersionListEntryVersion").replace("{0}", versionNumber);
					
					versionListHTML += "</a>";
					
					
					
					temp = _qp_getLocalString("S_VersionListEntryName");
					temp = temp.replace("{0}", dispname);
					
					//TODO - I18N these date and time formats.
					temp = temp.replace("{1}", sDate);
					temp = temp.replace("{2}", sTime);
					
					versionListHTML += "<span class=\"VersionListEntryName\">" + temp + "</span>";
					versionListHTML += "<span class=\"VersionListEntryComment\">" + comm + "</span>";

					
					
					versionListHTML += "</div>";					
					
					
				}				
				
				
			}			
			
			
			var versionList = document.getElementById(targetDivId);
			if(versionList && relevantEntries > 0) {
				versionList.innerHTML = versionListHTML;
				
				var versionListContainer = document.getElementById("VersionListContainer");
				if (versionListContainer) {
					versionListContainer.style.display="block";
				}
				
			}


		},
		mimetype: 'text/xml'
	});







}





function _qp_createVersion(sId) {


	var frm = document.getElementById("CreateVersionForm");
	if (!frm) {

		frm = document.createElement("form");
		frm.id = "CreateVersionForm";
		frm.method = "POST";
		frm.name="h_CreateVersionForm";

		var html = "";
		html += '<input type="hidden" name="h_EditAction" value="h_Ajax">';
		html += '<input type="hidden" name="h_AllDocs" value="">';
		html += '<input type="hidden" name="h_SetCommand" value="h_CreateVersion">';
		html += '<input type="hidden" name="h_NoSceneTrail" value="1">';
		html += '<input type="hidden" name="h_PublishedUNID" value="1">';
		html += '<input type="hidden" name="h_Comment" value="">';

		frm.innerHTML = html;
		document.body.appendChild(frm);
	}
	
	if (frm) {
		comment = prompt(_qp_getLocalString("S_VersionNewComment"), "");
		if (comment && comment.length > 0) {
			frm.action = getAbsoluteRoomURL(self) + '/h_Toc/' + sId + '/?EditDocument';

			frm.h_PublishedUNID.value = sId;
			frm.h_Comment.value = comment;

			QPAjax_SubmitForm(	"CreateVersionForm", 
						function() {
							alert(_qp_getLocalString("S_VersionCreateSuccess"));
							window.location.href = window.location.href;;
							//_qp_openVersionList(h_PageUnid);
						}, 
						function() {
							alert(_qp_getLocalString("S_VersionCreateError"));
						}
					);	
		}
		
	}

}


function _qp_revertVersion(sId) {


	var frm = document.getElementById("RevertVersionForm");
	if (!frm) {

		frm = document.createElement("form");
		frm.id = "RevertVersionForm";
		frm.method = "POST";
		frm.name="h_RevertVersionForm";

		var html = "";
		html += '<input type="hidden" name="h_EditAction" value="h_Ajax">';
		html += '<input type="hidden" name="h_AllDocs" value="">';
		html += '<input type="hidden" name="h_SetCommand" value="h_RevertVersion">';
		html += '<input type="hidden" name="h_NoSceneTrail" value="1">';
		html += '<input type="hidden" name="h_DraftUNID" value="1">';


		frm.innerHTML = html;
		document.body.appendChild(frm);
	}

	if (frm && confirm(_qp_getLocalString("S_VersionRevertAreYouSure"))) {

		frm.action = getAbsoluteRoomURL(self) + '/h_Toc/' + sId + '/?EditDocument';

		frm.h_DraftUNID.value = sId;

		QPAjax_SubmitForm (	"RevertVersionForm",	
					function() {
						alert(_qp_getLocalString("S_VersionRevertSuccess"));
						window.location.href = window.location.href;
					},
					function() {
						alert(_qp_getLocalString("S_VersionRevertError"));
					}
				);	
	}

}


var _qp_DEFAULT_LANG = "en";
var _qp_locales;

function _qp_getLocalString(localvar) {
	
	if (!_qp_locales) {
		_qp_locales = new Array();
		_qp_locales[_qp_locales.length] = _qp_DEFAULT_LANG;
	}
	
	var str;
	
	for (var ii = 0; ii < _qp_locales.length; ii++) {
		var tmp = localvar + "_" + _qp_locales[ii];
		try {
			str = eval(tmp);
		} catch(e) {}
		if (typeof(str) != "undefined") {
			break;
		}
	}
	
	if (typeof(str) == "undefined") {
		str = eval(localvar + "_" + _qp_DEFAULT_LANG);
	}
	
	if (typeof(str) != "undefined") {
		return str;
	} else {
		return "%%" + localvar + "%%";
	}

}
/*  -- SPR #JHHO775AU3 - Unable to find the locales language list.  remark out for now since it isn't translated for 8.0.0.1.
function _qp_loadLocales() {
	dojo.io.bind({
		url: getAbsoluteRoomURL(self) + "/h_AcceptLanguage?OpenView",
		method: 'get',
		sync: true,
		load: function(type,data,evt) {
			data += ",";
			_qp_locales = new Array();
			
			while (data.indexOf(",") > -1) {
				var tmp = data.substring(0, data.indexOf(","));
				if (tmp.indexOf(";") > -1) {
					tmp = tmp.substring(0, data.indexOf(";"));
				}
				tmp = tmp.replace(/-/ig, "_");

				_qp_locales[_qp_locales.length] = tmp;

				data = data.substring(data.indexOf(",") + 1);
			}
		},
		mimetype: 'text/plain'
	});
}
_qp_loadLocales();
*/





/* Translatable strings */

//List of version documents
var S_VersionList_en = "Version List";

var S_VersionListRevertAction_en = "Revert back to this version";
var S_VersionListViewAction_en = "View this version";

var S_VersionListEntryVersion_en = "Version {0}";
var S_VersionListEntryName_en = "uploaded by {0} on {1} at {2}";





//Create a new version
var S_VersionCreate_en = "Create Version";
var S_VersionNewComment_en = "Please enter in your comments about this new version";
var S_VersionCreateSuccess_en = "A new version has been successfully created.";
var S_VersionCreateError_en = "An error has occured creating a new version";




//Revert back to previous version of document
var S_VersionRevert_en = "Revert Version";
var S_VersionRevertAreYouSure_en = "Are you sure you want to revert back to this version?";
var S_VersionRevertSuccess_en = "This version has been successfully reverted.";
var S_VersionRevertError_en = "An error has occured revert back to this version";



