function initScrollLayer() {
  var wndo = new dw_scrollObj('wn', 'lyr1');
  wndo.setUpScrollbar("dragBar", "track", "v", 1, 1);
  dw_scrollObj.GeckoTableBugFix('wn'); 
}

var currentBox = null;
var lastdiv;
var tempTop;
var tempLeft;
var tempTotal;
var tempLastRun;
var tempChallenge;
var tempLocale;
var tempEmail;
var tempURL;
var avatarURL;
var xmlInterval;
var firstTime = null;

function setLyr(obj,lyr,xmlID,total,lastrun,locale,email,test,avatar)
{
//	alert('WORK IN PROGRESS...');
	if (currentBox != null) {
		HideContent(lastdiv);
	}
	currentBox = lyr;
	lastdiv = lyr;
	var coors = findPos(obj);
	if (lyr == 'testP') coors[1] -= 50;
	tempTop = (coors[1]-75) + 'px';
	tempLeft = (coors[0]+10) + 'px';
//	var getXML = "http://forums.nike.com/xmlServiceProxy.jsp?service=get_public_user_data&id="+ xmlID;
	var getXML = "/wordpress/wp-content/plugins/nipe/fetch_public_user_info.php?id="+ xmlID;
	tempURL = "http://forums.nike.com/nikeplus/v1/services/app/get_public_user_data.jhtml?id=";

	makeRequest(getXML);

	tempTotal = total;
	tempLastRun = lastrun;
	tempLocale = locale;
	tempEmail = email;
	avatarURL = avatar;
	if (test == true) {
		document.getElementById("tdone").style.display = "none";
		document.getElementById("tdtwo").style.display = "none";
	} else {
		document.getElementById("tdone").style.display = "block";
		document.getElementById("tdtwo").style.display = "block";
	}
}

function setWhite(lyr)
{
	currentBox = lyr;
	if (currentBox != null) {
		HideContent(lastdiv);
	}
	var x = document.getElementById(lyr);
	x.style.top = tempTop;
	x.style.left = tempLeft;
	x.style.display = "block";
}

function getGreen()
{
	var getChallenge = "xmlServiceProxy.jsp?service=get_challenges_for_user";
	tempURL = "/nikeplus/v1/services/app/get_challenges_for_user.jhtml";
	makeRequest(getChallenge);
}

function setGreen(lyr)
{
	currentBox = lyr;
	if (currentBox != null) {
		HideContent(lastdiv);
	}
	var y = document.getElementById(lyr);
	y.style.top = tempTop;
	y.style.left = tempLeft;
	y.style.display = "block";
	lastdiv = lyr;
}

function setGreen2(lyr)
{
	currentBox = lyr;
	if (currentBox != null) {
		HideContent(lastdiv);
	}
	var y = document.getElementById(lyr);
	y.style.top = tempTop;
	y.style.left = tempLeft;
	y.style.display = "block";
	document.getElementById("tdchallenge2").innerHTML = 'You must be logged in.';
	lastdiv = lyr;
}

function setGreenSuccess(lyr)
{
	currentBox = lyr;
	if (currentBox != null) {
		HideContent(lastdiv);
	}
	var y = document.getElementById(lyr);
	y.style.top = tempTop;
	y.style.left = tempLeft;
	y.style.display = "block";
	document.getElementById("tdchallenge2").innerHTML = 'Your challenge(s) have been sent.';
	lastdiv = lyr;
}

function findPos(obj)
{
	var curleft = curtop = 0;
	if (obj.offsetParent) {
		curleft = obj.offsetLeft
		curtop = obj.offsetTop
		while (obj = obj.offsetParent) {
			curleft += obj.offsetLeft
			curtop += obj.offsetTop
		}
	}
	return [curleft,curtop];
}

function HideContent(d) {
	if(d.length < 1) { return; }
	document.getElementById(d).style.display = "none";
}

