﻿// CS Api 0.1
// Version: 2008-11-05 11:12
//
 
function CS(){}

CS.cache = [];

/// <summary>Return value of ept field</summary>
/// <param name="documentid">int. Document id</param>
/// <param name="fieldname">string. Ept field name</param>
/// <returns>string or null if field not found</returns>
/// <example>CS.getEptField(1254, 'title')</example>
CS.getEptField = function (documentid, fieldname, usecache)
{
    try
	{
	    if (!isInt(documentid))
	        throw new argumentException("documentid");
	    if (!isString(fieldname) || fieldname.lenght == 0)
	        throw new argumentException("fieldname");
	    if (!usecache)
	    	usecache = false;
	    
	    if (usecache && CS.cache["e_" + documentid + "_" + fieldname] != undefined)
	    	return CS.cache["e_" + documentid + "_" + fieldname];
	    
	    	var dom = CS.getDocumentContent(documentid);
	    	if (!dom)
	    		return null;
		var field = dom.selectSingleNode("/CSEPT/CSRecord/"+fieldname);
		if (field == null)
			return null;
		if (usecache)
			CS.cache["e_" + documentid + "_" + fieldname] = field.text;
		return field.text;
	}
	catch(e)
	{
		handleError(e, "CS.getEptField");
	}
};

/// <summary>Sets value of ept field</summary>
/// <param name="documentid">int. Document id</param>
/// <param name="fieldname">string. Ept field name</param>
/// <param name="value">string. Value</param>
/// <returns>bool. true if successful.</returns>
/// <example>CS.setEptField(1949, 'titel', 'new titel')</example>
CS.setEptField = function (documentid, fieldname, value)
{	
	try
	{
		if (arguments.length != 3)
	        throw new argumentException("3 arguments expected");
		if (!isInt(documentid))
	        throw new argumentException("documentid");
   	    if (!isString(fieldname))
	        throw new argumentException("fieldname");
	    if (!isString(value))
	        throw new argumentException("value");
	        
		var webserviceurl = getAdminURL("/WebAPI/ContentStudio_Document_DocumentManager.ashx?action=savecompletedocument&PerformApprove=1&PerformAutoCheckIn=1&PerformAutoCheckOutOnUpdate=1&id=" + documentid + "&connectionid=" + ConnectionID);
		var parameterxml = "&lt;CSEPT&gt;&lt;CSRecord&gt;" +
		"&lt;" + fieldname + "&gt;" + HTMLEncode(HTMLEncode(value)) + "&lt;/" + fieldname + "&gt;" +  
		"&lt;/CSRecord&gt;&lt;/CSEPT&gt;";
		
		var xml = "<root><parameters><parameter name=\"content\">" + parameterxml + "</parameter>" +
		"</parameters></root>";
	
		var tdom;
		tdom = getXMLDOM(webserviceurl, "POST", xml);

		if (tdom.selectSingleNode("//result[.='0']")==null)
			return false;
		return true;
	}
	catch(e)
	{
		handleError(e, "CS.setEptField");
	}
};

/// <summary>Returns document property</summary>
/// <param name="documentid">int. Document id</param>
/// <param name="fieldname">string. Ept field name. One of following: elementcreateddate, publishdate, introduction, elementorder, content
//    					elementimage, elementtarget, elementurl, elementname, filename, marking,
//    					revision, revisiondate, elementcreatedby, contentcreatedby, revisedby, modifiedby,
//    					modifieddate, contentcreateddate, categoryid, revisionstatus, 
//					publishstatus(num),ischeckedoutbyid,ischeckedoutcaller, lastcheckedout,
//					checkedoutbyname, filesize, contenttype, bodyproperties, headerproperties, keywords,
//					isapproved, isactivated, isdeleted, isrejected, isonrevision, isedittemplate,
//					ispresentationtemplate, sourcecodepreservation, documentuseage, lastused, etforptid,
//					parentelementid, modulename, elementid, imagesavailable, documentnr, guoid</param>
/// <returns>string. value of propery or null if not found</returns>
/// <example>CS.setEptField(1949, 'titel', 'new titel')</example>
CS.getDocumentField = function (documentid, fieldname, usecache)
{
	try
	{
	    if (!isInt(documentid))
	        throw new argumentException("documentid");
	    if (!isString(fieldname))
	        throw new argumentException("fieldname");
	    if (!usecache)
	    	usecache = false;
	    
	    if (usecache && CS.cache["dc_" + documentid + "_" + fieldname] != undefined)
	    	return CS.cache["dc_" + documentid + "_" + fieldname];

		var dom = CS.getDocument(documentid);
	
		if (dom.selectSingleNode("//result[.='0']")==null)
			return null;

		var field = dom.selectSingleNode("/root/document/"+fieldname);
					
		if (field == null)
			return null;
		
		if (usecache)
			CS.cache["dc_" + documentid + "_" + fieldname] = field.text;		
	
		return field.text;
	}
	catch(e)
	{
		handleError(e, "CS.getDocumentField");
	}
};

