﻿/// <reference name="lssdk_forms.js" />
/// <reference name="lssdk_xml.js" />

// Page level variables
var xmlSDK = null;
var selectedSectionID = -1;
var selectedDemoID = -1;
var selectedTabID = 'showMeTab';
var selectedContentID = 'showMeContent';
var hierarchy = '';
var browser = '';
var errorCount = 0;

// Handles node link clicks (set text value of txtPath)
function setUpRequest(path)
{
    var txtPath = document.getElementById("txtPath");
    txtPath.value = path.toString();  
}

// Handles collapse/expand of content areas.
function OpenClose(elem)
{
    var idVariable = document.getElementById(elem);
    // Change height of content area on click.
    if (idVariable.style.height=="")
    {
        idVariable.style.height="12px";
    }
    else
    {
        idVariable.style.height="";
    }
}

// Loads the feature tree XML document and populate the tree in the UI
function loadSDK() {

    // Load the SDK XML
    browser = this.getBrowser();
    xmlSDK = this.createXMLDoc();
    xmlSDK.load("SDK.xml");
    
    // Populate the UI from the XML data
    this.populateFeatureTree();    
}

// Populates the node of the feature tree with data.
function populateFeatureTree() {
    
    var xmlNodes = xmlSDK.getElementsByTagName("section");
    var strTree = "<div><b>I want to:</b></div>";
    
    for(var i = 0; i < xmlNodes.length; i++) {
        
        // Get the node ID and title
        var nodeID = xmlNodes[i].getAttribute("id");
        var nodeTitle = xmlNodes[i].getAttribute("description");
        
        // Build the title node
        strTree += "<div id='node" + nodeID + "' class='treenode' onclick='javascript:showSection(" + nodeID + ");'>";
        strTree += "<img id='img" + nodeID + "' src='./img/expand.gif'/>&nbsp;" + nodeTitle + "</div>";
        strTree += "<div id='sub" + nodeID + "' class='collapsedNode'>";
		        
		// Populate the sub nodes
		for(var j = 0; j < xmlNodes[i].childNodes.length; j++) {
            var currentNode = xmlNodes[i].childNodes[j];
		    if (currentNode.nodeName == "demo") {
		        
		        // Get the subnode ID and Title
		        var subNodeID = currentNode.getAttribute("id");
		        var subNodeTitle = currentNode.getAttribute("description");
		        
		        // Build the subnode HTML
		        strTree+="<div id='" + subNodeID + "' class='treesubnode' onclick='javascript:showDemo(" + subNodeID + ")'>" + subNodeTitle + "</div>";	
				
		    }
		}      
    
        // Close the subnode
        strTree += "</div>";
        
    }	
    
    // Add reference to "What's New" item.
    //strTree +="<div style=\"margin-top:10px\"><a style=\"color:#fffff; text-decoration:none;\" href=\"http://msdn2.microsoft.com/en-us/library/bb447720.aspx\"><img src=\"./img/new.gif\" /><br /><b>What's new in the latest release?</b></a></div>";
    
    // Close the HTML tags and set the innerHTML of the tree element.
    strTree += "</div>";
    document.getElementById("tree").innerHTML = strTree;
   
    // Show the first Section / Demo by default
    this.showSection(1);
   
}

// Hides or shows the supplied section.
function showSection(id) {

    // Hide the demos of the previously selected section
    if (selectedSectionID > -1) {
        var currentSubNode = document.getElementById("sub" + selectedSectionID);
        var currentImageNode = document.getElementById("img" + selectedSectionID);
        if (currentSubNode != null) currentSubNode.className = 'collapsedNode';
        if (currentImageNode != null) currentImageNode.src = "./img/expand.gif";
    }
    
    // Save the new selected section ID
    selectedSectionID = id;

    // Show the demos for this section
    if (selectedSectionID > -1) {
        var subNode = document.getElementById("sub" + selectedSectionID);
        var imageNode = document.getElementById("img" + selectedSectionID);
        if (subNode != null) subNode.className = 'expandedNode';
        if (imageNode != null) imageNode.src = "./img/collapse.gif";
    
        // Select the first demo under this section
        index = 0;
        if (browser == 'moz') index = 1; // XPath in Firefox is 1 based 
        var firstDemoNode = this.selectSingleNode(xmlSDK, "//section[@id='" + selectedSectionID + "']/demo[" + index + "]");
        if (firstDemoNode != null) this.showDemo(firstDemoNode.getAttribute("id"));
    }        
}

