﻿if (typeof vcc != "object")	vcc = {};

if (vcc.authoring == null)
	vcc.authoring = {};

vcc.authoring.draggables = {};

$(document).ready(function() {
	//Only run ce init when in list view mode
	if (document.getElementById("page") == null)
		vcc.authoring.ce.init();
    vcc.authoring.createNonVisibleItems();
    vcc.authoring.createVolvoCarsLinksSubMenu();
});

/*  XML  */
vcc.authoring.getXmlDocument = function(sXml) {
    var oXmlDoc;

    if (sXml.substring(0, 1) == "/") {
        try {
            // IE
            oXmlDoc = new ActiveXObject("Msxml2.FreeThreadedDOMDocument");
            oXmlDoc.async = "false";
            oXmlDoc.load(sXml);
        }
        catch (e) {
            // TODO: Solve synchronization problem in other browsers when loading XML from file
            return null;
        }
    }
    else {
        try { // Firefox, Mozilla, Opera, etc.
            parser = new DOMParser();
            oXmlDoc = parser.parseFromString(sXml, "text/xml");
        }
        catch (e) {
            try {
                // IE
                oXmlDoc = new ActiveXObject("Msxml2.FreeThreadedDOMDocument");
                oXmlDoc.async = "false";
                oXmlDoc.loadXML(sXml);
            }
            catch (e) {
                return null;
            }
        }
    }
    return oXmlDoc;
}

/*  XSLT  */
/*
    Description: transforms the XML, using the XSL, and returns the result as a text node
    PARAM1: string of XML
    PARAM2: string of XSL
    PARAM3: Array of Objects with properties "name" and "value"
    RETURNS: DOM node
*/
vcc.authoring.xslTransform = function(sXml, sXsl, aXslArgumentList) {
    var xmlDoc = vcc.authoring.getXmlDocument(sXml);
    var xslDoc = vcc.authoring.getXmlDocument(sXsl);
    var result;
    try {
        if (window.ActiveXObject) {
            // Internet Explorer - xmlDoc.resolveExternals = false;
            var xslTemplate = new ActiveXObject("MSXML2.XSLTemplate");
            xslTemplate.stylesheet = xslDoc;
            var xslProc = xslTemplate.createProcessor();
            xslProc.input = xmlDoc;
            // Add XSL arguments
            if (aXslArgumentList && aXslArgumentList != null) {
                for (i = 0; i < aXslArgumentList.length; i++)
                    xslProc.addParameter(aXslArgumentList[i].name, aXslArgumentList[i].value);
            }
            xslProc.transform();
            result = document.createElement();
            result.innerHTML = xslProc.output;
        }
        else if (document.implementation && document.implementation.createDocument) {
            // Mozilla, Firefox, Opera etc
            xsltProcessor = new XSLTProcessor();
            xsltProcessor.importStylesheet(xslDoc);
            // Add XSL arguments
            if (aXslArgumentList && aXslArgumentList != null) {
                for (i = 0; i < aXslArgumentList.length; i++)
                    xsltProcessor.setParameter(null, aXslArgumentList[i].name, aXslArgumentList[i].value);
            }
            result = xsltProcessor.transformToFragment(xmlDoc, document);

        }
    }
    catch (e) { }
    return result;
}

/*  AJAX  */
/* 
    Description: sends a asynchronous HTTP request using the method and url specified
                 and calls onReadyFunction with the response text when done 
*/
vcc.authoring.sendAjaxRequest = function(method, url, onReadyFunction) {
    var xmlHttp;
    try {
        // Internet Explorer 6.0+
        xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
    }
    catch (e) {
        // Internet Explorer 5.5+
        try {
            xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
        }
        catch (e) {
            try {
                // Firefox, Opera 8.0+, Safari
                xmlHttp = new XMLHttpRequest();
            }
            catch (e) {
                return null;
            }
        }
    }
    xmlHttp.onreadystatechange = function() {
        // Check if request has completed
        if (xmlHttp.readyState == 4 || xmlHttp.readyState == 'complete') {
            // Pass response text to the callers on ready function
            onReadyFunction(xmlHttp.responseText);
        }
    }
    xmlHttp.open(method, url, true);
    xmlHttp.send(null);
}