function makeRequest(url) {
    http_request = false;
    if (window.XMLHttpRequest) { // Mozilla, Safari,...
        http_request = new XMLHttpRequest();
        if (http_request.overrideMimeType) {
            http_request.overrideMimeType('text/xml');
            // See note below about this line
        }
	if (tempURL.substr(52,6) == 'public')	{
	    http_request.onreadystatechange = getData;
//		document.getElementById("tduser").innerHTML = 'WORK IN PROGRESS';
	} else if (tempURL.substr(52,10) == 'challenge_')	{
	    http_request.onreadystatechange = getSuccess;
	} else {
	    http_request.onreadystatechange = getChallenge;
	} 
    http_request.open('GET', url, true);
    http_request.send(null);
    
//    alert('getData: '+http_request.readyState+' || '+http_request.status);
    
    } else if (window.ActiveXObject) { // IE
        try {
            http_request = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e) {
            try {
                http_request = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e) {}
        }
	if (tempURL.substr(52,6) == 'public')	{
	    http_request.onreadystatechange = getData;
	} else if (tempURL.substr(52,10) == 'challenge_')	{
	    http_request.onreadystatechange = getSuccess;
	} else {
	    http_request.onreadystatechange = getChallenge;
	} 
    http_request.open('GET', url, true);
    http_request.send();
    }
    if (!http_request) {
        alert('Cannot create an XML XMLHTTP instance.  It might be a good idea to upgrade your browser.');
        return false;
    }
}

function encode_utf8(rohtext) {
	// dient der Normalisierung des Zeilenumbruchs
	rohtext = rohtext.replace(/\r\n/g,"\n");
	var utftext = "";
	for(var n=0; n<rohtext.length; n++)
	{
	// ermitteln des Unicodes desĘ aktuellen Zeichens
	var c=rohtext.charCodeAt(n);
	// alle Zeichen von 0-127 => 1byte
	if (c<128)
		utftext += String.fromCharCode(c);
	// alle Zeichen von 127 bis 2047 => 2byte
	else if((c>127) && (c<2048)) {
		utftext += String.fromCharCode((c>>6)|192);
		utftext += String.fromCharCode((c&63)|128);}
	// alle Zeichen von 2048 bis 66536 => 3byte
	else {
		utftext += String.fromCharCode((c>>12)|224);
		utftext += String.fromCharCode(((c>>6)&63)|128);
		utftext += String.fromCharCode((c&63)|128);}
	}
	return utftext;
}

function decode_utf8(utftext) {
	var plaintext = ""; var i=0; var c=c1=c2=0;
	// while-Schleife, weil einige Zeichen uebersprungen werden
	while(i<utftext.length)	{
		c = utftext.charCodeAt(i);
		if (c<128) {
			plaintext += String.fromCharCode(c);
			i++;}
		else if((c>191) && (c<224)) {
			c2 = utftext.charCodeAt(i+1);
			plaintext += String.fromCharCode(((c&31)<<6) | (c2&63));
			i+=2;}
		else {
			c2 = utftext.charCodeAt(i+1); c3 = utftext.charCodeAt(i+2);
			plaintext += String.fromCharCode(((c&15)<<12) | ((c2&63)<<6) | (c3&63));
			i+=3;}
		}
	return plaintext;
}


