/** @fileoverview
 * Common logic for cms components.
 * @author Russ Tennant <russ@i2rd.com> 
 * @requires prototype.js version >=1.5
 */
if(typeof cmslib == 'undefined') {
cmslib = true;
if(typeof cms == 'undefined'){cms = {};}

cms.ZIndex = {};
cms.ZIndex.LOW = 10;
cms.ZIndex.MEDIUM = 200;
cms.ZIndex.HIGH = 500;
/** Tries to reload the page without triggering conditional-gets and adding to the history.
 * @param {bool} force flag to determine if the page should be forced to be reloaded regardless
 * of the browser history.
 */
cms.reloadPage = function(force) {
	var w = window;
	if(window.top){w = window.top;}
	if(force) {
		w.location.reload();
	} else {
		var path = unescape(w.location.pathname);
		if(path.indexOf("#") == (path.length - 1)) { path = path.substring(0, path.length - 1); }
		w.location.replace( path ); // Prevents entry from being added to browser history.
		w.setTimeout("cms.reloadPage(true)", 15000);
	}
};
cms_autoid_serial = 0;
cms.getId = function(element) {
	if(!element.id) {
		var pref = "ag_";
		if(element.nodeName){pref = element.nodeName.toLowerCase() + "_" + pref;}
		element.id = pref + (cms_autoid_serial++);
	}
	return element.id;
};
cms.removePageElementPath = function(path) {
	if(!path){return path;}
	var split = path.split("/");
	if(split.length !== 0) {
		var last = split[split.length - 1];
		if(last.match(/[a-zA-Z0-9]+,bx\d+[a-zA-Z0-9,]*/)) {
			split.length = split.length - 1;
			path = split.join("/");
		}
	}
	if(path.indexOf("/") !== 0){path = "/" + path;}
	return path;
};
cms.getBaseURL = function() {
	return window.location.protocol + "//" + window.location.host;
};
cms.getSanitizedURL = function() {
	return cms.getBaseURL() + cms.removePageElementPath(window.location.pathname);
};
cms.__xhtml = null;
cms.isXhtml = function() {
	if(!(document && i2rd.getBody())){
		throw new Error("You must call this method, cms.isXhtml(), after the document has been loaded.");
	}
	if(!cms.__xhtml) {
		var body = i2rd.getBody();
		var de = document.documentElement;
		var nsuri = (de ? de.namespaceURI : body.namespaceURI);
		var dt = document.doctype;
		cms.__xhtml =  (nsuri && nsuri.match(/xhtml/))
			|| (dt && dt.publicId && dt.publicId.toLowerCase().match(/xhtml/))
			|| (dt && dt.systemId && dt.systemId.toLowerCase().match(/xhtml/));
	}
	return cms.__xhtml;
};
cms.__strict = null;
cms.isStrict = function() {
	if(!(document && i2rd.getBody())){
		throw new Error("You must call this method, cms.isStrict(), after the document has been loaded.");
	}
	if(!cms.__strict) {
		var dt = document.doctype;
		var p = (dt ? dt.publicId : false);
		var s = (dt ? dt.systemId : false);
		cms.__strict = (p && p.toLowerCase().match(/strict/))
			|| (s && s.toLowerCase().match(/strict/));
	}
	return cms.__strict;
};
cms.isIE = function() { // compat.
	return i2rd.isIE;
};
/* Ref.
if(typeof Node == 'undefined') {
	var Node = new Object();
	Node.ELEMENT_NODE                   = 1;
  	Node.ATTRIBUTE_NODE                 = 2;
	Node.TEXT_NODE                      = 3;
	Node.CDATA_SECTION_NODE             = 4;
	Node.ENTITY_REFERENCE_NODE          = 5;
  	Node.ENTITY_NODE                    = 6;
  	Node.PROCESSING_INSTRUCTION_NODE    = 7;
  	Node.COMMENT_NODE                   = 8;
  	Node.DOCUMENT_NODE                  = 9;
  	Node.DOCUMENT_TYPE_NODE             = 10;
  	Node.DOCUMENT_FRAGMENT_NODE         = 11;
  	Node.NOTATION_NODE                  = 12;
}
*/
cms.getParent = function(el, pTagName) {
	if (el === null){return null;}
    while (el.parentNode && (!el.tagName ||
        (el.tagName.toUpperCase() != pTagName.toUpperCase()))){
      el = el.parentNode;
    }
	return el;
};
/** 
 * Set the inner HTML/XHTML. 
 * @return true on success; false otherwise.
 */
cms.setInnerHTML = function(el, xml) {
	if(!el) {
		log4js.logger.error("Got null element in setInnerHTML.", new Error());
		return false;
	}
	el = $(el);
	try {
		var html = "";
   		if(typeof(xml) == "string") {
   			html = xml;
		}else{
			var i,ib;
			if(xml.xml) {
				for ( i=0,ib=xml.childNodes.length; i < ib; i++ )
					{html += xml.childNodes[i].xml;}
			}else{
				var xmlSerializer = new XMLSerializer();
				for (i=0,ib=xml.childNodes.length ; i < ib; i++ ) {
					var tmp = xmlSerializer.serializeToString(xml.childNodes[i]);
					tmp = tmp.replace( /<textarea([^>]*)\/>/gi, '<textarea$1></textarea>' ) ;
					html += tmp;
				}
			}
        }
		Element.update(el, html);
		return true;
	} catch(e) { log4js.logger.error("Failed to update element: " + cms.getId(el), e); }
  	return false;
};
cms.setInnerXHTML = function(el, xml){
    if (!document.importNode || !DOMParser) { return cms.setInnerHTML(el, xml); }
    if(typeof(xml) == "string") {xml = new DOMParser().parseFromString(xml, 'text/xml');}
    var de = xml.documentElement;
    if (!(de && de.namespaceURI && de.namespaceURI.indexOf("xhtml") != -1 && de.nodeName != 'parsererror')) {
        return cms.setInnerHTML(el, xml);
    }
    el = $(el);
    try {
        var range = document.createRange();
        range.selectNodeContents(el);
        range.deleteContents();
    } catch(e) {
        log4js.logger.warn("Unable to delete contents. Perhaps the element is no longer in the document.", e);
        return cms.setInnerHTML(el, xml);
    }
    var node, scripts = [], i;
    scripts.pushAll(de.getElementsByTagName("script"));
    for (i = 0; i < scripts.length; i++) {
        node = scripts[i]; 
        if (!node.src || node.src.length == 0) {
            node.parentNode.removeChild(node);
        } else {
            scripts[i] = null;
        }
    }
    // Import DocumentElement
    el.appendChild(document.importNode(de, true));
    // Execute scripts
    var se = function(){
        for (var i = 0; i < scripts.length; i++) {
            if(!scripts[i]) continue;
            if (window.execScript) {
                window.execScript(scripts[i].textContext, "JavaScript");
            } else {
                window.eval(scripts[i].textContent);
            }
        }
    };
    setTimeout(se, 10);
    return true;
};
cms.copyTxtToClipboard = function(txt) {
		if(!txt) {
			var selObj = window.getSelection(); 
			if(selObj){txt = selObj.txt;}
		}
		if(window.clipboardData) {
			window.clipboardData.setData('Text', txt);
		} else if(typeof Components != 'undefined') {
			//http://developer.mozilla.org/en/docs/index.php?title=Using_the_Clipboard
			try {
				netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
				var ch = Components.classes["@mozilla.org/widget/clipboardhelper;1"].getService(Components.interfaces.nsIClipboardHelper);
				ch.copyString(txt);
			}catch(e) {
				var se = (e + "").indexOf("denied") > -1;
				if(se) { // Prompt user to give permission.
					cms.promptPermission("copy to the clipboard");
				}
				log4js.logger.info("Unable to copy to clipboard. " + e, e);
			}
		} else {
			/*var tr=document.selection.createRange();
			if(tr.text == txt)
				tr.execCommand("Copy");*/
		}
};
cms.promptPermission = function(perm) {
	var asked = i2rd.getCookie("asked-uxpc");
	if(!asked) {
		if(!confirm("To enable '" + perm + "', you need to grant permission." 
		+ " Please set 'signed.applets.codebase_principal_support' to true in about:config and grant permission when prompted."
		+ " Press Cancel if you no longer wish to see this message.")) {
			var time = new Date();
			time.setMonth(time.getMonth() + 1);
			i2rd.setCookie("asked-" + perm.replace(/ /g,"-"), "1", time, "/");
		}
	}
};
/**
* Get elements by tag name. Checks tag name in upper and lower case 
* for HTML and XHTML compat.
* @param tagName the tag name in lower case.
* @param start the start element. If not specified, use the document element.
* @return a node list or empty array.
*/
cms.getElementsByTagName = i2rd.getElementsByTagName;

cms.sendMouseClick = function(el) {
	el = $(el);
	var impl = document.implementation;
	if(impl && impl.hasFeature("MouseEvents","2.0") ) {
		var de = document.createEvent("MouseEvents");
		de.initMouseEvent("click", false, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
		el.dispatchEvent(de);
	}
	else if(cms.isIE()){el.click();}
	else{log4js.logger.warn("Generated mouse events not supported for browser");}
};


} // End conditional eval.
