var map = null;
var xmlNode=-1;
var pinid=1;
var xmldoc=null;
var shortcode=null
var longcode=null;
var codetab=1;
var id=-1;
var layerid=1;
var polyid=1;
var xmltree=null;
var xmlabout=null;
var numberOfNodes;
var refTopic;
var refsTable = null;
var xmlRefDoc=null;
var is3dLoading=false;
var alerttext;
var reloadRef = true;

var browser;

//Ignoring all errors
//Remove this when debugging
window.onerror = function(error, source, line)
{
    return true;
}

function onPageLoad() //fires when the page first loads
{
    if (window.ActiveXObject) { browser = 'ie'; }
    else if (document.implementation && document.implementation.createDocument) { browser='moz'; } 
	try{LoadTree();}
	catch(err){}
	try{LoadSnippets();}
	catch(err){}
	try{PopAbout();}
	catch(err){}
	if(map==null)
	{
	   id="100";
	   ShowTab('content1');
	   setTimeout('DoTreeClick()',100);
	}
}
function LoadSnippets() //puts all code snippets in an XMLDocument for easy retreival
{
    var xmlhttp = GetXmlHttp();
    xmlhttp.open("GET", "Snippets.xml" ,true);
    xmlhttp.onreadystatechange=function()
    {
        if (xmlhttp.readyState == 4)
        {
            xmldoc = xmlhttp.responseXML;
            xmlhttp	= null;
        }
    }
    xmlhttp.send(null);
}
function LoadTree() //loads the  XML file for the task tree
{
    var xmlhttp = GetXmlHttp();
    xmlhttp.open("GET", "Tree.xml" ,true);
    xmlhttp.onreadystatechange=function()
    {
        if (xmlhttp.readyState == 4)
        {
            xmltree = xmlhttp.responseXML;
            PopTree();
            xmlhttp	= null;
        }
    }
    xmlhttp.send(null);
}
function PopTree() //creates the Task Tree based on the nodes in the xmltree
{
var whatsnew = "<br><div onclick='doWhatsNew()'><img src='./img/new.gif' /><br><b>What's new in the latest release?</b></div>";
whatsnew = whatsnew + "<br><div>";//<li><a href='#' onclick='GetDefaultMap();doClick(2);'>Map Control Url for India</a>.</li>";
whatsnew = whatsnew + "<li><a href='http://msdn.microsoft.com/en-us/library/bb429619.aspx' targer='_blank'>Map Control Documentation</a></li>";
whatsnew = whatsnew + "<li><a href='http://msdn.microsoft.com/en-us/library/cc980922.aspx' targer='_blank'>Web Services Documentation</a></li>";
whatsnew = whatsnew + "<li>To use Web Services <a href='mailto:veindia@microsoft.com?subject=Request for creation of App ID to use VE Web Services.&body=To create a new AppID, Send your information along with this mail. The required details are *Application name, *Description, *Company name, *Country/region, *Email address(We ll only contact you if there are breaking changes to the APIs). Send us your Website also(Optional information).'>apply</a> here for App ID. &nbsp; By doing so, you agree to <a href='http://search.live.com/developers/tou.aspx' targer='_blank'>API terms of use</a>.</li>";
	numberOfNodes = xmltree.getElementsByTagName("node").length+1;
    var strTree = "<div><b>&nbsp;I want to:</b></div>";
	for (x=0;x<numberOfNodes-1;x++)
	{
		var nodeNumber = xmltree.getElementsByTagName("node")[x].attributes[0].nodeValue;
		var nodetitle = xmltree.getElementsByTagName("node")[x].attributes[1].nodeValue;
		
		strTree+="<div id='node"+nodeNumber+"' class='SDKtreenode' onclick='DoExpandoClick("+nodeNumber+")'><div class='state' id='hidden"+nodeNumber+"'></div>";
		strTree+="<img id='img"+nodeNumber+"' src='./img/expand.gif'>&nbsp;"+nodetitle+"</div>";
		strTree+="<div id='sub"+nodeNumber+"' class='SDKtreehidden'>";
		
		for (sn=0;sn<xmltree.getElementsByTagName("node")[x].childNodes.length;sn++)
		{
			if (xmltree.getElementsByTagName("node")[x].childNodes[sn].nodeName=="subnode" 
					&& xmltree.getElementsByTagName("node")[x].childNodes[sn].hasChildNodes() 
					&& xmltree.getElementsByTagName("node")[x].childNodes[sn].childNodes[0].nodeName=="#text")
				{
					var snid = xmltree.getElementsByTagName("node")[x].childNodes[sn].attributes[0].nodeValue;
					var sntitle = xmltree.getElementsByTagName("node")[x].childNodes[sn].childNodes[0].nodeValue;
					strTree+="<div id="+snid+" class='SDKtreesubnode' onclick='ChangeMap(event)'>"+sntitle+"</div>";	
				}
		}
		strTree+="</div>";
	}
	strTree+=whatsnew;
	var tree = document.getElementById('tree');
	tree.innerHTML=strTree;
	SelectFirstTreeItem();
}
function SelectFirstTreeItem() //selectes the first item in the Task Tree
{
	DoExpandoClick(1);
	xmlNode=1;
	document.getElementById('100').className="SDKtreeselected";
	if (xmldoc!=null)
	{
		ShowCode(); 
		GetRef();
		doClick(1);
	}
}
function PopAbout() //creates the "Learn More" tab content from the About.xml file
{
    var xmlhttp = GetXmlHttp();
    xmlhttp.open("GET", "About.xml" ,true);
    xmlhttp.onreadystatechange=function()
    {
        if (xmlhttp.readyState == 4)
        {
            xmlabout = xmlhttp.responseXML;
            ShowAbout();
            xmlhttp	= null;
        }
    }
    xmlhttp.send(null);    
}
function ShowAbout() //shows the content when the "Learn More" tab is clicked
{
	var about = document.getElementById('learnmore');
	about.innerHTML=xmlabout.getElementsByTagName("HtmlText")[0].childNodes[0].nodeValue;
}