/// <summary>Executes filter query and returns value of specified field of first hit</summary>
/// <param name="categoryid">int. Category id</param>
/// <param name="indexedfields">string. comma separated string of fieldname to return in result or use in filter criteria</param>
/// <param name="filtercriteria">string. filter criteria.</param>
/// <param name="returnfield">string. value of field to return</param>
/// <returns>string. value of propery or null if not found</returns>
/// <example>CS.executeScalar(185, "titel", "[titel] LIKE '%Ny%'", "titel")</example>
CS.executeScalar = function (categoryid, indexedfields, filtercriteria, returnfield)
{
	try
	{
	    if (arguments.length != 4)
	        throw new argumentException("4 arguments expected");
		if (!categoryid || !isInt(categoryid))
			throw new argumentException("categoryid");
		if (!indexedfields || !isString(indexedfields))
			throw new argumentException("indexedfields");
		if (!filtercriteria || !isString(filtercriteria))
			throw new argumentException("filtercriteria");
		if (!returnfield || !isString(returnfield))
			throw new argumentException("returnfield");

		var i,url = getAdminURL("WebApi/ContentStudio_Document_EPT_XmlIndexQuery.ashx?action=query&PageNumber=1&PageSize=1&connectionid=" + ConnectionID);
		var params = "<root><parameters>" + 
			"<parameter name=\"categoryID\">" + categoryid + "</parameter>";
		
		var ifs = indexedfields.split(',');
		for (i=0; i<ifs.length; i++)
			params += "<parameter name=\"f" + (i+1).toString() + "\">" + ifs[i] + "</parameter>" + 
				  "<parameter name=\"r" + (i+1).toString() + "\">1</parameter>";

		params += "<parameter name=\"filter\">" + HTMLEncode(filtercriteria) + "</parameter>" + 
			"</parameters></root>";
	
		var xmldom = getXMLDOM(url, "POST", params);
		if (!xmldom)
			throw new exception("invalid xmldom");

		if (xmldom.selectSingleNode("//status[.='0']") == null)
			throw new exception(xmldom.selectSingleNode("root/statustext").text);

		var rows = xmldom.selectSingleNode("root/rows");
		if (!rows)
			return null;
		if (!rows.childNodes || rows.childNodes.length == 0)
			return null;
		return rows.childNodes[0].getAttribute(returnfield);
	}
	catch(e)
	{
	    handleError(e, "executeScalar");
	}
};

function isInt(value) { return typeof value == "number" && parseInt(value) == value; }
function isString(value) { return typeof value == "string"; }
function isObject(value) { return typeof value == "object"; }

function exception(message)
{
    this.name = "Exception";
    this.message = message;
}
function argumentException(fieldname)
{
    this.name = "ArgumentException";
    this.message = "Argument exception: " + fieldname;
}

function handleError(ex, name)
{
    var mess = ex.message;
    if (!mess)
    	mess = ex;
    throw new exception("Error in " + name + ": " + mess);
}

