/*
 * iKnowBase Content Services - Generic javascripts
 * Copyright 1999-2010, e-vita as.
 */

/*
 * The global iKnowBase-object
 */

iKnowBase = {
	Version: '5.8',
	locations: {
		ikbViewer: "/ikbViewer",
		resource: "/ressurs"
	},
	ensures: {
		facebox: { js: "/ressurs/iknowbase/libs/jquery-plugins/facebox/facebox.js",
			   css: "/ressurs/iknowbase/libs/jquery-plugins/facebox/facebox.css" },
		ikbPopup: { js: [ "/ressurs/iknowbase/libs/jquery-plugins/ikbPopup/ikbPopup.js",
				  "/ressurs/iknowbase/content-services/common-popup/IKBPopup.js",
				  "/ressurs/iknowbase/libs/jquery-plugins/jquery.bgiframe.js" ],
			   css: "/ressurs/iknowbase/libs/jquery-plugins/ikbPopup/ikbPopup.css" },
		ext3: { js: [ "/ressurs/iknowbase/libs/ext3/ext-base.js",
				  "/ressurs/iknowbase/libs/ext3/ext-all.js" ],
			   css: "/ressurs/iknowbase/libs/ext3/resources/css/ext-ikb.css" },
		form: { js: "/ressurs/iknowbase/libs/jquery-plugins/jquery.form.js" }
	},
	config: {
		ikbLanguage: "us",
		locale: "en",
		href: (function() {
			var parts = /([^?#]*)(#[^?]*)?(.*)/.exec(window.location.href);
			return parts[1] + (parts[3] || "");
		})()
	}
}

iKnowBase.init = function(config) {
	jQuery.extend(iKnowBase.config, config);
}

iKnowBase.setLanguage = function(ikbLanguage, locale) {
	iKnowBase.ikbLanguage = ikbLanguage || iKnowBase.ikbLanguage;
	iKnowBase.locale = locale || iKnowBase.locale;
}

iKnowBase.setLocale = function(locale) {
	iKnowBase.locale = locale;
}

iKnowBase.errorPopup = function(message) {
	jQuery("<div class='ikbErrorPopup' onclick='jQuery(this).slideUp();' />").hide().append(message).prependTo("body").slideDown();
	iKnowBase.log (message);
}

iKnowBase.log = function() {
	var args = Array.prototype.slice.call(arguments);
	if (window.console && console.log) console.log (args);
	else if (window.opera && opera.postError) opera.postError(args);
}

iKnowBase.nvl = function(value, alternate)
{
	if (value != null)
		return value;
	else
		return alternate;
}

iKnowBase.assert = function(bool, message)
{
	if (! bool)
		iKnowBase.errorPopup ('iKnowBase.assert', message);
}

iKnowBase.setCookie = function (name, value, expires, path, domain, secure)
{
    document.cookie= name + "=" + escape(value) +
        ((expires) ? "; expires=" + expires.toGMTString() : "") +
        ((path) ? "; path=" + path : "") +
        ((domain) ? "; domain=" + domain : "") +
        ((secure) ? "; secure" : "");
}

iKnowBase.getCookie = function (name) {
    var dc = document.cookie;
    var prefix = name + "=";
    var begin = dc.indexOf("; " + prefix);
    if (begin == -1)
    {
        begin = dc.indexOf(prefix);
        if (begin != 0) return null;
    }
    else
    {
        begin += 2;
    }
    var end = document.cookie.indexOf(";", begin);
    if (end == -1)
    {
        end = dc.length;
    }
    return unescape(dc.substring(begin + prefix.length, end));
}

iKnowBase.deleteCookie = function (name, path, domain) {
    if (getCookie(name))
    {
        document.cookie = name + "=" + 
            ((path) ? "; path=" + path : "") +
            ((domain) ? "; domain=" + domain : "") +
            "; expires=Thu, 01-Jan-70 00:00:01 GMT";
    }
}

iKnowBase.toggleClassForClass = function (forClass, toggleClass) {
    var elements = document.getElementsByClassName(forClass);
    for (i=0 ; i<elements.length ; i++)
    {
        this.toggleClassForElement('toggle', elements[i], toggleClass);
    }
}

iKnowBase.toggleClassForElement = function (action,o,c1,c2) {
    switch (action) {
        case 'toggle':	
            return this.toggleClassForElement('check',o,c1) 
                 ? this.toggleClassForElement('remove',o,c1) 
                 : this.toggleClassForElement('add',o,c1);
        case 'swap':
            o.className = !this.toggleClassForElement('check',o,c1)
                        ? o.className.replace(c2,c1)
                        : o.className.replace(c1,c2);
            break;
        case 'add':
            if(!this.toggleClassForElement('check',o,c1)){o.className+=o.className?' '+c1:c1;}
            break;
        case 'remove':
            var rep=o.className.match(' '+c1)?' '+c1:c1;
            o.className=o.className.replace(rep,'');
            break;
        case 'check':
            return new RegExp('\\b'+c1+'\\b').test(o.className);
    }

    return o.className != null ? o.className : "";
}

iKnowBase.withFacebox = function(callback) {
	iKnowBase.ensure ( iKnowBase.ensures.facebox, callback);
}

iKnowBase.withIkbPopup = function(callback) {
	iKnowBase.ensure ( iKnowBase.ensures.ikbPopup, callback);
}

iKnowBase.withForm = function(callback) {
	iKnowBase.ensure ( iKnowBase.ensures.form, callback);
}

iKnowBase.withExt3 = function(callback) {
	iKnowBase.ensure ( iKnowBase.ensures.ext3, callback);
}

/*
 * Function used to open iKnowBase targets. Used in onclick-commands 
 */

function ikbPopup(self,target,params) { 
   var url = (typeof self === "string" ? self : self.href);
   window.open(url, target, params).focus(); 
   return false; 
}


/*
 * The global iKnowBaseDevelopment-object
 */

iKnowBaseDevelopment = {
	Version: '5.8'
}

iKnowBaseDevelopment.showPortletCacheStatus = function (name, millis) {
	var cookieName = "ikb.showPortletCacheStatus." + name;
	var cookie = iKnowBase.getCookie(cookieName);

	if (cookie == null)
	{
		style  = "ikbPortletCacheUnknown";
		status = "unknown status";
	}
	else if (cookie == millis)
	{
		style  = "ikbPortletCacheCached";
		status = "from cache";
	}
	else
	{
		style  = "ikbPortletCacheNotCached";
		status = "not from cache";
	}
	
	document.write ("<div class='" + style + "'>");
	document.write ("<!-- ");
	document.write ("name=" + cookieName);
	document.write ("; renderTime=" + millis);
	document.write ("; cookieTime=" + cookie);
        document.write (" -->");
	document.write ("Cache");
	document.write (": delta=" + (millis-cookie));
	document.write ("; " + status);
	document.writeln ("</div>");
	
    iKnowBase.setCookie (cookieName, millis);
}

jQuery(function() {
	jQuery(".ikbComponentInformation .ikbHeader").bind("click", function() {
		jQuery(this).next().toggle();
	});
});

/*
 * Ensures that one or more scripts and/or CSS-files are loaded
 */

(function(IKB,$) {

	// Set up the jQuery-function
	IKB.ensure = function( data, callback)
	{
        load( $.makeArray(data.js), $.makeArray(data.css), callback);
	}

    // List of URLs loaded through ensure
    var loadedUrls = []

	function load(scriptList, cssList, callback) {
		var scriptsToLoad = 0;

		// Start loading scripts
		$.each(scriptList, function() {
			var url = this;
			if (isUrlLoaded(url) || isTagLoaded('script', 'src', url) ) {
				IKB.log ('Already loaded: ' + url);
			} else {
				IKB.log ('Requesting script: ' + url);
				++scriptsToLoad;
				$.ajax({
					type: "GET",
					async: false, // Added to give sync loading
					url: url,
					success: function() {
						// IKB.log ("getScript() success: " + url);
						registerUrl(url);
					},
					error: function() {
						IKB.errorPopup ("getScript() failed: " + url);
					},
					complete: function() {
						IKB.log ("getScript() complete: " + url);
						scriptsToLoad--;
					},
                    dataType: "script",
					cache: true,
					timeout: 12000
				});
			}
		});

		// Start loading CSS
		$.each(cssList, function() {
			var url = "" + this;    	// "this" may not be a string -- stringify!
			if (isUrlLoaded(url) || isTagLoaded('link', 'href', url)) {
				IKB.log ('Already loaded: ' + url);
			} else {            
				IKB.log ('Requesting CSS: ' + url);
				var link = document.createElement('link');
				link.setAttribute("href", url);
				link.setAttribute("rel", "stylesheet");
				link.setAttribute("type", "text/css");
				var head = document.getElementsByTagName("head")[0] || document.documentElement;
				head.appendChild(link);
				registerUrl(url);
			}
		});

		// wait for scripts
		var i=0;
		var waitForScripts = function () {
		    if (scriptsToLoad <= 0) {
			return (callback && callback());
		    }
		    else {
			IKB.log ("waitForScripts: scriptsToLoad=" + scriptsToLoad + "; i=" + (++i) + "; waiting for 50msec");
			window.setTimeout(waitForScripts, 50);
		    }
		}

		waitForScripts();
	}

	function isTagLoaded (tagName, attName, value)
	{
		var sel = tagName + "[" + attName + "=" + value + "]";
		count= $(sel).length;
		// IKB.log ("isTagLoaded: result=" + (count > 0) + "; selector=" + sel);
		return count > 0;
	}

	function isUrlLoaded (url) {
		// IKB.log ("isUrlLoaded: result=" + (loadedUrls[url] === true) + "; url=" + url);
		return loadedUrls[url] === true;
	}

	function registerUrl (url) {
		// IKB.log ("Registering url: " + url);
		loadedUrls[url] = true;
	}

})(iKnowBase, jQuery);
/*
 * iKnowBase Content Services - Content Viewer javascripts
 * Copyright 1999-2006, e-vita as.
 */


/*
 * Create/initialize the main ContentViewer-object
 */

(function(IKB) {

    // The main iKnowBase ContentViewer object
    IKB.ContentViewer = {}

    // Local functions
    function getUrl(portlet, ctl, data) {
		if (portlet) {
			data = jQuery.extend({
				_rtarget: portlet,
				_ikbController: ctl,
				portlet: portlet
			}, data || {});
		}

		var url = (portlet
		   ? location.href.match(/[^\?]*/)[0]
		   : IKB.locations.ikbViewer + ctl);

		if (data != null && data != 'undefined') {
			url = url + "?" + jQuery.param(data);
		}

		return url;
    }

    function popup (portlet, controller, params) {
        portlet = null;
		var url = getUrl (portlet, controller, params);
		IKB.log ("Request: " + url);
		IKB.withIkbPopup(function() {
			jQuery.ikbPopup( { post: url });
		});
		return false;
    }

    function reloadComponent (id,url) {
    	var comp = jQuery('#' + id);
    	var loading = jQuery("<div class='ikbContentViewerLoading'></div>").prependTo(comp);
    	comp.load (url, {
    		ikbRender: id
    	}, function (response, status) {
    		if (status != "success") {
    			// TODO: Enable errorPopup to be component-specific
    			loading.remove();
    			IKB.errorPopup ('refreshComponent error: id=' + id + '; status=' + status);
    		}
    	});
    	return false;
    }

	function clickAction (id,link,event) {
		// If there is an event, do nothing when modifier keys are clicked. This
		// is to enable "ctrl+click" for "open in new tab", etc.
		iKnowBase.log("clickAction", arguments);
		if (event && (event.altKey || event.ctrlKey || event.shiftKey))
			return true;

		return iKnowBase.PageEngine.reloadComponent(id, link.href);
	}
	
    function navigatePage(clientName,operation,arg) {
        //TODO: var viewer = jQuery(clientName); if (viewer) { ajax } else { post }
		var form = jQuery("<form method='post'>");
		form.append("<input type='hidden' name='ikbAction' value='" + clientName + "' />");
		form.append("<input type='hidden' name='" + clientName + ".operation' value='" + operation + "' />");
		form.append("<input type='hidden' name='" + clientName + ".arg' value='" + arg + "' />");
		form.appendTo("body").submit();
		return false;
    }

    function navigatePortal(clientName,operation,arg) {
		var form = jQuery("<form method='post'>");
		form.append("<input type='hidden' name='" + clientName + ".operation' value='" + operation + "' />");
		if (operation=="startrow" || operation=="sortinfo")
			form.append("<input type='hidden' name='" + clientName + ".arg' value='" + arg + "' />");
		else if (operation=="checkin" || operation=="checkout")
			form.append("<input type='hidden' name='" + clientName + ".document_id' value='" + arg + "' />");
		form.appendTo("body").submit();
		return false;
    }

    // Public functions
    jQuery.extend(IKB.ContentViewer, {

		// Refers to local functions
		getUrl: getUrl,
		navigatePage: navigatePage,
		navigatePortal: navigatePortal,
		reloadComponent: reloadComponent,
		clickAction: clickAction,

		deleteDocument: function(docID, version, portlet) {
			return popup (portlet, '/private/document/delete/request', {
				docid: docID,
				version: (version || 0)
			});
		},

		deleteDocumentConfirm: function(docID, version, mode, portlet) {
			return popup (portlet, '/private/document/delete/confirm', {
				docid: docID,
				version: (version || 0),
				mode: mode
			});
		},

		changeDocumentType: function(docid, quickLinkGuid, portlet) {
			return popup (portlet, '/private/document/changeDocumentType/request', {
				docid: docid,
				quickLinkGuid: quickLinkGuid
			});
		},

		changeDocumentTypeConfirm: function(docid, formGuid, portlet) {
			return popup (portlet, '/private/document/changeDocumentType/confirm', {
				docid: docid,
				formGuid: formGuid
			});
		},

		copyDocument: function(docid, quickLinkGuid, portlet) {
			return popup (portlet, '/private/document/copy/request', {
				docid: docid,
				quickLinkGuid: quickLinkGuid
			});
		},

		copyDocumentConfirm: function(docid, formGuid, portlet) {
			return popup (portlet, '/private/document/copy/confirm', {
				docid: docid,
				formGuid: formGuid
			});
		},
			
		selectPersonalAcl: function (portlet, cbFunction, cbClosure) {
			return popup (portlet, '/private/personalAcl/popup', {
				cbFunction: cbFunction,
				cbClosure: cbClosure
			});
		},
			
		editPersonalAcl: function (acl) {
			return popup (null, '/private/personalAcl/popup', {
				acl: acl
			});
		},
			
		set_new_version: function (docid, version, site_id) {
			var run_url = "/ikbViewer/pls/ikb_ce_custom_editor_portlet.switch_version?p_document_id="+ encodeURIComponent(docid)+ "&p_site_id="+ encodeURIComponent(site_id)+ "&p_version_no="+ encodeURIComponent(version);
			var code = jQuery.ajax({
				url: run_url,
				async: false
			}).responseText;

			if (code != "OK")
				alert(code);
			else
				window.location.reload();
        }
    });
})(iKnowBase);

/*
 * Office AddIn-functions
 */

iKnowBase.ContentViewer.EditOpenOfficeDocument = function(type,URL,mimeType,ikbToken,operation)
{
	if (mimeType == null)
		mimeType = "";

	try
	{
		var filename = ""

		if (type == "INDIRECT")
		{
			var xmlhttp = jQuery.ajax({
				type: "GET",
				async: false,
				url: encodeURI(URL),
				beforeSend: function(xhr) {
					xhr.setRequestHeader("x-iknowbase-getcontent-url", URL);
				}
				});

			if (xmlhttp.status != 200)
			{
				iKnowBase.errorPopup ('XMLHTTPError: ' + xmlhttp.status + "=" + xmlhttp.statusText + " (url=" + URL + ")");
				return;
			}

			URL = xmlhttp.getResponseHeader("x-iknowbase-content-url");
			filename = xmlhttp.getResponseHeader("x-iknowbase-content-filename");

		}
		
		// create the service objects
   		var objServiceManager = new ActiveXObject("com.sun.star.ServiceManager"); 
   		var objCoreReflection= objServiceManager.createInstance("com.sun.star.reflection.CoreReflection"); 
   		var objDesktop = objServiceManager.createInstance("com.sun.star.frame.Desktop"); 

   		// a new document 
   		var args = new Array();
		var objDocument = objDesktop.loadComponentFromURL(URL, "_blank", 0, args); 
	}
	catch	(e)
	{
	   iKnowBase.errorPopup ('Error opening document. Error= ' + e.name + '; description=' + e.message);
	}
}

iKnowBase.ContentViewer.EditMSOfficeDocument = function (type, URL, mimeType, ikbToken, operation)
{
        if (! window.ActiveXObject)
        {
                iKnowBase.errorPopup ('This function requires support for ActiveXObject (typically Microsoft Internet Explorer)');
                return;
        }

	if (mimeType == null)
		mimeType = "";

	var app = null;
	var doc = null;

	try
	{
		var filename = ""

		if (type == "INDIRECT")
		{
			var xmlhttp = jQuery.ajax({
				type: "GET",
				async: false,
				url: encodeURI(URL),
				beforeSend: function(xhr) {
					xhr.setRequestHeader("x-iknowbase-getcontent-url", URL);
				}
				});

			if (xmlhttp.status != 200)
			{
				iKnowBase.errorPopup ('XMLHTTPError: ' + xmlhttp.status + "=" + xmlhttp.statusText + " (url=" + URL + ")");
				return;
			}

			URL = xmlhttp.getResponseHeader("x-iknowbase-content-url");
			filename = xmlhttp.getResponseHeader("x-iknowbase-content-filename");

		}
		
		if (window.ikbCustomEditWindowsDocument)
		{
			var status = ikbCustomEditWindowsDocument ("PREOPEN", null, URL,
					mimeType, filename, operation)
			if (! status)
				return;
		}

		app = new ActiveXObject ("iKnowBase.RemoteDocument");
		doc = app.OpenDocument ("", URL, mimeType, ikbToken, filename);

		if (doc)
		{
			if (window.ikbCustomEditWindowsDocument)
			{
				var status = ikbCustomEditWindowsDocument ("POSTOPEN-SUCCESS", doc, URL, 
						mimeType, filename, operation)
				if (! status)
					return;
			}

			// doc contains Office Document Object, eg "Word.Document"
			// Set properties using "ikbOfficeSetProperty (doc, name, value)"
		}
		else
		{
			if (window.ikbCustomEditWindowsDocument)
			{
				var status = ikbCustomEditWindowsDocument ("POSTOPEN-FAILURE", doc, URL, 
						mimeType, filename, operation)
				if (! status)
					return;
			}

			window.open (URL, "_blank");
		}

		app = null;
		doc = null;
	}
	catch	(e)
	{
	   iKnowBase.errorPopup ('Error opening document. Error= ' + e.name + '; description=' + e.message);
	   app = null;
	   doc = null;
	}
}

function openOODoc(type, URL, mimeType, ikbToken, operation) {
	iKnowBase.ContentViewer.EditOpenOfficeDocument(type,URL,mimeType,ikbToken,operation);
}

function ikbEditWindowsDocument (type, URL, mimeType, ikbToken, operation) {
	iKnowBase.ContentViewer.EditMSOfficeDocument(type,URL,mimeType,ikbToken,operation);
}

function ikbOfficeSetProperty (doc, name, value)
{
	try
	{
		doc.CustomDocumentProperties(name).Value = value;
	}
	catch (e)
	{
		doc.CustomDocumentProperties.Add (name, false, 4, value);
	}
}
/*
 * iKnowBase Content Services - Office Addin javascripts
 * Copyright 1999-2010, e-vita as.
 */
(function(IKB) {

    var withAddin = withAddinFunction;

    function loadInProgress() {
        IKB.log ('AddinLoader: loading is already in progress');
    }

    function withAddinFunction(cb) {
        var v='AddinLoader: withAddin';
        IKB.log (v);
        withAddin = loadInProgress;
        jQuery.getScript('/ressurs/iknowbase/content-services/office-addin/office-addin.js', function() {
            IKB.log (': IKB.OfficeAddin loaded ok...');
            cb();
        });
    }

    function editDocument (options) {
        var v='AddinLoader: editDocument';
        IKB.log (v);
        withAddin(function() {
            IKB.log (': IKB.OfficeAddin loaded ok');
            IKB.OfficeAddin.editDocument(options);
        });
    }
    
    IKB.OfficeAddin = {
        editDocument: editDocument
    }

})(iKnowBase);
/*
 * iKnowBase Content Services - Content Viewer javascripts
 * Copyright 1999-2009, e-vita as.
 */

(function(IKB) {

    var undefined;

    function getUrl(controller, data) {
        var url = (IKB.locations.ikbViewer + controller);

        if (data !== undefined) {
            url = (url.match(/\?/) ? "&" : "?") + jQuery.param(data);
        }

		return url;
    }

    function showLoading (jqId) {
    	return jQuery("<div class='ikbContentViewerLoading'></div>").prependTo(jqId);
    }

    function reloadComponent (pageComponent, p1, p2) {

		// Default url is the page itself
		var url = IKB.config.href;
		var args = {}
	
		if (typeof pageComponent === "string")
			pageComponent = jQuery("#" + pageComponent);
	
		// Content viewer uses reloadComponent(id,url);
		if (typeof p1 === "string") {
			url = p1;
			args = p2;
		} else {
			args = p1;
		}

        var args = jQuery.extend({
            ikbRender: pageComponent.attr("id")
        }, args);

        var loading = showLoading(pageComponent);
    	pageComponent.load (url, args, function (response, status) {
            if (status != "success") {
                loading.remove();
                IKB.errorPopup ('reloadComponent error: id=' + pageComponent.attr("id") + '; status=' + status);
            }
        });
    	return false;
    }

	// Private function to get a target result
	function _callTargetService(url, data) {

		IKB.log ("_callTargetService", { url:url, data:data });

		jQuery.ajax({
			url: url,
			type: "POST",
			data: data,
			dataType: 'json',
			error: function (xhr,message,ex) {
				IKB.log ("_callTargetService: Error loading location info", {url:url, message:message, ex:ex});
				window.location = url;
			},
			success: function (json) {
				IKB.log ("_callTargetService: Target destination", json);
				if (json.data.windowName != null) {
					var features = json.data.windowFeatures;
					if (json.data.windowHeight) {
						features = "height=" + json.data.windowHeight
								 + ",top=" + (Math.max(screen.height-json.data.windowHeight,0) / 2)
								 + "," + features;
					}
					if (json.data.windowWidth) {
						features = "width=" + json.data.windowWidth
								 + ",left=" + (Math.max(screen.width-json.data.windowWidth,0) / 2)
								 + "," + features;
					}
					var win = window.open(json.data.URL, json.data.windowName, features)
				} else {
					window.location = json.data.URL;
				}
			}
		});
	}
	
	function goTarget (params) {
		var encoder = function(value) { return encodeURIComponent(value || ""); }
		// The page engine needs to get the redirect on the current URL, to ensure that
		// parameters stored in the path are handled properly
		if (IKB.config.isPage) {
			_callTargetService (IKB.config.href, {
				ikbAction: "ikb$goTarget",
				ikb$goTarget: jQuery.map([params.guid].concat(params.data), encoder)
			});
		} else {
			_callTargetService (IKB.locations.ikbViewer + "/go/target/" + params.guid, {
				_p: jQuery.map(params.data, encoder)
			});
		}
		return false;
	}

	// When clicking an A HREF link
	function clickTarget (link, event) {
		// If there is an event, do nothing when modifier keys are clicked. This
		// is to enable "ctrl+click" for "open in new tab", etc.
		if (event && (event.altKey || event.ctrlKey || event.shiftKey))
			return true;

		_callTargetService((typeof link === "string") ? link : link.href);
		return false;
	}
	
    // Expose these public functions
    IKB.PageEngine = {
        showLoading: showLoading,
        reloadComponent: reloadComponent,
		goTarget: goTarget,
		clickTarget: clickTarget
    };

})(iKnowBase);

/*
 * Function used to open iKnowBase targets. Uses javascript to find
 * any window features, if specified.
 */

function ikbGoTarget (link,event) {
	return iKnowBase.PageEngine.clickTarget(link,event);
}