function doClick(t) //handles clicks of the tabs--from map to reference to snippet, etc.
{
    //set the look of the tab itself
    document.getElementById("contentTab1").className = "backContentTab";
    document.getElementById("contentTab2").className = "backContentTab";
    document.getElementById("contentTab3").className = "backContentTab";
    document.getElementById("contentTab4").className = "backContentTab";
    document.getElementById("contentTab" + t).className = "activeContentTab";

    //..and if the custom user control is currently shown, remove it
    RemoveMyControl();
    //...and hide the alert box if it is open
    HideAlert();

    //Set up the hierarchy for adCenter tracking

    var hierarchy = 'vesdk/TAB/';

	if (t==4) //learn more page
	{
	    HideTab('ref');
	    HideTab('code');
	    HideTab('SDKmap');
	    HideTab('codebutton');
        ShowTab('learnmore');
        hierarchy += 'LearnMore';
	}
	else if (t==3) //reference page
	{
        if (reloadRef)
            GetRef();

	    HideTab('code');
	    HideTab('SDKmap');
	    HideTab('codebutton');
	    HideTab('learnmore');
        ShowTab('ref');

        ShowRef();
        hierarchy += 'Reference';
	}
	else if (t==2)//code page
	{
		if (xmldoc!=null)
		{
			ShowTab('code');
	        HideTab('SDKmap');
            HideTab('ref');
	        HideTab('learnmore');
	    	ShowTab('codebutton');
	    	hierarchy += 'SourceCode';
		}
	}
	else if (t==5) //Shows the what's new page
	{
	    HideTab('code');
	    HideTab('SDKmap');
	    HideTab('codebutton');
	    HideTab('learnmore');
        ShowTab('ref');
        hierarchy += 'WhatsNew';
	}
	else //show the map
	{
	    ShowTab('SDKmap');
		HideTab('code');
        HideTab('ref');
        HideTab('learnmore');
	    HideTab('codebutton');
	    hierarchy += 'ShowMe';
	}

		if (eventAnalytics != null) //Report whatever is in the hierarchy object with the following instrumentation
	{
	    eventAnalytics.PageViewRegistered = false;
	    eventAnalytics.SetView(1, hierarchy); //build view hierarchy in previous steps and sub in the string
	    eventAnalytics.TrackPage();
	}

}
function HideTab(id) //generic handler for hiding an element
{
    document.getElementById(id).style.visibility="hidden";
    document.getElementById(id).style.display="none";
}
function ShowTab(id)//generic handler for showing an element
{
    document.getElementById(id).style.visibility="visible";
    document.getElementById(id).style.display="block";
}
function ShowCode() //shows the Code tab content
{
    try
    {
        snip = xmldoc.selectNodes("/demos/demo[id='"+id+"']")[0];
	    longcode = snip.getElementsByTagName("long")[0].childNodes[0].nodeValue;
	    var codebox = document.getElementById("code");
	    codebox.innerText = longcode;
	}catch(e)
	{
	    //Safari 2 does not support xpath. Have to use a loop to search for the correct node.
	    var codebox = document.getElementById("code");
	    codebox.innerText = SearchForNode(id);
	}
}
function SearchForNode(id)
{
    var s = "";
    try
    {
        var nodes = xmldoc.getElementsByTagName("demo");
        for(var i=0;i<nodes.length;i++)
        {
            var n = nodes[i].getElementsByTagName("id")[0];
            if(n && n.childNodes && n.childNodes[0] && n.childNodes[0].nodeValue == id)
            {
                s = nodes[i].getElementsByTagName("long")[0].childNodes[0].nodeValue;
            }
        }
    }catch(e){}
    return s;
}
function GetRef(link) //shows the reference tab content
{
	//if (codetab==3) document.getElementById("refbox").className = "ref";
	if(!link)
	    link = refTopic;
	
	document.getElementById("refframe").src = "http://msdn2.microsoft.com/en-us/library(d=ide)/"+link;
	reloadRef = false;
}
function ShowRef()
{
	var s = "<a href='http://msdn2.microsoft.com/en-us/library/"+refTopic+"' target='_blank'>Click here to open the Bing Map Control SDK in a new window.</a><br>";
    if(refsTable != null)
    {
        s += "<br>Click on the links below to see other related references.<br>";
        var name;
	    for(name in refsTable)
	    {
	        s+="<a href='#' onclick=\"javascript:GetRef('"+refsTable[name]+"');\">"+name+"</a><br>";
	    }
    }
    DoAlert(s);
}

