/*********************************************************************/
/*                                                                   */
/* 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.                         */
/*                                                                   */
/*********************************************************************/

//-------------------------------------------------------------
// 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" || h_VersionType == "implicit")) {
	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.requireLocalization("qdojo.i18n.calendar", "gregorian");
	dojo.date.addCustomFormats("qdojo.i18n.calendar","gregorian");

	var now = new Date();

	dojo.io.bind({
		url: getAbsoluteRoomURL(self) + '/h_Versions/' + sId + '/?ReadViewEntries&Count=100000&StartKey=' + sId + '&timestamp=' + now.getTime() + '&charset=utf-8',
		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");
			var lastMainUNID;
			
			for (var i=0; i<entries.length; i++) {
				var entrydata = entries[i].getElementsByTagName("entrydata");
				var unid = entries[i].getAttribute('unid');
				if(entrydata.length == 1) {
					//This is a replication conflict - ignore
					continue;
				}

				var unidVersion = _qp_getVersionColumnValue(entrydata[UNID_VERSION]);
				if(unidVersion.indexOf("G") == -1) {
					lastMainUNID = _qp_getVersionColumnValue(entrydata[VERSION_UNID]);
				}

				if (unidVersion.indexOf("G") > -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]);
					if(typeof(comm) == 'undefined') {
						comm = '';
					}
					comm = comm.replace(/Restored from Version/, QuickrLocaleUtil.getStringResource("VERSION.S_VersionRestoredFrom"));
					
					var dispname = _qp_getVersionColumnValue(entrydata[LAST_EDITOR_DISPLAY_NAME]);	
					var sDateTime = _qp_getVersionColumnValue(entrydata[MODIFIED]);
					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 = QuickrLocaleUtil.getStringResource("VERSION.S_VersionListRevertAction");
					var tempCurrent = QuickrLocaleUtil.getStringResource("VERSION.S_VersionListCurrent");

					if(lastMainUNID == unid) {
						versionListHTML += "<a class=\"VersionListEntryRevertLink\" href=\"javascript:void();\">";
						versionListHTML += "<img src=\"/qphtml/skins/quickr8/doc_current.gif\" border=\"0\" alt=\"" + tempCurrent + "\" title=\"" + tempCurrent + "\">";
						versionListHTML += "</a>";
					}
					else if(mbIsPublishedWithDraftPage) {  // MAYETIC FIX AL 09/2010
						versionListHTML += "<a class=\"VersionListEntryRevertLink\" href=\"javascript:void();\">"
						versionListHTML += "<img src=\"/qphtml/skins/quickr8/doc_revert.gif\" border=\"0\" alt=\"" + "Le document est en cours de modification. Il n'est pas possible de restaurer une version." + "\" title=\"" + "Le document est en cours de modification. Il n'est pas possible de restaurer une version." + "\">";
						versionListHTML += "</a>";	
					}  // END MAYETIC FIX AL 09/2010
					else {
						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 = QuickrLocaleUtil.getStringResource("VERSION.S_VersionListViewAction");
					versionListHTML += "<a title=\"" + temp + "\" class=\"VersionListEntryDocLink\" href=\"" + newloc + "\">";
					versionListHTML += QuickrLocaleUtil.getStringResource("VERSION.S_VersionListEntryVersion").replace("{0}", versionNumber);
					versionListHTML += "</a>";

					temp = QuickrLocaleUtil.getStringResource("VERSION.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) {

	if(sId == "activeversion") {
		alert(QuickrLocaleUtil.getStringResource("VERSION.ACTIVEVERSION"));
		return;
	}

	var frm = document.getElementById("CreateVersionForm");
	if (!frm) {
		frm = document.createElement("form");
		frm.id = "CreateVersionForm";
		frm.method = "POST";
		frm.name="h_CreateVersionForm";
		
		frm.encoding="text/plain";

		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(QuickrLocaleUtil.getStringResource("VERSION.S_VersionNewComment"), "");
		if (comment && comment.length > 0) {
			frm.action = getAbsoluteRoomURL(self) + '/h_Toc/' + sId + '/?EditDocument&charset=utf-8';
			frm.h_PublishedUNID.value = sId;
			frm.h_Comment.value = comment;
			QPAjax_SubmitForm(	"CreateVersionForm", 
				function() {
					alert(QuickrLocaleUtil.getStringResource("VERSION.S_VersionCreateSuccess"));
					window.location.href = window.location.href;;
					//_qp_openVersionList(h_PageUnid);
				}, 
				function() {
					alert(QuickrLocaleUtil.getStringResource("VERSION.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(QuickrLocaleUtil.getStringResource("VERSION.S_VersionRevertAreYouSure"))) {
		frm.action = getAbsoluteRoomURL(self) + '/h_Toc/' + sId + '/?OpenDocument';
		frm.h_DraftUNID.value = sId;
		QPAjax_SubmitForm (	"RevertVersionForm",	
					function() {
						alert(QuickrLocaleUtil.getStringResource("VERSION.S_VersionRevertSuccess"));
						window.location.href = window.location.href;
					},
					function() {
						alert(QuickrLocaleUtil.getStringResource("VERSION.S_VersionRevertError"));
					}
				);	
	}
}