function getData() {
	var localTotal;
	var localRecent;

    if (http_request.readyState == 4) {
        if (http_request.status == 200) {
			var doc = http_request.responseXML;
			var status = doc.getElementsByTagName('status').item(0);
			if (status.firstChild.data == 'failure') {
				setGreen('greendiv3');
			} else {
				var user = doc.getElementsByTagName('screenName').item(0);
				var city = doc.getElementsByTagName('city').item(0);
				try {
					var state = doc.getElementsByTagName('state').item(0);
					document.getElementById("tdstate").innerHTML = state.firstChild.data;
				} catch (e) {
					var country = doc.getElementsByTagName('country').item(0);
					document.getElementById("tdstate").innerHTML = country.firstChild.data;
				}
				var avatar = doc.getElementsByTagName('avatar').item(0);
				var byunit = doc.getElementsByTagName('distanceUnit').item(0);
				var total = doc.getElementsByTagName('totalDistance').item(0);
				var duration = doc.getElementsByTagName('totalDuration').item(0);
				var totalruns = doc.getElementsByTagName('totalRuns').item(0);
				var recentrun = doc.getElementsByTagName('distance').item(0);
				var powersong = doc.getElementsByTagName('title').item(0);
				var artist = doc.getElementsByTagName('artist').item(0);
				var album = doc.getElementsByTagName('album').item(0);
				document.getElementById("tduser").innerHTML = user.firstChild.data;
				document.getElementById("tdcity").innerHTML = city.firstChild.data;
				try {
				var songQuery = escape('artistTerm=' + artist.firstChild.data + '&songTerm=' + powersong.firstChild.data + '&albumTerm=' + album.firstChild.data);
				var urlsong = escape('http://phobos.apple.com/WebObjects/MZSearch.woa/wa/advancedSearchResults?' + songQuery);
				} catch (e) {
				} 
				if (byunit.firstChild.data == 'mi')	{
					localTotal = total.firstChild.data*0.621371192;
					localRecent = recentrun.firstChild.data*0.621371192;
				} else {
					localTotal = total.firstChild.data;
					localRecent = recentrun.firstChild.data;
				}
				tempDuration = duration.firstChild.data / 1000 ;
				if (avatar.firstChild.data.substr(0,4) == 'http')	{
					uploadavaImg = '<img src="'+ avatar.firstChild.data + '" alt="" width="75" height="35" border="0">';
					document.getElementById("avatar").innerHTML = uploadavaImg;
				} else	{
					var i=0
					for (i=0;i<=5;i++) {
						if (avatar.firstChild.data == i) {
						var j = i + 1;
						avaImg = '<img src="' + avatarURL + '/nikeplus/v1/swf/images/avatars/'+ j + '.jpg" alt="" width="75" height="35" border="0">';
						document.getElementById("avatar").innerHTML = avaImg;
						}
					}
				} 
				if (recentrun.firstChild.data != null)	{
					lastRun = tempLastRun + '<br><span class="boldredlg">'+ Math.round(localRecent*100)/100 +'</span> <span class="totalunit">'+ byunit.firstChild.data +'</span>';
					document.getElementById("tdrecentrun").innerHTML = lastRun;
				}
				if (total.firstChild.data != null)	{
					var average = tempDuration / localTotal;
					var tempaverage = average / 60;
					var averagetotal = average % 60;
					totalRun = '<b>'+ Math.round(localTotal*100)/100 +'</b> '+ byunit.firstChild.data + ' ' + tempTotal + '<br><b>'+ Math.floor(tempaverage*1)/1 +'&rsquo;'+ Math.round(averagetotal*1)/1 + '&rdquo;</b> / '+ byunit.firstChild.data;
					document.getElementById("tdtotal").innerHTML = totalRun;
				} else	{
					document.getElementById("tdtotal").innerHTML = 'No runs so far';
				} 
				try {
					if (powersong.firstChild.data.length > 25)	{
							var tempsong = powersong.firstChild.data.substr(0,25) + '...';
						} else	{
							var tempsong = powersong.firstChild.data;
						} 
					chosenSong = '<a href="http://click.linksynergy.com/fs-bin/stat?id=1/9Ueoq1xdg&offerid=78941&type=3&subid=0&tmpid=1826&RD_PARM1='+ urlsong +'" target="_blank"><b>'+ tempsong +'</b></a>'
//					chosenSong = '<a href="STILL WORK IN PROGRESS" target="_blank"><b>'+ tempsong +'</b></a>'
					document.getElementById("tdpowersong").innerHTML = chosenSong;
					document.getElementById("tagpowersong").innerHTML = 'Powersong';
				} catch (e) {
					document.getElementById("tagpowersong").innerHTML = 'Powersong';
					document.getElementById("tdpowersong").innerHTML = 'None';
				}
				setWhite('demodiv');
			} 
        } else {
            alert('1.) There was a problem with the XML request.');
        }
    }
}

