/* wetpaint related customization */
if( window.WPCAPI ) { 
WPCAPI.setDeveloperKey(SF_DEV_KEY);
WPCAPI.setNamespace(SF_NAMESPACE);
WPCAPI.processLogin = function() { location.href = SF_SIGNIN_URL; }
WPCAPI.setLoginTicket(SF_USER_TICKET);
}

//Override cell id generation
if( window.WPCAPI )
{
    WPCAPI.generateCellID = function( parentID, title, tags ) {
        var id = title.toLowerCase();
        id = id.replace(/[^a-zA-Z1-90]/g,"-");
        id = id.replace(/^-+|-+$/g,"");
        id = id.replace(/-+/g,"-");
        //based on parentID we will be able to tell if the new cell is a Page, Blog, or Module
        if (parentID.indexOf(SF_PAGE_ROOT) >= 0)
        {
            if(parentID.length > SF_PAGE_ROOT.length)
            {
                id = parentID + "$" + id;
            }
            else
            {
                id = SF_PAGE_ROOT + id;
            }
        }
        else if(parentID.indexOf(SF_BLOG_ROOT) >= 0)
        {
            id = SF_BLOG_ROOT + id;
        }
        return id;
    };
}
 
//Override cell URL generation
if( window.WPCAPI )
{
    WPCAPI.generateCellURL = function( parentID, title, tags, cellID ) {
        //based on parentID we will be able to tell if the new cell is a Page, Blog, or Module
        if(parentID.indexOf(SF_PAGE_ROOT) >= 0)
        {
            var url = location.href.toLowerCase();
            url = url.substring(0, url.indexOf(SF_SITE_ID) + SF_SITE_ID.length);
            var pageSeg = cellID.substring(cellID.indexOf(SF_PAGE_ROOT) + SF_PAGE_ROOT.length);
            pageSeg = pageSeg.replace("$","/");
            return url + "/" + pageSeg + "/";
        }
        else if( parentID.indexOf(SF_BLOG_ROOT) >= 0)
        {
            var cellSeg = cellID.substring(cellID.indexOf(SF_BLOG_ROOT) + SF_BLOG_ROOT.length);
            var url = location.href.toLowerCase();
            if(url.indexOf("?") > 0)
            {
                url = url.substring(0,url.indexOf("?"));
            }
            if(url.lastIndexOf("/") < url.length-1)
            {
                return url + "/" + cellSeg + "/?newpost=" + cellID;
            }
            else
            {
                return url + cellSeg + "/?newpost=" + cellID;
            }
        }
        return location.href;
    };
}

//override signin message
if( window.WPCAPI ) 
{
    WPCAPI.setLoginDialogProperties({
        title: SF_SIGNIN_TITLE,
        message: SF_SIGNIN_MSG,
        submit: SF_SIGNIN_SUB
    });
}

//Override search provider
if(window.WPCAPI)
{
    WPCAPI.addListener( "dialog:open", function(e) {
        switch( e.data.id ) {
            case "addImage":
            e.data.params.searchProvider = "msn";
            break;
            }
        } );
}

/* Archive module's dynamic tree code */
function getSFblogs(node, y, m)
{
    var nodeId = SF_SITE_ID + "-" + y + "-" + m;
    var existNode = document.getElementById(nodeId);
    if(!existNode)
    {
        node.setAttribute("id", nodeId);
        var url = "/services/blogging/service.aspx?service=getBlogsByMonth&" + "site=" + SF_SITE_ID + "&year=" + y + "&month=" + m;
        callService2(getSFblogsCB, url, nodeId);
    }
}

function getSFblogsCB(data, nodeId)
{
    var existNode = document.getElementById(nodeId);
    existNode.lastChild.innerHTML = data;
}

/* Left nav's dynamic expando code */
function expandSFLn(cellId)
{
    var sfIconNode = GE("sfln-icon-"+cellId);
    var sfSubPages = GE("sfln-subs-"+cellId);
    if(sfIconNode)
    {
        sfIconNode.innerHTML = "-";
        sfIconNode.onclick = function() {collapseSFLn(cellId);}
    }
    if(sfSubPages)
    {
        sfSubPages.style.display = 'block';
    }
}

function collapseSFLn(cellId)
{
    var sfIconNode = GE("sfln-icon-"+cellId);
    var sfSubPages = GE("sfln-subs-"+cellId);
    if(sfIconNode)
    {
        sfIconNode.innerHTML = "+";
        sfIconNode.onclick = function() {expandSFLn(cellId);}
    }
    if(sfSubPages)
    {
        sfSubPages.style.display = 'none';
    }
}

function getSFsubs(cellId)
{
    var url = "/services/blogging/service.aspx?service=getSubpages&" + "site=" + SF_SITE_ID + "&cell=" + cellId;
    callService2(getSFsubsCB, url, cellId);
}