/// <summary>Extends non existing members in settings with members from options</summary>
CS.extend = function(settings, options)
{
	if (settings == null || settings == undefined)
		settings = {};
		
	for (var x in options)
	{
		if (settings[x] == undefined)
			settings[x] = options[x];
	}
	return settings;
};
/// <summary>
/// Fetches a document and returns xmldom
/// </summary>
CS.getDocument = function(documentid)
{
	try
	{
		if (!isInt(documentid))
	        	throw new argumentException("documentid");
	        
		var url = getAdminURL("WebAPI/ContentStudio_Document_DocumentReader.ashx?action=getdetails&id=" + documentid + "&connectionid=" + ConnectionID);
		var dom = getXMLDOM(url, "GET", null);

	    	if (dom.selectSingleNode("//result[.='0']")==null)
	    		return null;
	
		return dom;
	}
	catch(e)
	{
		handleError(e, "CS.getDocument");
	}
};

/// <summary>
/// Fetches document and returns content
/// </summary>
CS.getDocumentContent = function(documentid)
{
	try
	{
		if (!isInt(documentid))
	        	throw new argumentException("documentid");
	        
		var dom = CS.getDocument(documentid);

		dom.loadXML(dom.selectSingleNode("/root/document/content").text);
		return dom;
	}
	catch(e)
	{
		handleError(e, "CS.getDocumentContent");
	}
};

/// <summary>
/// Saves ept document. Extrafields are parameters. Settings are approve, checkin, checkout etc.
/// </summary>
CS.saveEptDocument = function(xmldata, extrafields, settings) {

	try
	{
	
		if (!isString(xmldata))
			throw new argumentException("xmldata");
			
		extrafields = CS.extend(extrafields, {
			elementname: "Untitled",
			fileext: "ept"
		});
				
		settings = CS.extend(settings, {
			approve: false,
			checkin: true,
			checkout: true
		});
			
		xml = "<root><parameters>" 
		xml = xml + "<parameter name=\"Content\">" + HTMLEncode(xmldata) + "</parameter>" ;
		xml = xml + "<parameter name=\"Contenttype\">text/xml</parameter>" ;
		
		if (extrafields && isObject(extrafields))
		{
			for (var f in extrafields)
			{
				if (f && extrafields[f])
					xml = xml + "<parameter name=\"" + HTMLEncode(f) + "\">" + HTMLEncode(extrafields[f]) + "</parameter>";
			}
		}
		
		xml += "</parameters></root>";
		
		var url = getAdminURL("webapi/ContentStudio_Document_DocumentManager.ashx?Action=savecompletedocument&PerformAutoCheckOutOnUpdate="+ (settings.checkout ? "1" : "0") +"&PerformAutoCheckIn=" + (settings.checkin ? "1" : "0") + "&connectionid=" + ConnectionID);
		if (settings.approve)
			url += "&PerformApprove=1";
		var xmldom = getXMLDOM(url, "POST", xml);
		
		if (!xmldom)
			throw new exception("invalid xmldom");
	
		if (xmldom.selectSingleNode("//status[.='0']") == null)
			throw new exception(xmldom.selectSingleNode("root/statustext").text);
		
		return xmldom;
	
	}
	catch(e)
	{
		handleError(e, "CS.saveEptDocument");
	}
};

/// <summary>
/// 
/// </summary>
CS.getDocumentPropertyFromDom = function(dom, fieldname)
{
	var node = dom.selectSingleNode("/root/document/" + HTMLEncode(fieldname));
	if (!node || !node.childNodes || node.childNodes.length == 0 )
		return null;
	return node.childNodes[0].data;
};

/// <summary>
/// Deletes document
/// </summary>
CS.deleteDocument = function(documentid, settings)
{
	try
	{
	    	if ((documentid = parseInt(documentid)) < 1)
	    		throw new argumentException("documentid");

	    	settings = CS.extend(settings, {
			permanent: false,
			parentchildrelation: false
		});
	    		
	        var url = getAdminURL("webapi/ContentStudio_Document_DocumentManager.ashx?Action=delete&id=" + documentid + 
			"&DeleteParentChildRelation=" + (settings.parentchildrelation == true ? "1" : "0") + 
			"&DeletePermanently=" + (settings.permanent == true ? "1" : "0") + 
			"&connectionid=" + ConnectionID);
			
		var xmldom = getXMLDOM(url, "GET", null);
		
		if (!xmldom)
			throw new exception("invalid xmldom");
	
		if (xmldom.selectSingleNode("//status[.='0']") == null)
			throw new exception(xmldom.selectSingleNode("root/statustext").text);
		
		return true;
	}
	catch(e)
	{
		handleError(e, "CS.deleteDocument");
	}
};