/*  Non-visible items  */
vcc.authoring.createNonVisibleItems = function() {
	
	var aNonVisibleItems = $(".nonVisibleItem");
	if (aNonVisibleItems.length == 0)
		return;
		
	var oNonVisibleItemsContainer = document.createElement("div");
	oNonVisibleItemsContainer.className = "floatingWindow";
	oNonVisibleItemsContainer.title = "Page configuration";
	oNonVisibleItemsContainer.id = "nonVisibleItems";
	document.getElementsByTagName("form").item(0).appendChild(oNonVisibleItemsContainer);
	
	$.each(aNonVisibleItems, function() {
		var sGroupId = (this.getAttribute("group") != null) ? this.getAttribute("group").replace(/ /, "") : "DefaultGroup";
		if (sGroupId != "") {
			sGroupId = "ItemGroup_" + sGroupId;
			//Item belongs to a group
			var oGroup = document.getElementById(sGroupId);
			if (oGroup == null) {
				oGroup = document.createElement("div");
				oGroup.className = "nonVisibleItemsGroup"
				oGroup.id = sGroupId;
				oGroup.innerHTML = "<table><tbody><tr class=\"row\"></tr></tbody></table>";
				oNonVisibleItemsContainer.appendChild(oGroup);
			}
			var oTableRow = oGroup.getElementsByTagName("tr")[0];
			var oNewCell = document.createElement("td");
			oNewCell.className = "nonVisibleitemsGroupItem";
			oTableRow.appendChild(oNewCell);
			oNewCell.appendChild(this);
		} else {
			oNonVisibleItemsContainer.appendChild(this);
		}
		
		if (this.title != null) {
			var sOriginalHtml = this.innerHTML;
			this.innerHTML = "<h2>" + this.title + "</h2>" + sOriginalHtml;
		}
	});
	
	//Fix groups
	var aGroups = $(".nonVisibleItemsGroup", oNonVisibleItemsContainer);
	if (oNonVisibleItemsContainer.getElementsByTagName("table").length > 0)
		aGroups[aGroups.length - 1].className = "nonVisibleItemsGroup-last";
	
	var oLink = document.createElement("a");
	oLink.href = "#";
	oLink.id = "nonvisibleitemslink";
	oLink.innerText = "Page configuration";
	oLink.description = "Manage meta data and custom JavaScript and CSS.";
	oLink.onclickFunction = "vcc.authoring.showPageConfiguration()";
	vcc.authoring.addLinkToSiteActionsMenu(oLink);

}

vcc.authoring.showPageConfiguration = function() {
    vcc.authoring.toggleFloatingWindow('nonVisibleItems', null);
    vcc.authoring.ce.init();
}

vcc.authoring.addLinkToSiteActionsMenu = function(oLink) {
	var sSiteActionXml = "<ie:menuitem description=\"" + oLink.description + "\" id=\"" + oLink.id + "\" type=\"option\" onMenuClick=\"" + oLink.onclickFunction + "\" text=\"" + oLink.innerText + "\" menuGroupId=\"2147483647\" />";
	var oSiteActionTd = document.getElementById("siteactiontd");
	if (oSiteActionTd == null)
		return;
	var aMenuTags = oSiteActionTd.getElementsByTagName("menu");
	if (aMenuTags.length == 0)
		return;
	aMenuTags.item(0).innerHTML += sSiteActionXml;
}

vcc.authoring.createVolvoCarsLinksSubMenu = function() {
    var oSiteActionTd = document.getElementById("siteactiontd");
    if (oSiteActionTd == null)
        return;
    var aMenuTags = oSiteActionTd.getElementsByTagName("menu");
    if (aMenuTags.length == 0)
        return;

    var oSubMenu = {
        text: "Volvo Cars Links",
        description: "Links to Volvo Cars web systems.",
        iconSrc: "/_layouts/volvocars.sharepoint.features.site3/images/logo32x30.gif"
    };
    var oLinks = [
		{
		    text: "SCNG editing",
		    description: "Manage SCNG data",
		    url: "https://scng.authoring.volvocars.net/"
		},
		{
		    text: "IDA editing",
		    description: "Manage dealer data",
		    url: "https://ida.authoring.volvocars.net/"
		},
		{
		    text: "IM Net",
		    description: "IM collaboration site",
		    url: "https://site.authoring.volvocars.net/sites/imnet/default.aspx"
		}
	];

    // Create xml for a submenu in the site actions menu
    var sSubMenu = "<ie:menuitem id=\"volvocarslinks_submenu\" type=\"submenu\" iconSrc=\"" + oSubMenu.iconSrc + "\" text=\"" + oSubMenu.text + "\" description=\"" + oSubMenu.description + "\">";
    // Add links to submenu
    for (var i = 0; i < oLinks.length; i++) {
        sSubMenu += "<ie:menuitem id=\"volvocarslinks_submenu_link" + i + "\" type=\"option\" onMenuClick=\"window.open('" + oLinks[i].url + "');\" text=\"" + oLinks[i].text + "\" description=\"" + oLinks[i].description + "\" menuGroupId=\"2147483646\"></ie:menuitem>";
    }
    // Close submenu xml
    sSubMenu += "</ie:menuitem>";

    // Add submenu xml to site actions menu
    aMenuTags.item(0).innerHTML += sSubMenu;
}

vcc.authoring.floatingWindowResizeIntervals = {};