function GetLinks() //deprecated - should be safe to delete
{
	var text = xmldoc.getElementsByTagName("links")[xmlNode].childNodes[0].childNodes[0].firstChild.nodeValue;
	var link = xmldoc.getElementsByTagName("links")[xmlNode].childNodes[0].childNodes[1].firstChild.nodeValue;
}
function DoExpandoClick(id) //handles changes when the user expands/collapese a node in the Task Tree.
{
	var expimg = "./img/collapse.gif";
	var colimg = "./img/expand.gif";
	

	//collapse all nodes first
	for (var s=1; s<numberOfNodes; s++)
	{
		if (s!=id)
		{	
			var d = document.getElementById("node"+s);
			var nodes = d.childNodes[0];
			nodes.id = "hidden"+s;
			document.getElementById("sub"+s).className="SDKtreehidden";
			document.getElementById("img"+s).src=colimg;
		}
	}
	//now expand the one we want
	var div = document.getElementById("node"+id);
	var img = document.getElementById("img"+id);
	var subnode = document.getElementById("sub"+id);
	var hiddennode = div.childNodes[0];
	if (hiddennode.id=="hidden"+id)//we are collapsed
	{
	
		subnode.className="SDKtreeshown";
		hiddennode.id="shown"+id;
		img.src=expimg;
	}
	else //we are expanded
	{
		subnode.className="SDKtreehidden";
		hiddennode.id="hidden"+id;
		img.src=colimg;
	}
}
function Do3DWait() //HACK required for some 3D-mode UI changes
{
    if (!is3dLoading)
    {
        DoAlert(alerttext);
       // is3dLoading=true;
    }
    else
    {
       setTimeout('Do3DWait();',1500);
    }
}
function DoAlert(text) //this is used for all UI notifications, including the new alerts that contain UI elements.
{
	var d=document.getElementById("alertdiv");
	d.style.visibility="visible";
	document.getElementById("alerttext").innerHTML = text;
    
    addShim(d,'alertshim');
}
function addShim(el,id) //creates the required 3D shim for an element. Used espcially with the DoAlert() function
{
    var shim = document.getElementById('alertshim');
    if (!shim) 
        shim = document.createElement("iframe"); 
    shim.id = id;         
    shim.frameBorder = "0"; 
    shim.style.position = "absolute";
    shim.style.zIndex = "1";
    shim.style.top  = el.offsetTop + "px";
    shim.style.left = el.offsetLeft + "px";
    shim.style.width  = el.offsetWidth + "px";
    var h = parseInt(document.getElementById("alerttitle").offsetHeight) +
	        parseInt(document.getElementById("alerttext").offsetHeight);
    if (h > 0)
	    shim.style.height = h + "px";
	else
	    shim.style.height = parseInt(document.getElementById("alerttitle").style.height) +
	                        parseInt(document.getElementById("alerttext").style.height) + "px";


    el.shimElement = shim; 
    el.parentNode.insertBefore(shim, el);
}
function HideAlert() //hides the custom Alert box
{
    document.getElementById('alertdiv').style.visibility='hidden';
    var myShim = document.getElementById("alertshim");            
    if (myShim!=null) myShim.parentNode.removeChild(myShim);            
    myShim = null;
}
function doCopy() //copies the code snippet to the clipboard.
{
	if (window.clipboardData) 
	{	
	window.clipboardData.setData("Text", longcode);
	}
	else
	{
	var t = document.getElementById("TextToCopy");
				t.value = longcode;
				t.focus();
				t.select();				
	DoAlert("Your browser does not allow direct copies to the clipboard. The code has been selected. "+
				"Please press Control-C to copy it to your clipboard.");
				}
}
function doWhatsNew() //brings up the What's New topic
{
    GetRef('bb412561.aspx');
	//document.getElementById("refframe").src = "http://dev.live.com/virtualearth/sdk/ref/HTML/WhatsNew.htm";
	
	doClick(3);
	HideAlert();
	reloadRef = true;
}
function startLoading() 
{
    is3dLoading=true;
}
function doneLoading()
{
    is3dLoading=false;
}

function GetXmlHttp()
{
    var req = null;

    // Check for the W3C Standard way of invoking an XMLHTTP Object first
    if (window.XMLHttpRequest)
    {
        req = new XMLHttpRequest();
    }
    else if (window.ActiveXObject)
    {
        try
        {
            req = new ActiveXObject('Msxml2.XmlHttp.6.0');
        }
        catch(everything)
        {
            try
            {
                req = new ActiveXObject('Msxml2.XmlHttp.3.0');
            }
            catch(everything)
            {
                try
                {
                    req = new ActiveXObject('Msxml2.XMLHTTP');
                }
                catch(everything)
                {
                    try
                    {
                        req = new ActiveXObject('Microsoft.XMLHTTP');
                    }
                    catch(everything) { }
                }
            }
        }
    }
    else
    {
        throw('XMLHTTP Required: Browser not supported');
    }

    return req;
}