/// <summary>
/// Edits document via edit template
/// </summary>
CS.editDocument = function (documentid, callback)
{
	try
	{
		if ((documentid = parseInt(documentid)) < 1)
			throw new argumentException("documentid");
		var oWnd = showWebitor(ConnectionID, 0, documentid, "", "");
		if(oWnd == null)
			return;
		if (callback)
			oWnd.attachEvent("onunload", function() {
				callback(oWnd);
			});
	}
	catch (e)
	{
		handleError(e, "CS.editDocument");
	
	}

};

/// <summary>
/// Launches edit template
/// </summary>
CS.newDocument = function (categoryid, callback)
{
	try
	{
		if ((categoryid = parseInt(categoryid)) < 1)
			throw new argumentException("categoryid");			
		var oWnd = showWebitor(ConnectionID, categoryid, "", "", "");
		if(oWnd == null)
			return;
		if (callback)
			oWnd.attachEvent("onunload", function() {
				callback(oWnd);
			});
	}
	catch (e)
	{
		handleError(e, "CS.newDocument");
	
	}

};
// bas-klasser
// ---------------------------------------------------------------
//
/*                  _cscontainer
                       /                  _csdocument       _cscategory
              /     \                       Document     EptDocument     Category
       

*/

function _cscontainer()
{
	this.name;
	this.id;
}

function _csdocument()
{
	this.filename;
	this.publishdate;
	this.isCheckedOut = function () {
		throw new Error("not implemented");
	};
}

function _cscategory()
{
	
}

_cscategory.prototype = new _cscontainer();
_csdocument.prototype = new _cscontainer();



// Klasser
// --------------------------------------------------------------

function Category()
{
    
    return true;
}

Category.prototype = new _cscategory();



function Document()
{
    this.content;
    this.header;
    
    this.load = function (documentid) {
        throw new Error("not implemented");
    }; 
    
    return true;
}

Document.prototype = new _csdocument();