vcc.authoring.toggleFloatingWindow = function(sId, oLink) {
	var oWindow = document.getElementById(sId);
	if (oWindow == null)
		return false;	

	if (oWindow.style.visibility == "visible") {
		//Hide window
		//$(oWindow).hide();
		oWindow.style.visibility = "hidden";
		oWindow.style.top = "-5000px";
		oWindow.style.left = "-5000px";
		$(oWindow).draggable("destroy");
		clearInterval(vcc.authoring.floatingWindowResizeIntervals[sId]);
	} else {
		var aFloatingWindows = $(".floatingWindow");
		if (aFloatingWindows.length == 0)
			return;

		if (oWindow.getAttribute("draggable") != "true") {
			var oForm = document.getElementsByTagName("form").item(0);
			oForm.appendChild(oWindow);
			var sOriginalHtml = oWindow.innerHTML;
			var sHtml = "<iframe src=\"/_layouts/VolvoCars.SharePoint.Features.Site3/empty.htm\" frameborder=\"0\" border=\"0\" width=\"100%\" height=\"100px\"></iframe><div class=\"floatingWindow_inner\">";
			sHtml += "<div class=\"titlebar\" onfocus=\"this.blur();\" onselect=\"this.blur();\"><span>" + oWindow.getAttribute("title") + "</span><a href=\"#\" onclick=\"vcc.authoring.toggleFloatingWindow('" + oWindow.id + "', null);return false;\"></a></div>";
			sHtml += "<div class=\"window-content\">" + oWindow.innerHTML + "</div>";
			sHtml += "</div>";
			oWindow.innerHTML = sHtml;
			vcc.authoring.resizeIframeForFloatingWindow(sId);
			oWindow.setAttribute("draggable", "true");
			vcc.authoring.floatingWindowResizeIntervals[sId] = setInterval("vcc.authoring.resizeIframeForFloatingWindow('" + sId + "')", 500);
		}
		//Move this floatingWindow to the top over all other floatingWindows
		var iHighestZIndex = 0;
		var aFloatingWindows = $(".floatingWindow");
		$.each(aFloatingWindows, function() {
			if (this.style.zIndex > iHighestZIndex)
				iHighestZIndex = this.style.zIndex;
		});
		oWindow.style.zIndex = iHighestZIndex + 1;
		
		if (oLink == null) {
			oWindow.style.left = 100 + "px";
			oWindow.style.top = 100 + "px";
		} else {
			oLink = $(oLink);
			oWindow.style.left = oLink.offset().left + "px";
			oWindow.style.top = oLink.offset().top - 100 + "px";
		}
		oWindow.style.visibility = "visible";
		$(oWindow).draggable({
			handle: $(".titlebar", $(oWindow))
		});
	}
	return false;
}

vcc.authoring.resizeIframeForFloatingWindow = function(floatingWindowId) {
	var oWindow = document.getElementById(floatingWindowId);
	if (oWindow == null)
		return false;
	var oIframe = oWindow.getElementsByTagName("iframe").item(0);
	var oFloatingWindowInner = $("#" + floatingWindowId + " .floatingWindow_inner");
	oIframe.style.width = oFloatingWindowInner.outerWidth() + "px";
	oIframe.style.height = oFloatingWindowInner.outerHeight() + "px";
}

/* Flash */
vcc.authoring.onFlashAssetSelected = function(newAssetUrl, sParentContainerID) {
    // Check file type
    if (newAssetUrl.substring(newAssetUrl.length - 5).toLowerCase() == ".aspx") {
        // Dynamic content
        vcc.authoring.sendAjaxRequest("GET", newAssetUrl + "?xmlonly=true", function(sXml) {

            // Create XML document
            var oAjaxXmlDoc = vcc.authoring.getXmlDocument(sXml);

            var height = oAjaxXmlDoc.childNodes[0].getAttribute('height');
            var width = oAjaxXmlDoc.childNodes[0].getAttribute('width');
            var movieurl = oAjaxXmlDoc.childNodes[0].getAttribute('movieurl');
            var contenturl = oAjaxXmlDoc.childNodes[0].getAttribute('contenturl');
            var transparency = oAjaxXmlDoc.childNodes[0].getAttribute('transparency');
            var sBgcolor = oAjaxXmlDoc.childNodes[0].getAttribute('bgcolor');
            var requiredVersion = oAjaxXmlDoc.childNodes[0].getAttribute('requiredflashplugin');
            if (requiredVersion == null)
                requiredVersion = "8";

            // New
            $("#" + sParentContainerID + " .flash-width input").val(width);
            $("#" + sParentContainerID + " .flash-height input").val(height);
            $("#" + sParentContainerID + " .flash-version select option:contains(" + requiredVersion + ")").attr("selected", true);

            //Write flash object
            var sContainerId = sParentContainerID.replace("_flashSettings", "_flashContainer");
            $("#" + sContainerId).replaceWith("<div id=\"" + sContainerId + "\"></div>");
            contenturl = encodeURIComponent(contenturl + "?xmlonly=true");
            movieurl = movieurl + "?contenturl=" + contenturl + "&onlineparam=volvocars.net";

            swfobject.embedSWF(movieurl, sContainerId, width, height, "8", "/_layouts/VolvoCars.SharePoint.Features.Site3/swf/expressInstall.swf", vcc.flashVars, { wmode: "opaque", allowscriptaccess: "always", allowfullscreen: "true", bgcolor: sBgcolor }, { id: sContainerId, "class": "flash" });

        });
    }
    else {
        // Static flash file
        var sContainerId = sParentContainerID.replace("_flashSettings", "_flashContainer");
        $("#" + sContainerId).replaceWith("<div id=\"" + sContainerId + "\"></div>");
        // Get size of flash
        var width = $("#" + sParentContainerID + " .flash-width input").val();
        var height = $("#" + sParentContainerID + " .flash-height input").val();
        // Embed the flash movie
        swfobject.embedSWF(newAssetUrl, sContainerId, width, height, "8", "/_layouts/VolvoCars.SharePoint.Features.Site3/swf/expressInstall.swf", vcc.flashVars, { wmode: "opaque", allowscriptaccess: "always", allowfullscreen: "true", bgcolor: "#FFFFFF" }, { id: sContainerId, "class": "flash" });
    }
}