// Displays the content for the specified feature
function showDemo(id) {

    // Unselect the previously selected demo
    if (selectedDemoID > -1) {
        document.getElementById("txtDemoID").value = "";
        var oldNode = document.getElementById(selectedDemoID);
        if (oldNode != null) oldNode.className = 'treesubnode';        
    }
    
    // Save the new demo ID
    selectedDemoID = id;
    
    // Select the new demo
    if (selectedDemoID > -1) {
    
        // Show the node as selected
        var node = document.getElementById(selectedDemoID);
        if (node != null) node.className = 'selectedsubnode';
        
        // Record analytics
        var section = this.selectSingleNode(xmlSDK, "//section[@id='" + selectedSectionID + "']");
        var hierarchy = ("userdatasdk/toc/" + section.getAttribute("description") +"/" + node.innerHTML);
      
        // Get the demo ID.
        var demoNode = this.selectSingleNode(xmlSDK, "//demo[@id='" + selectedDemoID + "']");
        document.getElementById("txtDemoID").value = demoNode.getAttribute("id");
        
        // Populate the language drop-down with valid values for this demo
        var comboLanguage = document.getElementById("comboLanguage");
        var selectedLanguage = (comboLanguage.value != null) ? comboLanguage.value : "";
        if (comboLanguage.options.length > 1) comboLanguage.options.length = 0;
        var sampleCodeNode = this.selectSingleNode(xmlSDK, "//demo[@id='" + selectedDemoID + "']/sampleCode");
        if (sampleCodeNode != null) {
           var defaultLanguage = sampleCodeNode.getAttribute("default");
           var codeSampleNodes = sampleCodeNode.getElementsByTagName("code");
           comboLanguage.options.length = codeSampleNodes.length;
           for(var i = 0; i < codeSampleNodes.length; i++) {
                var language = codeSampleNodes[i].getAttribute("language");
                comboLanguage.options[i].value = language;
                comboLanguage.options[i].text = language;
                if ((selectedLanguage.length > 0 && language == selectedLanguage) || (selectedLanguage.length == 0 && language == defaultLanguage)) comboLanguage.options[i].selected = true;
           }
        }    
        
        // Refresh the source code 
        this.refreshSampleCode(); 
        
        // Refresh the show me content
        this.refreshMainContent();
        
        // Refresh the reference content
        this.refreshRefContent();     

        // Update the analytics
	    if (eventAnalytics !=null)
		reportAnalytics(hierarchy);  
    }    
}

// NEW. Displays the reference content for the selected demo.
function refreshRefContent()
{
    // Get the demo ID.
    // This code takes the demo ID and displays the URL specified in sdk.xml.
    // It had to be removed because MSDN now redirects to http rather than https,
    // which caused errors on our site.
    //var demoNode = this.selectSingleNode(xmlSDK, "//demo[@id='" + selectedDemoID + "']");
    //document.getElementById("refFrame").src = demoNode.getAttribute("refUrl");
    
    // This code points to a "ref" page for the topic.
    var refFrame = document.getElementById("refFrame");
    var path = "Refs/" + selectedDemoID + "_ref.aspx";    
    setHtml(refFrame, path);
}

// NEW. Displays the main content HTML for the selected demo.
function refreshMainContent()
{
    var mainContent = document.getElementById("mainContent");
    var path = "ShowMe/" + selectedDemoID + ".aspx";    
    setHtml(mainContent, path);
}

// Displays sample code for the selected demo / language
function refreshSampleCode() {
    // Get the selected language
    var comboLanguage = document.getElementById("comboLanguage");
   
    // Get the area where source code content will be located
    var codebox = document.getElementById("codebox");
   
    // Get the sample code for the selected demo / language
    var sampleCodeNode = selectSingleNode(xmlSDK, "//demo[@id='" + selectedDemoID + "']/sampleCode/code[@language='" + comboLanguage.value + "']");
    var code = "[Source Code Unavailable]";
    if (sampleCodeNode != null && sampleCodeNode.childNodes.length > 0) {
        
        // Get the code
        code = this.getCDATAText(sampleCodeNode);
        
        // Get rules for the language and the field mask delimiter to use for the language
        var languageDefNode = selectSingleNode(xmlSDK, "//languages/language[@name='" + comboLanguage.value + "']");
        var delimiter = languageDefNode.getAttribute("fieldDelimiter");
        var sdkURL = languageDefNode.getAttribute("SDKUrl");
        
        // Set the URL for the associated SDK if one is specified. Also hide/show the Download button
//        var buttonDownloadSDK = document.getElementById("buttonDownloadSDK");
//        var buttonCopySourceCode = document.getElementById("buttonCopySourceCode");
//        if (sdkURL == null || sdkURL.length == 0) {
//			buttonDownloadSDK.href = "";
//			buttonDownloadSDK.style.display = "none";
//			buttonDownloadSDK.style.visibility = "hidden";
//			buttonCopySourceCode.style.right = "0px";
//        }
//        else {
//			buttonDownloadSDK.href = sdkURL;
//			buttonDownloadSDK.style.display = "inline";
//			buttonDownloadSDK.style.visibility = "visible";	
//			buttonCopySourceCode.style.right = "100px";
//        }
        
        // Replace placeholders in the source code with parameter values by looping through each
        // setting defined in the SDK.xml file and searching for a placeholder of the same name
        var optionsNode = selectSingleNode(xmlSDK, "//options");
        var options = optionsNode.getElementsByTagName("option");
        for(var i = 0; i < options.length; i++) {
            var settings = options[i].getElementsByTagName("setting");
            for(var j = 0; j < settings.length; j++) {
            
				// Get information about how to retrieve the current setting from the HTML form
                var settingName = settings[j].getAttribute("name");
                var settingControlID = settings[j].getAttribute("controlID");
                var settingControl = document.getElementById(settingControlID);
                if (settingControl == null) settingControl = document.getElementsByName(settingControlID)[0];
				if (settingName == "#text") settingName = options[i].getAttribute("name");
				
				// Get syntax rules for this setting
				var replaceRule = selectSingleNode(languageDefNode, "syntaxRule[@option='" + settingName + "' and @type = 'replace']");
				var prependRule = selectSingleNode(languageDefNode, "syntaxRule[@option='" + settingName + "' and @type = 'prepend']");
				var appendRule = selectSingleNode(languageDefNode, "syntaxRule[@option='" + settingName + "' and @type = 'append']");
		
		        // CLEANUP
				// Get the current setting
				//var formValue = this.getFormValue(settingControl, delimiter, prependRule, appendRule);
            
				// Apply any ConcatStart, ConcastEnd and Replace syntax rules
				if (replaceRule != null) {
					var find = replaceRule.getAttribute("find");
					while(formValue.indexOf(find) >= 0) {
						formValue = formValue.replace(find, this.getNodeText(replaceRule));
					}
				}
				
				// Replace the marker with the value
				var settingMarker = "{{" + settingName + "}}";
				while(code.indexOf(settingMarker) >= 0) {
	                code = code.replace(settingMarker, formValue);
				}
				             
            }
        }
        
    } 
   
    // Set the source code text
    setText(codebox, code);
    
    // Resize the codebox
    this.resizeCodebox();
    
}