function getSFsubsCB(data, cellId)
{
    var existNode = GE("sfln-subs-"+cellId);
    existNode.innerHTML = data;
}

//MKTree script (original url: http://www.mattkruse.com/javascript/mktree/source.html)
// Automatically attach a listener to the window onload, to convert the trees
addEvent(window,"load",convertTrees);

// Utility function to add an event listener
function addEvent(o,e,f){
	if (o.addEventListener){ o.addEventListener(e,f,true); return true; }
	else if (o.attachEvent){ return o.attachEvent("on"+e,f); }
	else { return false; }
}

// utility function to set a global variable if it is not already set
function setDefault(name,val) {
	if (typeof(window[name])=="undefined" || window[name]==null) {
		window[name]=val;
	}
}

// Full expands a tree with a given ID
function expandTree(treeId) {
	var ul = document.getElementById(treeId);
	if (ul == null) { return false; }
	expandCollapseList(ul,nodeOpenClass);
}

// Fully collapses a tree with a given ID
function collapseTree(treeId) {
	var ul = document.getElementById(treeId);
	if (ul == null) { return false; }
	expandCollapseList(ul,nodeClosedClass);
}

// Expands enough nodes to expose an LI with a given ID
function expandToItem(treeId,itemId) {
	var ul = document.getElementById(treeId);
	if (ul == null) { return false; }
	var ret = expandCollapseList(ul,nodeOpenClass,itemId);
	if (ret) {
		var o = document.getElementById(itemId);
		if (o.scrollIntoView) {
			o.scrollIntoView(false);
		}
	}
}

// Performs 3 functions:
// a) Expand all nodes
// b) Collapse all nodes
// c) Expand all nodes to reach a certain ID
function expandCollapseList(ul,cName,itemId) {
	if (!ul.childNodes || ul.childNodes.length==0) { return false; }
	// Iterate LIs
	for (var itemi=0;itemi<ul.childNodes.length;itemi++) {
		var item = ul.childNodes[itemi];
		if (itemId!=null && item.id==itemId) { return true; }
		if (item.nodeName == "LI") {
			// Iterate things in this LI
			var subLists = false;
			for (var sitemi=0;sitemi<item.childNodes.length;sitemi++) {
				var sitem = item.childNodes[sitemi];
				if (sitem.nodeName=="UL") {
					subLists = true;
					var ret = expandCollapseList(sitem,cName,itemId);
					if (itemId!=null && ret) {
						item.className=cName;
						return true;
					}
				}
			}
			if (subLists && itemId==null) {
				item.className = cName;
			}
		}
	}
}

// Search the document for UL elements with the correct CLASS name, then process them
function convertTrees() {
	setDefault("treeClass","mktree");
	setDefault("nodeClosedClass","liClosed");
	setDefault("nodeOpenClass","liOpen");
	setDefault("nodeBulletClass","liBullet");
	setDefault("nodeLinkClass","bullet");
	setDefault("preProcessTrees",true);
	if (preProcessTrees) {
		if (!document.createElement) { return; } // Without createElement, we can't do anything
		uls = document.getElementsByTagName("ul");
		for (var uli=0;uli<uls.length;uli++) {
			var ul=uls[uli];
			if (ul.nodeName=="UL" && ul.className==treeClass) {
				processList(ul);
			}
		}
	}
}

// Process a UL tag and all its children, to convert to a tree
function processList(ul) {
	if (!ul.childNodes || ul.childNodes.length==0) { return; }
	// Iterate LIs
	for (var itemi=0;itemi<ul.childNodes.length;itemi++) {
		var item = ul.childNodes[itemi];
		if (item.nodeName == "LI") {
			// Iterate things in this LI
			var subLists = false;
			for (var sitemi=0;sitemi<item.childNodes.length;sitemi++) {
				var sitem = item.childNodes[sitemi];
				if (sitem.nodeName=="UL") {
					subLists = true;
					processList(sitem);
				}
			}
			var s= document.createElement("SPAN");
			var t= '\u00A0'; // &nbsp;
			s.className = nodeLinkClass;
			if (subLists) {
				// This LI has UL's in it, so it's a +/- node
				if (item.className==null || item.className=="") {
					item.className = nodeClosedClass;
				}
				// If it's just text, make the text work as the link also
				if (item.firstChild.nodeName=="#text") {
					t = t+item.firstChild.nodeValue;
					item.removeChild(item.firstChild);
				}
				s.onclick = function () {
					this.parentNode.className = (this.parentNode.className==nodeOpenClass) ? nodeClosedClass : nodeOpenClass;
					return false;
				}
			}
			else {
				// No sublists, so it's just a bullet node
				item.className = nodeBulletClass;
				s.onclick = function () { return false; }
			}
			s.appendChild(document.createTextNode(t));
			item.insertBefore(s,item.firstChild);
		}
	}
}