vcc.authoring.numCheck = function(e) {
    if (window.event)
        keycode = e.keyCode;
    else if (e.which)
        keycode = e.which;

    keychar = String.fromCharCode(keycode);
    numcheck = /\d/;
    return numcheck.test(keychar);
}

vcc.authoring.updateFlashMovie = function(sParentContainerID) {
    var sFlashContainerId = sParentContainerID.replace("_flashSettings", "_flashContainer");
    var oFlash = document.getElementById(sFlashContainerId);
    if (oFlash != null) {
        var w = $("#" + sParentContainerID + " .flash-width input").val();
        var h = $("#" + sParentContainerID + " .flash-height input").val();
        oFlash.style.width = w + "px";
        oFlash.style.height = h + "px";
    }
}

/* Agi */
/*
    Description: called when the AGI template drop down list is changed
                 Makes a AJAX call to the URL (arg 1) and transforms the response text xml
                 using the XSL string (arg 2) into HTML. The HTML is then added as a text
                 node to the container pointed to by the container ID (arg 3).
                 The response text xml is also stored in the xml control pointed to by
                 the xml control ID (arg 4)
*/
vcc.authoring.loadAgiTemplate = function(sTemplateUrl, sXslt, sContainerID, sXmlControlID, sParameterControlID) {
    var oXmlControl = document.getElementById(sXmlControlID);
    if (oXmlControl == null)
		return;
    var oContainer = document.getElementById(sContainerID);
    if (sTemplateUrl == null || sTemplateUrl == "") {
        oXmlControl.value = "";
        oContainer.removeChild(oContainer.childNodes[0]);
        return;
    }
    try {
        vcc.authoring.sendAjaxRequest("GET", sTemplateUrl + "?config=true", function(sXml) {
            oXmlControl.value = sXml;
            var args = new Array();
            args[0] = new Object();
            args[0].name = "xmlControlID";
            args[0].value = sXmlControlID;
            args[1] = new Object();
            args[1].name = "parametersControlID";
            args[1].value = sParameterControlID;
            var newNode = vcc.authoring.xslTransform(sXml, sXslt, args);
            if (oContainer.childNodes.length == 1)
                oContainer.removeChild(oContainer.childNodes[0]);
            oContainer.appendChild(newNode);
        });
    }
    catch (e) {
    }
}