// Highlights the contents of the source code box
function selectSourceCode() {
    var codebox = document.getElementById("codebox");
    if (codebox != null) codebox.select();
}

// Selects the specified tab index in the UI
function selectTab(tabID, contentID) {
    // Unselect the old tab
    if (selectedTabID.length > 0) {
        var oldTab = document.getElementById(selectedTabID);
        if (oldTab != null) oldTab.className = "inactiveTab";
    }
    
    // Hide the old content
    if (selectedContentID.length > 0) {
        var oldContent = document.getElementById(selectedContentID);
        if (oldContent != null) {
            oldContent.style.visibility = "hidden";
            oldContent.style.display = "none";
        }
    }
  
    
    // Save the new selected tab ID and content
    selectedTabID = tabID;
    selectedContentID = contentID;
    
    // Refresh the source code if switching to the source code tab
    if (selectedTabID == 'sourceCodeTab') refreshSampleCode();
    
    // Show the new selected tab
    if (selectedTabID.length > 0) {
        var newTab = document.getElementById(selectedTabID);
        if (newTab != null) newTab.className = "activeTab";
    }
    
     // Show the new content
    if (selectedContentID.length > 0) {
        var newContent = document.getElementById(selectedContentID);
        if (newContent != null) {
            newContent.style.visibility = "visible";
            newContent.style.display = "block";
        }
    }

    //Record the new tab for analytics
    var hierarchy = ("userdatasdk/tab/" + newTab.innerHTML);
    
    // Make sure the results frame or code is positioned correctly (switching tabs can knock the sizing off)
    if (selectedTabID == 'sourceCodeTab')
        this.resizeCodebox();

    // Update the analytics
	if (eventAnalytics !=null)
		reportAnalytics(hierarchy);   
        
}

// Reports events back to adCenter Analytics
function reportAnalytics(hierarchy){
	    eventAnalytics.PageViewRegistered = false;
	    eventAnalytics.SetView(1, hierarchy); 
	    eventAnalytics.TrackPage();
}

// Resizes the source code box. For some reason, in IE, the codebox will resize. This will set it back.
function resizeCodebox() {
    if (selectedTabID == 'sourceCodeTab') {
		// Position the source code box (for some reason, on IE, it doesn't size correctly so we have to do it manually)
		var contentArea = document.getElementById("tabsContent");
		var codebox = document.getElementById("codebox");
		var widthOffset = (browser == 'moz') ? 2 : 4;
		var heightOffset = (browser == 'moz') ? 29 : 32;
		codebox.style.width = (contentArea.offsetWidth - widthOffset) + "px";
		codebox.style.height = (contentArea.offsetHeight - heightOffset) + "px";
    }
 }

// Resets the query text and re-submits
function resubmitQuery(queryText) {
    document.getElementById("textQuery").value = queryText;
    executeSearch();
}

// Copies the provided text to the clipboard
function copyCodeToClipboard(text) {
	var codeTextbox = document.getElementById("codebox");
	if (window.clipboardData) window.clipboardData.setData("Text", getText(codeTextbox));
}

// Event handler - fired when a key is pressed while focus is on the search query text box. This waits for the Enter key to be pressed.
// If it is, it executes the search. 
function checkExecuteSearch(e) {
	var keyNum = (browser == 'moz') ? e.which : e.keyCode;
	if (keyNum == 13) executeSearch();
}


