//Test version of javscript utils
var proxy = "http://specials.uk.msn.com/proxy.aspx?cp-documentid=";
var loadingImg = '<img src="http://estc.msn.com/br/intl/spec/fr-fr/spacevision/image/1/loading2.gif">';
var spaceListFeed = "http://spaces.live.com/changes.aspx";
var feedFrom = "change"; // value is 'change|interested'
var xmlhttpChanges = null;
var xmlhttp = null;     
var map = null;
var debug=false;
var stop = false;
var clientBrowser;
var waitDelay = 1000; // milliseconds
var shape = null;
var max = 0;
var arrShapes=new Array();
var resultObj=new Object();
var searchValid=true;
var maxBubblesOnScreen = 2;

//Points to the current profile being fetched
var profilePointer=0;
var arrChanges=new Array();

//Global variable used to handle state
var changesCallbackComplete=false;
var profileCallbackComplete=false;
var readyToFindNextProfile=true;

//photo move
var photoMaxWidth = 60;
var photoMaxHeight = 70;
var photoMove = null;
var photoMoveSpeed = 10;
var photoMoveInterval = 100;
var photoLeft = 0;
var photoImgWidth = 30;

//show no3D install info
var showNo3DInfo = false;
var firstShow3D = true;

//Is false until something awful happens, then javascript should exit
var fatalError=false; 
	
//=====common function ==========================================================================================================================
function $(id)
{
    return document.getElementById(id);
}

function errorHandler(p_errorMessage)
{
	//alert("Sorry, we've had a problem serving this page.\n\n"+p_errorMessage);
	return;
}   

function checkValue(value)
{ 
    try
    {
        if(value.replace(/\s/g,"")=="") 
        {
            return false;
        }
        else
        {
            return true;
        }
    }
    catch(Error)
	{
	    return false;
	}  
}

//auto site image's size for bubble photo
function resizeImage(ImgD, maxwidth, maxheight)
{  
   var image=new Image(); 
   image.src=ImgD.src;  
   
   if (!maxwidth) maxwidth = photoMaxWidth;
   if (!maxheight) maxheight = photoMaxHeight;
   
   if(image.width>0 && image.height>0)
   {  
        if(image.width/image.height>=maxwidth/maxheight)
        {  
             ImgD.width=maxwidth;  
             ImgD.height= (image.height*maxwidth)/image.width;  
        }  
        else
        {  
             ImgD.height=maxheight;  
             ImgD.width= (image.width*maxheight)/image.height;       
         }  
    }  
} 

//HTML encode
function htmlEndcode(str)
{
    return str.replace(/[<>]/g," ");
}

//=====xml function ==========================================================================================================================
// Generate a XmlDom Object according to the givin 'xmlString' parameter
function GenerateXMLDOC(xmlString, async)
{
    var dom = null; 
    
    if(async==null)
    {
        async=true;
    }
                
    if(clientBrowser=='Mozilla' || clientBrowser=='Opera') 
    { // Mozilla
        try
        {
           dom = new DOMParser().parseFromString(xmlString,"text/xml");
           dom.async=async;
        }
        catch(e)
        { 
           dom = null;
        }
    }
    else if(clientBrowser=='IE 6' || clientBrowser=='IE 7' || clientBrowser=='unknow') 
    { // IE6 or IE7 or something else
        try 
        {
            dom = new ActiveXObject("Msxml2.DOMDocument");
            dom.async=async; 
            dom.loadXML(xmlString);
        } 
        catch (e) 
        {
            dom = null;
        }
    }  
    
    if(dom == null)
    {
        errorHandler('failed to Cenerate XMLDocument Object');
    }
    return dom;
}

// Check the client side web browser
function CheckUserWebBrowser()
{
     var userAgent = window.navigator.userAgent;
     if(userAgent.indexOf('MSIE 7.0') > -1)
     {
          return 'IE 7';
     }
     if(userAgent.indexOf('MSIE 6.0') > -1)
     {
         return 'IE 6';
     }
     if(userAgent.indexOf('Firefox') > -1)
     {
         return 'Mozilla';
     }
     if(userAgent.indexOf('Opera') > -1)
     {
         return 'Opera';
     }
     
     return 'unknow';
}