/// <summary>Ept document</summary>
/// <example>var ept = new EptDocument();
/// ept.setField("title", "Documents title");
/// ept.saveIn(654); // Save in category 654
/// </example>
function EptDocument()
{
    this.fields = [];
    
    /// <summary>Sets ept field</summary>
    this.setField = function (fieldname, value) {
        this.fields[fieldname] = value;
    };
    
    this.getField = function (fieldname) {
        return this.fields[fieldname];
    };

    this.existsField = function (fieldname) {
        return this.fields[fieldname] != undefined;
    };
        
    this.load = function (documentid) {
    
    	if (!isInt(documentid))
    	{
    		documentid = parseInt(documentid);
    		if (documentid < 1)
    			throw new argumentException("documentid");
    	}
        var dom = CS.getDocument(documentid);
        
        if (!dom)
        	return false;
        
        this.name = CS.getDocumentPropertyFromDom(dom, "elementname");
	this.filename = CS.getDocumentPropertyFromDom(dom, "filename");
	this.publishdate = CS.getDocumentPropertyFromDom(dom, "publishdate");

     	dom.loadXML(CS.getDocumentPropertyFromDom(dom, "content"));
        	
        var xmlnode = dom.selectSingleNode("CSEPT/CSRecord");
        if (!xmlnode)
        	return false;

        var i;
        for (i=0; i<xmlnode.childNodes.length; i++)
        {
            if (!xmlnode.childNodes[i])
            	continue;
            if (xmlnode.childNodes[i].nodeName == "documentid" && xmlnode.childNodes[i].childNodes.length > 0)
                this.id = xmlnode.childNodes[i].childNodes[0].data;
            
          if (xmlnode.childNodes[i].childNodes.length > 0)
            this.setField(xmlnode.childNodes[i].nodeName, xmlnode.childNodes[i].childNodes[0].data);
        }
        this.id = documentid;
        return true;
        
    };
    
    this.loadXml = function (xml) {
        throw new Error("not implemented");
    };    
    
    this.saveIn = function (categoryid, settings) {
        
        if (!isInt(categoryid))
        	throw new argumentException("categoryid");
        	
        var xml = "<CSEPT>" + this.toXml("CSRecord") + "</CSEPT>";
        
        var xmldom = CS.saveEptDocument(xml, {categoryid: categoryid, elementname: this.name}, settings);
        
        var node = xmldom.selectSingleNode("root/documentid");
        if (node && node.childNodes.length > 0)
        	return this.id = parseInt(node.childNodes[0].data);
        return null;
    };
    
    this.saveAs = function (documentid, settings) {
     	if (!isInt(documentid))
    		documentid = parseInt(documentid);
        if (!isInt(documentid))
        	throw new argumentException("documentid");
        	
        var xml = "<CSEPT>" + this.toXml("CSRecord") + "</CSEPT>";
        
        var options = {documentid: documentid};
        if (this.name)
        	options["elementname"] = this.name;
        var xmldom = CS.saveEptDocument(xml, options, settings);
        this.id = documentid;
        return this.id;
    };
    
    this.save = function (settings) {
	this.saveAs(this.id, settings);
	return this.id;
    };
    
    this.approve = function () {
    	if (!isInt(this.id) || this.id < 1)
    		throw new argumentException("id not set");
    		
        var url = getAdminURL("webapi/ContentStudio_Document_DocumentManager.ashx?Action=approve&id="+this.id+"&connectionid=" + ConnectionID);
	var xmldom = getXMLDOM(url, "GET", null);
	
	if (!xmldom)
		throw new exception("invalid xmldom");

	if (xmldom.selectSingleNode("//status[.='0']") == null)
		throw new exception(xmldom.selectSingleNode("root/statustext").text);
	
	return true;
    };
    
    this.count = function() {
    	var n = 0;
    	if (this.fields == null || this.fields == undefined)
    		return 0;
    	for (var i in this.fields)
    		n++;
    	return n;
    };
        
    this.hasFields = function () {
        return this.count() > 0;
    };

    this.checkIn = function () {
        throw new Error("not implemented");
    };

    this.checkOut = function () {
        throw new Error("not implemented");
    };
    
    this.clear = function () {
        this.fields = [];
    };    
    
    this.toString = function () {
        var str = "";
        for (var s in this.fields)
            str += s + "=" + this.fields[s] + ", ";
        return str.substr(0,str.length-2);
    };
    
    this.toJSON = function () {
        var str = "{";
        for (var s in this.fields)
            str += "\"" + s + "\": \"" + this.fields[s] + "\", ";
        return str.substr(0,str.length-2) + "}";
    };
    
    this.fromXmlNode = function (xmlnode) {
    
        if (!xmlnode || !isObject(xmlnode))
            throw new argumentException("xmlnode");
    
        var i;
        for (i=0; i<xmlnode.attributes.length; i++)
        {
            if (xmlnode.attributes[i].name == "documentid")
                this.id = parseInt(xmlnode.attributes[i].value);
            
            this.setField(xmlnode.attributes[i].name, xmlnode.attributes[i].value);
        }
    };
    
    this.toXml = function (containername) {
    	if (!containername)
    		containername = "ept";
    		
        var str = "<" + HTMLEncode(containername) + ">\n";
        for (var s in this.fields)
            str += "<" + HTMLEncode(s) + ">" + HTMLEncode(this.fields[s]) + "</" + HTMLEncode(s) + ">\n";
        str += "</" + HTMLEncode(containername) + ">";
        return str;
    };

    this.clear();
    return true;
}