vcc.authoring.encodeAgiValue = function(sValue) {
    if (typeof sValue != "string")
        return sValue;

    var decodedValue = sValue;

    decodedValue = decodedValue.replace(/</g, "&lt;");
    decodedValue = decodedValue.replace(/>/g, "&gt;");
    decodedValue = decodedValue.replace(/&/g, "&amp;");
    decodedValue = decodedValue.replace(/\'/g, "&apos;");
    decodedValue = decodedValue.replace(/\"/g, "&quot;");

    return decodedValue;
}

/*
Description: loads XML from control and updates the specified node name with the value
*/
vcc.authoring.updateAgiXml = function(sName, sValue, sXmlControlID, sParametersControlID, nDrawableIndex) {
    var oXml = vcc.authoring.getXmlDocument(document.getElementById(sXmlControlID).value);
    var xmlNode;
    if (nDrawableIndex >= 0) {
        var subNodes = oXml.getElementsByTagName('Drawable')[nDrawableIndex].childNodes;
        for (i = 0; i < subNodes.length; i++) {
            if (subNodes[i].nodeName == sName)
                xmlNode = subNodes[i];
        }
    }
    else {
        var xmlNodes = oXml.getElementsByTagName(sName);
        for (i = 0; i < xmlNodes.length; i++) {
            if (xmlNodes[i].parentNode.nodeName == "AgiSettings") {
                xmlNode = xmlNodes[i];
            }
        }
    }
    if (xmlNode) {
        var textNode = oXml.createTextNode(vcc.authoring.encodeAgiValue(sValue));
        if (xmlNode.childNodes.length == 0) {
            xmlNode.appendChild(textNode);
        }
        else {
            xmlNode.replaceChild(textNode, xmlNode.firstChild);
        }
        // Update parameters control
        vcc.authoring.updateAgiParametersControl((nDrawableIndex >= 0 ? nDrawableIndex + "_" + sName : sName), sParametersControlID);
        // Update XML control
        vcc.authoring.updateAgiXmlControl(oXml, sXmlControlID);
    }
}

/*
Description: adds the string in sName to the value of the control pointed to by sParametersControlID (the value is only added once)
*/
vcc.authoring.updateAgiParametersControl = function(sName, sParametersControlID) {
    var sValue = document.getElementById(sParametersControlID).value;
    if (sValue.length < sName.length) {
        if (sValue.length > 0)
            sValue += ",";
        sValue += sName;
    }
    else {
        if (sValue.indexOf(sName) == -1) {
            sValue += "," + sName;
        }
    }
    document.getElementById(sParametersControlID).value = sValue;
}

/*
Description: updates the value of the control with the XML documents content
*/
vcc.authoring.updateAgiXmlControl = function(oXml, sXmlControlID) {
    var serializedXml;
    try { // Firefox, Mozilla, Opera, etc.
        serializedXml = (new XMLSerializer()).serializeToString(oXml);
    }
    catch (e) { // IE
        try {
            serializedXml = oXml.xml;
        }
        catch (e) {
            return;
        }
    }
    document.getElementById(sXmlControlID).value = serializedXml;
}

/*
    Description: converts the RGB color values returned by some browsers to a regular HEX format.
                 Ex. rgb(100, 100, 100) is converted to "#646464"
*/
vcc.authoring.rgbToHex = function(str) {
    if (str.indexOf("rgb(") == -1)
        return str.toUpperCase();

    arr = str.replace(/rgb\(|\)/g, "").split(",");
    arr[0] = parseInt(arr[0], 10).toString(16).toUpperCase();
    arr[1] = parseInt(arr[1], 10).toString(16).toUpperCase();
    arr[2] = parseInt(arr[2], 10).toString(16).toUpperCase();
    arr[0] = (arr[0].length == 1) ? '0' + arr[0] : arr[0];
    arr[1] = (arr[1].length == 1) ? '0' + arr[1] : arr[1];
    arr[2] = (arr[2].length == 1) ? '0' + arr[2] : arr[2];
    return ('#' + arr.join(""));
}

/*
    Description: marks a DIV as selected by changing it's border-color to yellow and deselects all it's sibling DIV elements by setting their border-color to black
    PARAM1: DIV element that was clicked
*/
vcc.authoring.colorClick = function(sName, oDiv, xmlControlID, parametersControlID) {
    elements = oDiv.parentNode.getElementsByTagName('div');
    for (i = 0; i < elements.length; i++) {
        elements[i].className = "field-control-editor-colorBox";
    }
    var bgcolor = vcc.authoring.rgbToHex(oDiv.style.backgroundColor);
    vcc.authoring.updateAgiXml(sName, bgcolor, xmlControlID, parametersControlID);
    oDiv.className = "field-control-editor-colorBoxSelected";
}

vcc.authoring.toggleAgiMoreOptions = function(sId) {
	var oMoreContainer = document.getElementById(sId);
	if (oMoreContainer == null)
		return;
	oMoreContainer.style.display = (oMoreContainer.style.display == "block") ? "none" : "block";
}

/* Media type selector field control functions */

if (vcc.authoring.mediatypeselector == null) vcc.authoring.mediatypeselector = {};
		
vcc.authoring.mediatypeselector.onMediaSelected = function(oDropdown, sImageId, sFlashId, sAgiId, sControlId) {
	var sValue = oDropdown.options[oDropdown.selectedIndex].value;
	if (sValue == "#")
		return;
	var oXml = vcc.authoring.getPageConfigXml();
	var oInnerXml = oXml.createElement("type");
	oInnerXml.text = sValue;
	vcc.authoring.updatePageConfigSection("MediaType_" + sControlId, oInnerXml);
	document.getElementById(sImageId).style.display = (sValue == "image") ? "block" : "none";
	document.getElementById(sFlashId).style.display = (sValue == "flash") ? "block" : "none";
	document.getElementById(sAgiId).style.display = (sValue == "agi") ? "block" : "none";
}

/* Navigation visibility config */

vcc.authoring.setNavigationVisibility = function(oDropdown, sNavigationId) {
	var sValue = oDropdown.options[oDropdown.selectedIndex].value;
	var oConfigSectionXml = vcc.authoring.getPageConfigSection("NavigationVisibility", true);
	if (oConfigSectionXml == null) {
		//Create new config xml here
		var oNewSectionXml = new ActiveXObject("Microsoft.XMLDOM");
		oNewSectionXml.setProperty("SelectionLanguage", "XPath");
		var sDefaultXml = "<navigations/>";
		oNewSectionXml.loadXML(sDefaultXml);
		oConfigSectionXml = oNewSectionXml.documentElement;
	}
	var oNode = oConfigSectionXml.selectSingleNode("navigation[@id = '" + sNavigationId + "']");
	if (oNode == null) {
		var oNode = oConfigSectionXml.ownerDocument.createElement("navigation");
		oNode.setAttribute("id", sNavigationId);
		oConfigSectionXml.appendChild(oNode);
	}
	oNode.text = sValue;
	vcc.authoring.updatePageConfigSection("NavigationVisibility", oConfigSectionXml);	
}

/* Inherit AGI */

vcc.authoring.setInheritAGI = function(oCheckbox) {
	var sValue = oCheckbox.checked ? "true" : "false";
	var oConfigSectionXml = vcc.authoring.getPageConfigSection("InheritAGI", true);
	if (oConfigSectionXml == null) {
		//Create new config xml here
		var oNewSectionXml = new ActiveXObject("Microsoft.XMLDOM");
		oNewSectionXml.setProperty("SelectionLanguage", "XPath");
		var sDefaultXml = "<inherit/>";
		oNewSectionXml.loadXML(sDefaultXml);
		oConfigSectionXml = oNewSectionXml.documentElement;
		var oNode = oConfigSectionXml.selectSingleNode("/inherit");
		oNode.text = sValue;
	} else {
		oConfigSectionXml.text = sValue;
	}
	vcc.authoring.updatePageConfigSection("InheritAGI", oConfigSectionXml);	
}

/* Page config XML helper functions */

vcc.getElementByIdFragment = function (strId, strNodeName) {
	strNodeName = strNodeName || "*";
	var arElements = document.getElementsByTagName(strNodeName);
	for (var i=0; i<arElements.length; i++) {
		if (arElements[i].id && arElements[i].id.indexOf(strId) > -1)
			return(arElements[i]);
	}
	return null;
}

vcc.authoring.oPageConfigXml = null;
		
vcc.authoring.initPageConfigXml = function() {
	if (vcc.authoring.oPageConfigXml == null) {
		var oPageConfigTextarea = vcc.getElementByIdFragment("pageConfigXml", "textarea");
		if (oPageConfigTextarea == null)
			return;
		var sXml = oPageConfigTextarea.innerText;
		if (sXml == "")
			sXml = "<configs/>";
		vcc.authoring.oPageConfigXml = new ActiveXObject("Microsoft.XMLDOM");
		vcc.authoring.oPageConfigXml.setProperty("SelectionLanguage", "XPath");
		vcc.authoring.oPageConfigXml.loadXML(sXml);
	}
}

vcc.authoring.getPageConfigXml = function() {
	if (vcc.authoring.oPageConfigXml == null)
		vcc.authoring.initPageConfigXml();		
	return vcc.authoring.oPageConfigXml;
}

vcc.authoring.getPageConfigSection = function(sSectionId, bOnlyInnerXml) {
	if (vcc.authoring.oPageConfigXml == null)
		vcc.authoring.initPageConfigXml();
	var oSectionNode = vcc.authoring.oPageConfigXml.documentElement.selectSingleNode("/configs/config[@id='" + sSectionId + "']");
	if (oSectionNode == null) {
		oSectionNode = vcc.authoring.createPageConfigSection(sSectionId);	
	}
	if (bOnlyInnerXml) {
		return oSectionNode.firstChild;
	}
	return oSectionNode;
}

vcc.authoring.createPageConfigSection = function(sSectionId) {
	if (vcc.authoring.oPageConfigXml == null)
		vcc.authoring.initPageConfigXml();
	var oSectionNode = vcc.authoring.oPageConfigXml.createElement("config");
	oSectionNode.setAttribute("id",sSectionId);
	vcc.authoring.oPageConfigXml.documentElement.appendChild(oSectionNode);
	return oSectionNode;
}

vcc.authoring.updatePageConfigSection = function(sSectionId, oInnerXml) {
	var oSectionNode = vcc.authoring.getPageConfigSection(sSectionId, false);
	if (oSectionNode.childNodes.length > 0)
		oSectionNode.text = "";
	oSectionNode.appendChild(oInnerXml);
	vcc.getElementByIdFragment("pageConfigXml", "textarea").innerText = vcc.authoring.oPageConfigXml.xml;
	vcc.authoring.oPageConfigXml = null;
}

/// <summary>
/// Returns the first parent element with the specified nodeName
/// </summary>
/// <param name="strLayer">Id of the element whose parent you want to find.</param>
/// <param name="strParentNodeName">Name of the parent node.</param>
/// <param name="iDepth">Integer specifying number of levels to iterate before "giving up". Optional, default:15</param>
/// <returns>A HTML element</returns>
vcc.authoring.getParentNode = function(oChild, strParentNodeName, iDepth) {
	iDepth = iDepth || 15;
	elmTmpParent = oChild.parentNode;
	if (!elmTmpParent)
		return;
	for (var i=0; i<iDepth; i++) {
		if (elmTmpParent.nodeName == strParentNodeName.toUpperCase())
			return elmTmpParent;
		else
			elmTmpParent = elmTmpParent.parentNode;
	}
	return false;
}

/* Configured Experience */

vcc.authoring.ce = new Object();
vcc.authoring.ce.bAlreadyCreated = false;
vcc.authoring.ce.init = function() {
    if (document.getElementById("configuredExperience") == null || vcc.authoring.ce.bAlreadyCreated)
        return;

    //Set selected models
    var oModelsText = vcc.getElementByIdFragment("txtModels", "input");
    var aModels = oModelsText.value.split(",");
    var oParent = null;
    var iCheckedModels = 0;
    for (var i = 0; i < aModels.length; i++) {
        if (document.getElementById("checkbox_model_" + aModels[i]) != null) {
            $("#checkbox_model_" + aModels[i]).attr("checked", "checked");
            iCheckedModels++;
        }
    }
    /*if (vcc.currentModel != null && iCheckedModels == 0 && document.getElementById("checkbox_model_" + vcc.currentModel) != null) {
    $("#checkbox_model_" + vcc.currentModel).attr("checked", "checked");
    }*/

    //Set selected keywords
    var oKeywordsText = vcc.getElementByIdFragment("txtKeywords", "input");
    var aKeywords = oKeywordsText.value.split(",");
    for (var i = 0; i < aKeywords.length; i++) {
        var sKeyword = aKeywords[i];
        if (sKeyword == "")
            continue;
        vcc.authoring.ce.addKeyword(sKeyword);
        //Check it in the all keywords list
        vcc.authoring.ce.showAllKeywords(null);
        var aKeywordItems = $("#ce-keywords-window li");
        $.each(aKeywordItems, function() {
            if (this.getElementsByTagName("label").item(0).innerHTML == sKeyword) {
                var oInput = this.getElementsByTagName("input").item(0);
                $("#" + oInput.id).attr("checked", "checked");
            }
        });
        vcc.authoring.ce.showAllKeywords(null);
    }

    //Set selected callout types
    var oLivesInText = vcc.getElementByIdFragment("txtLivesIn", "input");
    var aCalloutTypes = oLivesInText.value.split(",");
    for (var i = 0; i < aCalloutTypes.length; i++) {
        var sCalloutType = jQuery.trim(aCalloutTypes[i]);
        var aLivesInItems = $("#ce-lives-in li");
        $.each(aLivesInItems, function() {
            if (this.getElementsByTagName("label").item(0).innerHTML == sCalloutType) {
                var oInput = this.getElementsByTagName("input").item(0);
                $("#" + oInput.id).attr("checked", "checked");
            }
        });
    }

    //Set selected rating
    var oRatingText = vcc.getElementByIdFragment("txtRating", "input");
    if (oRatingText.value == "0") {
        $("#radio_rating_Neutral").attr("checked", "checked");
    } else if (oRatingText.value == "1") {
        $("#radio_rating_Emotional").attr("checked", "checked");
    } else if (oRatingText.value == "-1") {
        $("#radio_rating_Rational").attr("checked", "checked");
    }
    
    vcc.authoring.ce.bAlreadyCreated = true;
}

vcc.authoring.ce.updateModels = function(oCheckBox) {
    var aModelCheckBoxes = $("#ce-models input");
    var sModelTags = "";
    $.each(aModelCheckBoxes, function() {
        if (this.checked) {
            sModelTags += this.value + ",";
        }
    });
    if (sModelTags.indexOf(",") > -1)
        sModelTags = sModelTags.substring(0, sModelTags.length - 1);
    vcc.getElementByIdFragment("txtModels", "input").value = sModelTags;
}

vcc.authoring.ce.updateLivesIn = function() {
    var aLivesInCheckBoxes = $("#ce-lives-in input");
    var sLivesIn = "";
    $.each(aLivesInCheckBoxes, function() {
        if (this.checked)
            sLivesIn += this.value + ",";
    });
    if (sLivesIn.indexOf(",") > -1)
        sLivesIn = sLivesIn.substring(0, sLivesIn.length - 1);
    vcc.getElementByIdFragment("txtLivesIn", "input").value = sLivesIn;
}

vcc.authoring.ce.updateRating = function(sRating) {
	vcc.getElementByIdFragment("txtRating", "input").value = sRating;
}

vcc.authoring.ce.showAllKeywords = function(oLink) {
	vcc.authoring.toggleFloatingWindow("ce-keywords-window", oLink);	
	return false;
}

vcc.authoring.ce.toggleKeyword = function(sKeyword, bAdd) {
	if (bAdd)
		vcc.authoring.ce.addKeyword(sKeyword);
	else
		vcc.authoring.ce.removeKeyword(sKeyword);
}

vcc.authoring.ce.addKeyword = function(sKeyword) {
	//Add keyword to keywords list
	var oKeywordsList = document.getElementById("ce-keywords");
	var oLi = document.createElement("li");
	oLi.innerHTML = "<a class=\"keyword\" href=\"#\" onclick=\"vcc.authoring.ce.removeKeyword('" + sKeyword + "'); return false;\"><span>" + sKeyword + "</span></a>";
	oKeywordsList.appendChild(oLi);
	
	//Move add link to last position in list
	var oLink = document.getElementById("add-keyword-link");
	oKeywordsList.appendChild(oLink);
	
	//Update keyword text field
	vcc.authoring.ce.updateKeywords();
}

vcc.authoring.ce.removeKeyword = function(sKeyword) {
	//Remove keyword from keywords list
	var aKeywordLinks = $("#ce-keywords a.keyword span");
	var oLinkToRemove = null;
	$.each(aKeywordLinks, function() {
		if (this.innerText == sKeyword) {
			oLinkToRemove = this.parentNode.parentNode;
		}		
	});
	if (oLinkToRemove != null)
		oLinkToRemove.parentNode.removeChild(oLinkToRemove);
		
		
	//Uncheck it in the all keywords list
	var aKeywordItems = $("#ce-keywords-window li");
	$.each(aKeywordItems, function() {
		if (this.getElementsByTagName("label").item(0).innerText == sKeyword) {
			this.getElementsByTagName("input").item(0).checked = false;
		}
	});
	
	//Update keyword text field
	vcc.authoring.ce.updateKeywords();
}

vcc.authoring.ce.updateKeywords = function() {
	var aKeywordLinks = $("#ce-keywords a.keyword span");
	var sKeywords = "";
	$.each(aKeywordLinks, function() {
		sKeywords += this.innerHTML + ",";
	});
	if (sKeywords.indexOf(",") > -1)
		sKeywords = sKeywords.substring(0, sKeywords.length - 1);
	vcc.getElementByIdFragment("txtKeywords", "input").value = sKeywords;
}

/* EDM */

vcc.authoring.showEDM = function() {
	vcc.authoring.toggleFloatingWindow("edm-settings", null);
}

/* Custom meta tags */

vcc.authoring.getMetaTagXml = function() {
	var oTextBox = document.getElementById("ctl00_metaTagsControl_customTagsXml");
	var sXml = oTextBox.innerText;
	if (sXml == "")
		return null;
	var oXml = new ActiveXObject("Microsoft.XMLDOM");
	oXml.setProperty("SelectionLanguage", "XPath");
	oXml.loadXML(sXml);
	return oXml;
}

vcc.authoring.updateMetaTagXml = function(oXml) {
	var oTextBox = document.getElementById("ctl00_metaTagsControl_customTagsXml");
	oTextBox.innerText = oXml.xml;
}

vcc.authoring.updateMetaTagId = function(iNodePosition, oTextField) {
	var oXml = vcc.authoring.getMetaTagXml();
	var sValue = oTextField.value;
	if (sValue == "keywords" || sValue == "description" || sValue == "index" || sValue == "follow") {
		alert("\"" + sValue + "\" is a reserved meta tag name and can not be used here.");
		oTextField.value = "";
		return false;
	}
	oXml.documentElement.selectSingleNode("/metatags/metatag[position() = '" + iNodePosition + "']").setAttribute("id", oTextField.value);
	vcc.authoring.updateMetaTagXml(oXml);
}

vcc.authoring.updateMetaTagValue = function(iNodePosition, oTextField) {
	var oXml = vcc.authoring.getMetaTagXml();
	oXml.documentElement.selectSingleNode("/metatags/metatag[position() = '" + iNodePosition + "']").text = oTextField.value;
	vcc.authoring.updateMetaTagXml(oXml);
}

vcc.authoring.removeMetaTag = function(iNodePosition) {
	if (confirm("Are you sure you want to remove this meta tag?")) {
		var oXml = vcc.authoring.getMetaTagXml();
		var oNode = oXml.documentElement.selectSingleNode("/metatags/metatag[position() = '" + iNodePosition + "']");
		oNode.parentNode.removeChild(oNode);
		vcc.authoring.updateMetaTagXml(oXml);
		vcc.authoring.renderMetaTagsTable();
	}
}

vcc.authoring.addMetaTag = function() {
	var oXml = vcc.authoring.getMetaTagXml();
	var oNode = oXml.createElement("metatag");
	oNode.setAttribute("id", "");
	oNode.text = "";
	oXml.documentElement.appendChild(oNode);
	vcc.authoring.updateMetaTagXml(oXml);
	vcc.authoring.renderMetaTagsTable();
}

vcc.authoring.renderMetaTagsTable = function() {
	var oXml = vcc.authoring.getMetaTagXml();
	var oNodes = oXml.documentElement.selectNodes("/metatags/metatag");
	var bCustomMetaTagExists = false;
	var sHtml = "<table cellspacing=\"0\"><tbody>";
	var sMetaTagsHtml = "";
	for (var i = 0; i < oNodes.length; i++) {
		var sId = oNodes[i].getAttribute("id");
		if (sId != "keywords" && sId != "description" && sId != "index" && sId != "follow") {
			bCustomMetaTagExists = true;
			var sValue = oNodes[i].text.replace("\"", "&quot;");
			sId = sId.replace("\"", "&quot;");
			sMetaTagsHtml += "<tr id=\"metatag_" + (i + 1) + "\"><td class=\"text\"><input onblur=\"vcc.authoring.updateMetaTagId(" + (i + 1) + ", this);\" type=\"text\" value=\"" + sId + "\" class=\"title\" /></td><td class=\"value\"><input type=\"text\" onblur=\"vcc.authoring.updateMetaTagValue(" + (i + 1) + ", this);\" value=\"" + sValue + "\" class=\"value\" /></td><td class=\"delete\"><a href=\"#\" onclick=\"vcc.authoring.removeMetaTag(" + (i + 1) + ");return false;\"><img src=\"/_layouts/VolvoCars.Sharepoint.Features.Site3/Images/Authoring/DropdownSearch/icon_trashcan.gif\" alt=\"Delete\" /></a></td></tr>";
		}
	}
	if (bCustomMetaTagExists)
		sHtml += "<tr><th>Name</th><th>Value</th><th></th></tr>";
	sHtml += sMetaTagsHtml;
	sHtml += "</tbody></table>";
	$("#custom-meta-tags table").replaceWith(sHtml);
}