function getChallenge() {
    if (http_request.readyState == 4) {
        if (http_request.status == 200) {
		    var agt=navigator.userAgent.toLowerCase();
		    var appVer = navigator.appVersion.toLowerCase();
		    var is_mac = (agt.indexOf("mac")!=-1);
		    var is_safari = ((agt.indexOf('safari')!=-1)&&(agt.indexOf('mac')!=-1))?true:false;
			var counter = 0;
			var msg = "";
			var doc = http_request.responseXML;
			var challengename = doc.getElementsByTagName("name");
			var challenge = doc.getElementsByTagName("challenge");
			var owner = doc.getElementsByTagName("owner");
			var active = doc.getElementsByTagName("active");
			tempChallenge = challenge.length;
			for (var x=0; x < challengename.length; x++) {
				var name = challengename[x].firstChild;
				var idnumber = challenge[x];
				if (name.nodeValue.length > 20)	{
					var tempname = name.nodeValue.substr(0,20) + '...';
				} else	{
					var tempname = name.nodeValue;
				}
				if ((owner[x].firstChild.nodeValue == 'true') && (active[x].firstChild.nodeValue == 'true')){
					msg += '<input type="checkbox" value="' + idnumber.getAttribute("id") + '" name="chkbx"> ' + tempname + '<br>\n';
					counter = counter + 1;
				} else {
				}
			}
			if (counter == 0) {
				setGreen('greensuccess');
				document.getElementById("tdsuccess").innerHTML = "You have no challenges.";
			} else if (counter < 6) {
				setGreen('greendiv2');
				document.getElementById("tdchallenge2").innerHTML = msg;
			} else {
				if (is_mac && is_safari) {
					setGreen('greendiv2');
					document.getElementById("tdchallenge2").innerHTML = msg;
				}
				else {
					setGreen('greendiv');
					document.getElementById("lyr1").innerHTML = msg;
					initScrollLayer();
				}
			}
        } else {
            alert('2.) There was a problem with the XML request.');
        }
    }
}

function invite(frm){
	var url = "xmlServiceProxy.jsp?service=add_challenge_member&email=";
	var finalurl;
	for (i = 0; i < frm.chkbx.length; i++)
	if (frm.chkbx[i].checked){
		var req = new Object();
		req = url + tempEmail + '&locale=' +  tempLocale + '&id=' + frm.chkbx[i].value;
		tempURL = "/nikeplus/v1/services/app/get_public_user_data.jhtml?id=";
		addToQueue(req);
	}
	if (queue.length == 0){
		alert('No challenges have been selected.');
	} else {
		sendAllRequests();
	}
}

var queue;
queue = new Array();

function addToQueue(req)
{
	queue.push(req);
}

function sendAllRequests()
{
	if (queue.length > 0) {
		var req = queue.pop();
		req.makeChallenge = sendAllRequests;
		makeChallenge(req);
	} else {
		setGreen('greensuccess');
		document.getElementById("tdsuccess").innerHTML = "Your challenges have been sent.";
	}
}

function makeChallenge(url) {

    http_request = false;

    if (window.XMLHttpRequest) { // Mozilla, Safari,...
        http_request = new XMLHttpRequest();
        if (http_request.overrideMimeType) {
            http_request.overrideMimeType('text/xml');
            // See note below about this line
        }
	http_request.onreadystatechange = getSuccess;
    http_request.open('GET', url, true);
    http_request.send(null);
    } else if (window.ActiveXObject) { // IE
        try {
            http_request = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e) {
            try {
                http_request = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e) {}
        }
	http_request.onreadystatechange = getSuccess;
    http_request.open('GET', url, true);
    http_request.send();
    }
    if (!http_request) {
        alert('Cannot create an XML XMLHTTP instance.  It might be a good idea to upgrade your browser.');
        return false;
    }
}

function getSuccess() {
    if (http_request.readyState == 4) {
        if (http_request.status == 200) {
			var doc = http_request.responseXML;
			var status = doc.getElementsByTagName('status').item(0);
			if (status.firstChild.data = 'success') {
				sendAllRequests();
			} 
        } else {
            alert('There was a problem with the XML request.');
        }
    }
}