EptDocument.prototype = new _csdocument();
/// <summary>Ept document</summary>
/// <example>var ept = new EptDocument();
/// ept.setField("title", "Documents title");
/// ept.saveIn(654); // Save in category 654
/// </example>
function XmlFilter()
{
    this.fields = new Array();
    this.recordcount = -1;
    this.pagecount = -1;
    this.criteria;
    this.categoryid;
    this.sortcommand;
    
    /// <summary>Sets ept field</summary>
    this.addField = function (fieldname, returnInResult) {
        if (returnInResult == null || returnInResult == undefined)
            returnInResult = true;
        if (fieldname == "documentid")
        	return;
        this.fields[fieldname] = returnInResult;
    };
    
    this.getField = function (fieldname) {
        return this.fields[fieldname];
    };

    this.existsField = function (fieldname) {
        throw new Error("not implemented");
    };
        
    this.hasFields = function () {
        throw new Error("not implemented");
    };

    this.clear = function () {
        this.fields = new Array();
        this.categoryid = 0;
    };
    
    this.toString = function () {
        var str = "";
        for (var s in this.fields)
            str += s + "=" + this.fields[s] + ", ";
        return str.substr(0,str.length-2);
    };
    
    /// <summary>
    /// Execute filter against ept category. 
    /// </summary>
    /// <returns>Erray of EptDocument or null</returns>
    this.execute = function (categoryid, pagenr, pagesize) {
        
        try 
        {
            if (!pagenr)
                pagenr = 1;
            if (!pagesize)
                pagesize = 1000000;
                
            if (!categoryid || !isInt(categoryid))
			    throw new argumentException("categoryid");
		    if (!isInt(pagenr))
			    throw new argumentException("pagenr");
		    if (!isInt(pagesize))
			    throw new argumentException("pagesize");
			    
			if (!this.criteria || !isString(this.criteria))
			    throw new argumentException("criteria");
            
            this.categoryid = categoryid;        
            
            var i,url = getAdminURL("WebApi/ContentStudio_Document_EPT_XmlIndexQuery.ashx?action=query&PageNumber=" + pagenr + "&PageSize=" + pagesize + "&connectionid=" + ConnectionID);
		    var params = "<root><parameters>" + 
			    "<parameter name=\"categoryID\">" + this.categoryid + "</parameter>";
    		
		    i=0;
		    for (var field in this.fields)
		    {
			    params += "<parameter name=\"f" + (i+1).toString() + "\">" + HTMLEncode(field) + "</parameter>" + 
				      "<parameter name=\"r" + (i+1).toString() + "\">"+ (this.fields[field] == true ? "1" : "0") + "</parameter>";
		        i++;
            }
            if (this.sortcommand)
            	params += "<parameter name=\"sortcommand\">" + this.sortcommand + "</parameter>";
            	
            if (i == 0)
            	throw new exception("at least one field must be specified");
            	
		    params += "<parameter name=\"filter\">" + HTMLEncode(this.criteria) + "</parameter></parameters></root>";
    	
		    var xmldom = getXMLDOM(url, "POST", params);
		    if (!xmldom)
			    throw new exception("invalid xmldom");

		    if (xmldom.selectSingleNode("//status[.='0']") == null)
			    throw new exception(xmldom.selectSingleNode("root/statustext").text);

		    this.recordcount = parseInt(xmldom.selectSingleNode("root/recordcount").text);
		    this.pagecount = parseInt(xmldom.selectSingleNode("root/pagecount").text);

		    var rows = xmldom.selectSingleNode("root/rows");
		    var epts = new Array();		    
		    if (!rows)
			    return epts;
		    if (!rows.childNodes || rows.childNodes.length == 0)
			    return epts;

            // bygg upp lista med eptdokument
			
			for (i=0; i<rows.childNodes.length; i++)
			{
			    var ept = new EptDocument();
			    ept.fromXmlNode(rows.childNodes[i]);
			    ept.categoryid = categoryid;
			    
			    epts.push(ept);
			}
			
		    return epts;
		}
		catch(e)
		{
		    throw new exception("error in XmlFilter:execute " + e.message);
		}
        
    };
    
    this.clear();
    return true;
}