//  Use these functions to make the firefox compatible with the selectNodes/selectSingleNode function.
function CompatibleFirefoxXMlDocument()
{
    // check for XPath implementation
    if(document.implementation.hasFeature("XPath", "3.0"))
    {
        // prototying the XMLDocument
        XMLDocument.prototype.selectNodes = function(cXPathString, xNode)
        {
            if(!xNode) 
            { 
                xNode = this; 
            } 
            var oNSResolver = this.createNSResolver(this.documentElement);
            var aItems = this.evaluate(cXPathString, xNode, oNSResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
            var aResult = [];
            for( var i = 0; i < aItems.snapshotLength; i++)
            {
                aResult[i] = aItems.snapshotItem(i);
            }
            return aResult;
        }

        // prototying the Element
        Element.prototype.selectNodes = function(cXPathString)
        {
            if(this.ownerDocument.selectNodes)
            {
              return this.ownerDocument.selectNodes(cXPathString, this);
            }
            else
            {
                throw "For XML Elements Only";
            }
        }
    }

    // check for XPath implementation
    if(document.implementation.hasFeature("XPath", "3.0"))
    {
        // prototying the XMLDocument
        XMLDocument.prototype.selectSingleNode = function(cXPathString, xNode)
        {
            if(!xNode) 
            { 
                xNode = this; 
            } 
            var xItems = this.selectNodes(cXPathString, xNode);
            if( xItems.length > 0 )
            {
                return xItems[0];
            }
            else
            {
                return null;
            }
        }

        // prototying the Element
        Element.prototype.selectSingleNode = function(cXPathString)
        { 
            if(this.ownerDocument.selectSingleNode)
            {
                return this.ownerDocument.selectSingleNode(cXPathString, this);
            }
            else
            {
                throw "For XML Elements Only";
            }
        }
    }
}

//get xml node's text
function getXmlText(node)
{
    if (!node)
        return 'nodata';
        
    if(clientBrowser=='Mozilla' || clientBrowser=='Opera') 
    {
        return node.textContent;
    }
    else
    {
        return node.text;
    }
}

  
function createProfileXml(str)
{
    var insertS = " xmlns:msn='http://schemas.microsoft.com/msn/spaces/2005/rss' ";
    var point = str.indexOf("xmlns:live");
	var newStr;
	
	if (point > 0 && str.indexOf(insertS) < 0)
	{
		var s1 = str.substring(0, point);
		var s2 = str.substring(point, str.length);
		newStr = s1 + insertS + s2;
	}
	else
	{
		newStr = str;
	} 
     
    return GenerateXMLDOC(newStr, true);
}

function createInterestedProfileHtml(str)
{    
    var div = document.createElement("div");
    div.innerHTML = str;
        
    return div;
}



//=========Ajax Utility=============================================================================================================
//Post asynchronous request for the spaces.live.com/changes.aspx feed via php proxy
function getSpacesChanges(p_callbackFunction)
{
	var errorstate="";
	//define request
	var url= proxy + spaceListFeed	
	
	xmlhttpChanges=null;
   
	if (window.XMLHttpRequest)
	{// code for IE7, Firefox, Mozilla, etc.
		xmlhttpChanges=new XMLHttpRequest();
	}
	else if (window.ActiveXObject)
	{// code for IE5, IE6
		xmlhttpChanges=new ActiveXObject("Microsoft.XMLHTTP");
	}
	if (xmlhttpChanges!=null)
	{
		xmlhttpChanges.onreadystatechange=p_callbackFunction;
		xmlhttpChanges.open("GET",url,true);
		xmlhttpChanges.send(null);
	}
	else
	{
	  	errorstate="XMLHTTP request for changes feed not generated";
	}
	return errorstate;
}


//Post asynchronous request for profilename.spaces.live/profile/feed/rss profile feed via php proxy
function getSpacesProfileFeed(p_subDomain, p_callbackFunction)
{
	var errorstate="";
	var url;
	//define request
//	if (feedFrom == "change")
	    url= proxy + p_subDomain ;
//	else
//	    url= p_subDomain ;
	
	xmlhttp=null;
   
	if (window.XMLHttpRequest)
	{// code for IE7, Firefox, Mozilla, etc.
		xmlhttp=new XMLHttpRequest();
	}
	else if (window.ActiveXObject)
	{// code for IE5, IE6
		xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
	}
	
	if (xmlhttp)
	{	    
		xmlhttp.onreadystatechange=p_callbackFunction;
		xmlhttp.open("GET",url,true);
		xmlhttp.send(null);
	}
	else
	{
	  	errorstate="XMLHTTP request for profile feed not generated";
	}
	return errorstate;
}

//Parse XML document returned from 
function parseProfileRSS(p_xmlpointer)
{
	var objStore=new Object();
	var myNodes;
	var arrayStore=new Array();	
	
	if (!p_xmlpointer)
	{
	    arrayStore[0]="nodata";
	    return arrayStore;
	}
	
	var imageNodeNames=new Array("title", "image", "url");
	var imageNodeValues=new Array();
	myNodes=p_xmlpointer.selectNodes("/rss/channel/image");
	
	//If success then extract the different values using a loop.
	if (myNodes && myNodes.length>0)
	{
		for (i=0; i<myNodes.length;i++)
		{
		    var node = myNodes[i].selectSingleNode("title");
		    var text;
		    if (node)
		    {
		        text = getXmlText(node.firstChild);
		        text = encodeURIComponent(text.substring(0,(text.length)-9));	
			    eval("objStore."+imageNodeNames[0]+"=text");
		    }
		    else
		    {
		        eval("objStore."+imageNodeNames[0]+"='nodata'");
		    }
		    
		    node = myNodes[i].selectSingleNode("url");
		    if (node)
		    {
		        text = getXmlText(node.firstChild);
		        text = encodeURIComponent(text);	
			    eval("objStore."+imageNodeNames[1]+"=text");
		    }
		    else
		    {
		        eval("objStore."+imageNodeNames[1]+"='nodata'");
		    }
		    
			node = myNodes[i].selectSingleNode("link");
		    if (node)
		    {
		        text = getXmlText(node.firstChild);
		        text = encodeURIComponent(text);	
			    eval("objStore."+imageNodeNames[2]+"=text");
		    }
		    else
		    {
		        eval("objStore."+imageNodeNames[2]+"='nodata'");
		    }
		}
	}
	else
	{
		//No response.
		for (j=0; j<(imageNodeNames.length);j++)
		{
			eval("objStore."+imageNodeNames[j]+"='nodata'");
		}
	}
	
	//get location
	var liveNodeNames=new Array("publicDisplayName","publicNickname","generalDisplayPicture","gender","age","occupation","location","interests","moreAboutMe");
	var liveNodeValues=new Array();	
	myNodes=p_xmlpointer.selectNodes("/rss/channel/item");
	if (myNodes && myNodes.length>0)
	{
		for (i=0; i<myNodes.length;i++)
		{
		    for (j=0; j<liveNodeNames.length; j++)
	        {
		        var node = myNodes[i].selectSingleNode("live:"+ liveNodeNames[j]);
		        var text;
		        if(node)
		        {
		            text = getXmlText(node.firstChild);
		            eval("objStore."+liveNodeNames[j]+"=encodeURIComponent(text)");
		        }
		    }		    
		}
	}
	else
	{
	    for (j=0; j<(liveNodeNames.length);j++)
		{
		    eval("objStore."+liveNodeNames[j]+"='nodata'");
		}
	}	
	return objStore;
}
	
function parseChangesRSS(p_xmlpointer)
{
	var myNodes=p_xmlpointer.getElementsByTagName("weblog");
	var arrayStore=new Array();	
	//If success then extract the different values using a loop.
	if (myNodes && p_xmlpointer && myNodes.length>1)
	{	
		for (var i=0; i<myNodes.length;i++)
		{
			arrayStore[i]=myNodes.item(i).attributes.getNamedItem("url").value;
		}
	}
	else
	{
		//No response.
		arrayStore[0]="nodata";
	}

	return arrayStore;
}

function parseInterestedProfileRSS(p_xmlpointer)
{
	var objStore = new Object();
	var myNode;	
	var key;
	var pointBegin;
	var pointEnd;
	
	//debugger;
	objStore.image = "nodata"; 
	objStore.location = "nodata"; 

	return objStore;
}

function parseInterestedRSS(p_xmlpointer)
{  
	var myNodes=p_xmlpointer.getElementsByTagName("item");
	var arrayStore=new Array();
	var arrLinks;
	//If success then extract the different values using a loop.
	if (myNodes && p_xmlpointer && myNodes.length>1)
	{	
		for (var i=0; i<myNodes.length;i++)
		{
			arrLinks = myNodes.item(i).getElementsByTagName("link");
			if (arrLinks)
			{   
			    var url = arrLinks[0].text;
			    var p = url.indexOf("default.aspx");
			    if (p > 0)
			        arrayStore[i] = url.substring(0, p);
			    else
			        arrayStore[i]="nodata";    
			}
			else
			    arrayStore[i]="nodata";
		}
	}
	else
	{
		//No response.
		arrayStore[0]="nodata";
	}

	return arrayStore;
}


//=======Map Utility===========================================================================================================================

function getSpacesChangesComplete()
{
	if(xmlhttpChanges.readyState==4)
	{	    
		if(xmlhttpChanges.status==200)
		{				
			var myXmlDoc = xmlhttpChanges.responseXML.documentElement;	
	
			if (feedFrom == "change")
			{
			    arrChanges=parseChangesRSS(myXmlDoc);
			}
			else
			{
			    arrChanges=parseInterestedRSS(myXmlDoc); 
			}
			
			profilePointer=0;
			max = arrChanges.length;			
			changesCallbackComplete=true;	
			
			if (debug)
			{		
				for (i=0; i<arrChanges.length; i++)
				{
					var changesInfo=document.getElementById("changes").innerHTML;
					changesInfo+="<"+ i +">"+arrChanges[i] +"<hr />";
					document.getElementById("changes").innerHTML=changesInfo;
				}
			}	
		}
		else
		{
			//errorHandler("Problem with fetching Spaces Feed, Error No. :"+ xmlhttpChanges.status);	
			fatalError=true;			
		}
	}
}

function getSpacesProfileFeedComplete()
{    
	var errorState="";
	if(xmlhttp.readyState==4)
	{
		//var objProfile=new Object();
		if(xmlhttp.status==200)
		{	
			var myXmlDoc;
//			if (feedFrom == "change")
//			{
			    myXmlDoc = createProfileXml(xmlhttp.responseText);
			    
			    myXmlDoc = myXmlDoc.documentElement;
			    if (myXmlDoc)
			        resultObj = parseProfileRSS(myXmlDoc);
//			}
//			else
//			{
//			    //myXmlDoc = createInterestedProfileHtml(xmlhttp.responseText);
//			    //myXmlDoc = myXmlDoc.document;
//			    myXmlDoc = xmlhttp.responseText;
//			    if (myXmlDoc)
//			        resultObj = parseInterestedProfileRSS(myXmlDoc);
//			}
			profileCallbackComplete=true;		
		}
		else
		{
			//errorHandler("Problem with fetching Spaces Profile:\n "+xmlhttp.status);
			fatalError=true;
		}
		
		if (debug)
		{
			var debugInfo=document.getElementById("debugOutput").innerHTML;
			debugInfo+="("+ (profilePointer-1) +") feed="+arrChanges[profilePointer-1] +" spaceUrl="+resultObj.url+" loc="+resultObj.location+" ";
			if (resultObj.image){debugInfo+="(image)";}
			debugInfo+="<hr \/> ";
			document.getElementById("debugOutput").innerHTML=debugInfo;
		}
	}
}

//can't get this to work from the onendpan event - bah!
function panComplete()
{
	readyToFindNextProfile=true;	
}

function findComplete(layer, resultsArray, places, hasMore, veErrorMessage)
{   
    var profileObj = resultObj;   
    resultObj = null; 
	readyToFindNextProfile=true;
	
	if(stop)
	    return;
	
	if (!veErrorMessage && profileObj)
	{			    
		createPhotoList(profileObj.title, profileObj.url, profileObj.image);
		
		shape = new VEShape(VEShapeType.Pushpin, places[0].LatLong);

        if (map.GetMapMode() == VEMapMode.Mode2D)
        {
            var customHTML="<div class='bubble'><div class='bubblebg'><div>";               
		    customHTML+="<div class='bubble_photo'>";    
           
            if (profileObj.image && profileObj.image!="nodata")
            {
			    customHTML+="<table border='0' cellpadding='0' cellspacing='0' width='60px' height='70px'><tr><td align='center' valign='middle'><img src='"+decodeURIComponent(profileObj.image)+"' onload='resizeImage(this);' /></td></tr></table>";
		    }
		    customHTML+="</div><div class='bubble_right'>";  
				
		    if (profileObj.title && profileObj.title!="nodata")
            {	
			    customHTML+="<span class='bubble_sectionname'>Name:</span><span class='bubble_sectionvalue'>"+htmlEndcode(decodeURIComponent(profileObj.title))+"</span><br/>";
            }
            if (profileObj.location && profileObj.location!="nodata")
            {
                customHTML+="<span class='bubble_sectionname'>Location:</span><span class='bubble_sectionvalue'>"+htmlEndcode(decodeURIComponent(profileObj.location))+"</span><br/>";
		    }
            if (profileObj.age && profileObj.age!="nodata" && profileObj.age!="0")
            {
			    customHTML+="<span class='bubble_sectionname'>Age:</span><span class='bubble_sectionvalue'>"+decodeURIComponent(profileObj.age)+"</span><br/>";
            }
            if (profileObj.interests && profileObj.interests!="nodata")
            {
        	    customHTML+="<span class='bubble_sectionname'>Interest:</span><span class='bubble_sectionvalue'>"+htmlEndcode(decodeURIComponent(profileObj.interests))+"</span><br/>";
            }
            customHTML+="</div><div><span  class='bubble_abstract'>";
            if (profileObj.moreAboutMe && profileObj.moreAboutMe!="nodata")
            {
        	    customHTML+=decodeURIComponent(profileObj.moreAboutMe);
            }
            customHTML+="</span></div><div class='bubble_btn'><img onclick=goMySpace('"+ profileObj.url +"') src='http://estc.msn.com/br/intl/spec/fr-fr/spacevision/image/1/see_my_space.jpg' /></div>";
            customHTML+="</div></div>";                
            shape.SetCustomIcon(customHTML);
        }
        else
        {
            var sIcon = new VECustomIconSpecification();
            if (profileObj.image!="nodata")
            {
			    sIcon.Image = decodeURIComponent(profileObj.image);
		    }			    
		    shape.SetCustomIcon(sIcon);
        }   
            
        shape.SetIconAnchor(places[0].LatLong);   
        map.AddShape(shape);
		var newLen=arrShapes.push(shape);
		if (newLen > maxBubblesOnScreen)
		{
				var removedItem=arrShapes.shift();
				map.DeleteShape(removedItem);
		}
		map.PanToLatLong(places[0].LatLong);
		
		if (!showNo3DInfo)
		{
			showMessage("none"); 
		}        			
	}
	else
	{
		fatalError=true;
		//errorHandler("in findComplete\n:"+ veErrorMessage);		
	}
	
	profileObj=null;
}

function FindLoc(p_location)
{

	    try
	    {		    				
		    //VEMap.Find(what, where, findType, shapeLayer, startIndex, numberOfResults, showResults, createResults, useDefaultDisambiguation, setBestMapView, callback);
            map.Find(null, p_location, null, null, null, 10, null, null, false,  false, findComplete);
	    }
	    catch(e)
	    {
		    //errorHandler(e+"in function FindLoc");
		    fatalError=true;
	    }

}

function updateMap()
{
	//Is the map fetched yet?
	
	if (!stop)
	{
	    
	        if (changesCallbackComplete)
	        {
    	        
		        if (profileCallbackComplete && !fatalError && resultObj && resultObj.location && resultObj.image && resultObj.location!="nodata" && resultObj.image!="nodata" )
		        {
			        //Yes so mark as busy and go off to find it
			        readyToFindNextProfile=false;
			        searchValid = true;
				    FindLoc(resultObj.location);			    
		        }
    		    
			    if (readyToFindNextProfile || fatalError)
		        {
			        //No go get another profile	
			        var profileUrl;	
			        //if (feedFrom == "change")
			        //    profileUrl = arrChanges[profilePointer] +"profile/feed.rss";
			        //else
			            profileUrl = arrChanges[profilePointer] +"profile/feed.rss";
    			        
    			        
    			        	    
			        var response = getSpacesProfileFeed(profileUrl, getSpacesProfileFeedComplete);
			        if (response!="")
			        {
				        errorHandler(response+"in function updateMap");
			        }
        			
			        profilePointer=profilePointer+1;
				    profileCallbackComplete=false;
			        fatalError = false;
		        }			
	        }

    	
	    //Call this again shortly
        if (profilePointer < max)
        {
			if (fatalError)
	        	setTimeout(updateMap,0);
			else
				setTimeout(updateMap,waitDelay);
        }
        else
        //Feed exhausted - refresh
        {
            if (feedFrom == "interested" && searchValid == false)
            {
                showMessage("searchNoResult"); 
            }   
            else
	            mapsReset();
        }
    }
}
	
function GetMap()
{    
   map = new VEMap('mymap');   
   map.SetDashboardSize(VEDashboardSize.Small);  
   map.LoadMap(); 
   
   map.AttachEvent('onmodenotavailable', no3DInstalled); 
   map.SetMapMode(VEMapMode.Mode3D);
   map.SetMapStyle(VEMapStyle.Hybrid); 
   map.Hide3DNavigationControl(); 
}

function mapsReset()
{
    changesCallbackComplete = false;
    readyToFindNextProfile = true;    
    profilePointer = 0;
        
    var response = getSpacesChanges(getSpacesChangesComplete);
    if (response!="") 
    {
        errorHandler(response+" in function init");
    }
    else
    {
        if (!map) {GetMap();}
        //doesn't seem to work
        //	map.AttachEvent("onendpan", panComplete);

        //In 2500 milliseconds go and check if the map was loaded and the callback completed
        setTimeout(updateMap,waitDelay);	            
        photoReset();
    }  
}


//=======Photobar Utility===========================================================================================================================
function createPhotoList(title, url, image)
{
    if (image == "nodata") return;
    
    var photoList = $("photo_list_imgs");    
    var newPhoto = "<a href='"+ decodeURIComponent(url) +"'";
    if (title && title!="nodata")
    {
        newPhoto += " title=\""+ decodeURIComponent(title).replace(/"/g,"'") +"\" ";
    }
    else
    {
        newPhoto += " title=\""+ decodeURIComponent(url).replace(/"/g,"'") +"\" ";
    }
    newPhoto += "target='_blank'><img src='"+ decodeURIComponent(image) +"'></a>";
    newPhoto += loadingImg;

    var photoListText;
    photoListText = photoList.innerHTML;    
    photoListText = photoListText.replace(/<img/ig, "<img")
    photoList.innerHTML = photoListText.replace(loadingImg.toLowerCase(), newPhoto);
    photoAutoMove();
}


function photoRollLeft()
{
    photoMove = setInterval(photoMoveLeft, photoMoveInterval);
}

function photoMoveLeft()
{
    var obj = document.getElementById('photo_list_imgs');
    var objParent = document.getElementById('photo_list');   
        
    if (obj.offsetWidth > objParent.offsetWidth && objParent.offsetWidth - obj.offsetWidth < photoLeft)
    {              
        photoLeft -= photoMoveSpeed;        
        obj.style.left = photoLeft.toString() + 'px';
    }
}

function photoRollRight()
{
    
    photoMove = setInterval(photoMoveRight, photoMoveInterval);    
}

function photoMoveRight()
{    
    var obj = document.getElementById('photo_list_imgs');
    var objParent = document.getElementById('photo_list'); 
   
    if (photoLeft < 0)
    {
        photoLeft +=  photoMoveSpeed;
        obj.style.left = photoLeft.toString() + 'px';
    }
}

function photoAutoMove()
{    
    var obj = document.getElementById('photo_list_imgs');
    var objParent = document.getElementById('photo_list'); 
    var width = obj.style.width;
    
    if (width == "")
    {        
        width = photoImgWidth;        
    }   
    else
    {
        width = parseInt(width);
    }    
    
    obj.style.width = width + photoImgWidth + 'px';     
   
    if (obj.offsetWidth > objParent.offsetWidth)
    {
        photoLeft -= photoImgWidth;        
        obj.style.left = photoLeft.toString() + 'px';
        
        if ($("photo_btn_left").innerHTML == "")
            $("photo_btn_left").innerHTML = "<img onmouseover='photoRollLeft()' onmouseout='clearInterval(photoMove)' src='http://estc.msn.com/br/intl/spec/fr-fr/spacevision/image/1/photoArrow_Left.gif'>";
        if ($("photo_btn_right").innerHTML == "")
            $("photo_btn_right").innerHTML = "<img onmouseover='photoRollRight()'onmouseout='clearInterval(photoMove)' src='http://estc.msn.com/br/intl/spec/fr-fr/spacevision/image/1/photoArrow_Right.gif'>";
    }
}

function photoReset()
{    
    var obj = document.getElementById('photo_list_imgs');
    
    photoLeft = 0;        
    obj.style.left = '0px';
    obj.style.width = photoImgWidth + 'px';
    $("photo_btn_left").innerHTML = "";
    $("photo_btn_right").innerHTML = "";
    $("photo_list").innerHTML = "<div id='photo_list_imgs'>"+ loadingImg +"</div>";
}


//=======UI Utility=================================================================================================================================
function addShim(el, z_index, iframename)
{
    var shim = document.createElement("iframe");
    shim.id = iframename ;
    shim.frameBorder = "0";
    shim.scrolling = "no";
    shim.style.position = "absolute";
    shim.style.zIndex = "1";
    shim.style.top  = el.offsetTop;
    shim.style.left = el.offsetLeft;
    shim.width  = el.offsetWidth;
    shim.height = el.offsetHeight;
    el.shimElement = shim;
    el.style.zIndex = z_index;
    el.parentNode.insertBefore(shim, el);
}

function goMySpace(url)
{
    window.open(decodeURIComponent(url),"","");
}

function no3DInstalled()
{
    if (firstShow3D)
    {
        firstShow3D = false;
        changeViewModel(2);        
    }
    else
    {
	    showNo3DInfo = true;
	    showMessage("no3D");
        $("imgView3d").src = "http://estc.msn.com/br/intl/spec/fr-fr/spacevision/image/1/3DVIEW_btn.jpg";
        $("imgView2d").src = "http://estc.msn.com/br/intl/spec/fr-fr/spacevision/image/1/2DVIEW_act_btn.jpg";	
    }
}

function no3DInstalled_close()
{
	showNo3DInfo = false;
	showMessage("none");
}
	
function searchIntersted()
{
    feedFrom = "interested";
    searchValid = false;
    
    var objSearchInput = $("searchmapKeyword");      
    if (objSearchInput)
    {  
        if (objSearchInput.value)        
            spaceListFeed = encodeURIComponent("http://search.live.com/results.aspx?q=meta:search.interests("+ objSearchInput.value +") site:spaces.live.com&format=rss");
        else
        {
            alert("Please input your keyword!"); 
            return;   
        }
    }    
    
    showMessage("loadInterested");
    
    stop = false;
    map.DeleteAllShapes();
    photoReset();     
    mapsReset();
}

function changeViewModel(model)
{    
    if (model == 2 && map.GetMapMode() == VEMapMode.Mode3D)
    {
        $("imgView3d").src = "http://estc.msn.com/br/intl/spec/fr-fr/spacevision/image/1/3DVIEW_btn.jpg";
        $("imgView2d").src = "http://estc.msn.com/br/intl/spec/fr-fr/spacevision/image/1/2DVIEW_act_btn.jpg";        
        map.SetMapMode(VEMapMode.Mode2D); 
    }
    else if (model == 3 && map.GetMapMode() == VEMapMode.Mode2D)
    {
        $("imgView3d").src = "http://estc.msn.com/br/intl/spec/fr-fr/spacevision/image/1/3DVIEW_act_btn.jpg";
        $("imgView2d").src = "http://estc.msn.com/br/intl/spec/fr-fr/spacevision/image/1/2DVIEW_btn.jpg";
        map.SetMapMode(VEMapMode.Mode3D);     
    }
}

function changeFeed(value)
{    
    if (value == 1 && feedFrom == "interested")
    {
        feedFrom = "change"
		spaceListFeed = "http://spaces.live.com/changes.aspx";
        
        $("update_btn").className = "update_btn_act";
        $("interested_btn").className = "interested_btn";
        $("searchboxholder").innerHTML = ""; 
        showMessage("loadUpdate");
        
        map.DeleteAllShapes();
        stop = false;
        photoReset()
        mapsReset();
    }
    else if( value == 2 && feedFrom == "change")
    {
        feedFrom = "interested";
        $("update_btn").className = "update_btn";
        $("interested_btn").className = "interested_btn_act";
        $("searchboxholder").innerHTML = "<div id='searchbox'><div id='searchinput'><input id='searchmapKeyword' /><img onclick='searchIntersted()' src='http://estc.msn.com/br/intl/spec/fr-fr/spacevision/image/1/search_btn.gif' /></div></div>";     
        
        showMessage("none");
        stop = true;
        map.DeleteAllShapes();        
        photoReset()
    }
}

function showMessage(whatcase)
{
    switch(whatcase)
    {
        case "loadUpdate":
        {
            $("maploading").innerHTML = "<img src='http://estc.msn.com/br/intl/spec/fr-fr/spacevision/image/1/wl_spaces_home.png' alt='logo' /><br /><b>Live Spaces Vision </b><br /><small>Recently updated accounts from around the world</small><br /><img src='http://estc.msn.com/br/intl/spec/fr-fr/spacevision/image/1/loading.gif' alt='rotation' /><br />Please wait - loading data...";
            break;
        }
        case "loadInterested":
        {
            $("maploading").innerHTML = "<img src='http://estc.msn.com/br/intl/spec/fr-fr/spacevision/image/1/wl_spaces_home.png' alt='logo' /><br /><b>Live Spaces Vision </b><br /><small>Recently interested accounts from around the world</small><br /><img src='http://estc.msn.com/br/intl/spec/fr-fr/spacevision/image/1/loading.gif' alt='rotation' /><br />Please wait - loading data...";
            break;
        }
        case "searchNoResult":
        {
            $("maploading").innerHTML = "<table id='no3d_info' width='100%' border='0' cellpadding='0' cellspacing='0'><tr><td  align='right' height='10px'><img onclick='no3DInstalled_close()' src='http://estc.msn.com/br/intl/spec/fr-fr/spacevision/image/1/close_unselected.gif' border=0></td></tr><tr><td  align='center' valign='middle'><br><br>Sorry, we did not find any results for your search!</td></tr></table>"; 
            break;
        }
        case "no3D":
        {
            $("maploading").innerHTML = "<table id='no3d_info' width='100%' border='0' cellpadding='0' cellspacing='0'><tr><td  align='right' height='10px'><img onclick='no3DInstalled_close()' src='http://estc.msn.com/br/intl/spec/fr-fr/spacevision/image/1/close_unselected.gif' border=0></td></tr><tr><td   align='left'>In order to switch to 3D view you must install the feature by clicking <a href='http://go.microsoft.com/fwlink/?LinkId=72623' target='_target' onclick='no3DInstalled_close()'>here</a>. </td></tr><tr><td align='left'>If you have already installed it, please:<ul><li>Make sure that Direct3D and DirectDraw acceleration are enabled.</li><li>Make sure that hardware acceleration is set to Full.</li><li>Make sure that you have the most recent display driver.</li><li><a href='http://help.live.com/help.aspx?mkt=en-us&project=wl_local&querytype=topic&query=WL_LOCAL_TROU_3D_VideoAcceleration.htm' target='_blank'>more help</a></li></ul></td></tr></table>"; 
            break;
        }
        case "none":
        {
            $("iframe_maploading").style.display = "none";
            $("maploading").style.display = "none";
            break;
        }
    }
    
    if (whatcase != "none")
    {
        $("iframe_maploading").style.display = "";
        $("maploading").style.display = "";
    }
}

function addLinkPopup()
{
    var divLink = $("textlink");
    if (divLink)
    {
        var aArr = divLink.getElementsByTagName("a");
        aArr[0].href = "javascript:void(null)";
        aArr[0].attachEvent("onclick",linkPopup);
    }
}

function linkPopup()
{
    var newWindow = window.open("", "learnmore", "width=300px,height=300px,top=200px,left=200px");
    newWindow.document.write("<html><head><title>About Live Spaces Vision - Live Spaces Vision - Updates in near real-time - MSN on Windows Live</title>");
    newWindow.document.write("<style type='text/css'>body{font-size:12px;font-family:Arial, Helvetica, sans-serif;}</style></head><body>");
    newWindow.document.write("<h3>About Live Spaces Vision</h3>");
    newWindow.document.write("<p><strong>Live Spaces Vision</strong> is a stream of global updates to the Windows Live Spaces network of local market sites in near real-time. <strong>Live Spaces Vision</strong> joins <a href='http://www.flickrvision.com/' target='_blank'>FlickrVision</a>, <a href='http://www.twittervision.com/' target='_blank'>TwitterVision</a>, and <a href='http://www.lkozma.net/wpv/index.html' target='_blank'>WikipediaVision</a> in the vision map genre. This was achieved by using the publicly available <a href='http://spaces.live.com/changes.aspx' target='_blank'>Changes Feed</a> and <a href='http://dev.live.com/virtualearth/sdk/' target='_blank'>Virtual Earth SDK</a>.</p>");
    newWindow.document.write("<p>Evangelised by <a href='http://pixorix.spaces.live.com/' target='_blank'>Rick Stock</a> and <a href='http://bedrockcms.spaces.live.com/' target='_blank'>Jason Christie</a> in London, UK. Developed by Cyokin Zhang and Jamie He in Shanghai, CN.</p>");
    newWindow.document.write("</body></html>");   
}

//======= Start =================================================================================================================================
function init()
{    
    $("update_btn").innerHTML = "<img id='imgUpdate'  onclick='changeFeed(1)' src='http://estc.msn.com/br/intl/spec/fr-fr/spacevision/image/1/feed_btn.gif' border=0 />";
    $("update_btn").className = "update_btn_act";
    $("interested_btn").innerHTML = "<img id='imgInterested'  onclick='changeFeed(2)' src='http://estc.msn.com/br/intl/spec/fr-fr/spacevision/image/1/feed_btn.gif' border=0 />";
    $("interested_btn").className = "interested_btn";
    $("view3d_btn").innerHTML = "<img id='imgView3d' onclick='changeViewModel(3)' src='http://estc.msn.com/br/intl/spec/fr-fr/spacevision/image/1/3DVIEW_act_btn.jpg' border=0 />";
    $("view2d_btn").innerHTML = "<img id='imgView2d' onclick='changeViewModel(2)' src='http://estc.msn.com/br/intl/spec/fr-fr/spacevision/image/1/2DVIEW_btn.jpg' border=0 />";    
    $("photo_list").innerHTML = "<div id='photo_list_imgs'>"+ loadingImg +"</div>";    
    
    //add "Live Space Vision" text
	var update_interested = $("update_interested");
	var spacevision = document.createElement("div");
	spacevision.id = "spacevision";
	spacevision.innerHTML = "Live Spaces Vision";
	update_interested.parentNode.insertBefore(spacevision, update_interested);
	spacevision = null;	
	
	//add a black space between update button and interested button
	var interested_btn = $("interested_btn");
	var btnblank = document.createElement("div");
	btnblank.id = "btnblank";
	interested_btn.parentNode.insertBefore(btnblank, interested_btn);
	btnblank = null;	
	
	//add a pop-up link 'Learn more about Live Space Vision'
	addLinkPopup();
    
    //add a IFRAME shim
    addShim($("maploading"),100, "iframe_maploading");
    addShim($("update_btn"),101, "iframe_update_btn");
    addShim($("interested_btn"),102, "iframe_interested_btn");
    
    //show loading message
    showMessage("loadUpdate");
    
    //if debug
    var href=String(window.location);
	if (href.indexOf("debug")!=-1)
	//if(debug)
	{
		debug=true;
		var debugHTML="<div style='padding: 4px 4px 4px 4px;'>";
		debugHTML+="<input type='button' value='debug' onClick='debugHandler()' /><input type='button' value='stop' onClick='javascript:stop=true' /></div>";
		debugHTML+="<table><tr><td valign='top'><div id='debugOutput'></div></td><td><div id='changes'></div></td></tr></table>";
		document.getElementById("debuginfo").innerHTML=debugHTML;
		document.getElementById("debuginfo").style.display = "block";
	}
	
	
    CompatibleFirefoxXMlDocument();
    clientBrowser = CheckUserWebBrowser();
	//Go get the list of Spaces changes
	setTimeout(mapsReset,1000);
} 


//Called by an onClick in the debug div below. Normally commented out.
function debugHandler()
{
	alert("profilePointer: "+profilePointer+"\nlocation: "+resultObj.location+"\nimage: "+resultObj.image +"\nchangesCallbackComplete: "+changesCallbackComplete+"\nprofileCallbackComplete: "+profileCallbackComplete+"\nreadyToFindNextProfile: "+readyToFindNextProfile+"\nfatalError: "+fatalError+"\nmax: "+max+"\ntitle: "+resultObj.title+"\narrayChanges: "+arrChanges[profilePointer]);
}

window.onload = init;
