// Following stats use inversed values, e.g. lower is better
var inversedStats = new Array(
"104", // Putting Average
"108", // Scoring Avg. (Actual)
"116", // Scoring Avg. Before Cut
"117", // Round 3 Scoring Avg.
"118", // Final Round Scoring Average
"119", // Putts Per Round
"120", // Scoring Average
"127", // All-Around Ranking
"129", // Total Driving
"155", // Eagles (Holes per)
"158", // Ball Striking
"171", // Par 3 Performance
"172", // Par 4 Performance
"173", // Par 5 Performance
"207", // Front 9 Scoring Avg.
"208", // Back 9 Scoring Avg.
"331", // Proximity to Hole
"336", // Approaches from > 200 Yards
"375", // Proximity to Hole from Sand
"426", // 3-Putt Avoidance
"431", // Fairway Proximity
"437", // Rough Proximity
"459"  // Left Rough Tendency
);
							 
// returns true if a lower score is positive (inversed)
function isLowerScoreBetter(statId) {
    for (var i = 0; i < inversedStats.length; i++) {
        if (inversedStats[i] == statId) {
            return true;
        }
    }
    return false;
}

// The xmlHttp object for handling xmlHttp requests
var xmlHttp;

// Specifies if we are currently querying for left (1) or right (2) player, or avg (3)
var leftRight;

// the tourcode of the first player
var currentTourCode;

// this function is triggered by a click on "Submit" button on the comparison page
function comparePlayers() {
    xmlHttp = GetXmlHttpObject();
    if (xmlHttp == null) {
        alert ("Browser does not support HTTP Request");
        return;
    } 
    updatePlayer('1');
}

// updates a player
// 1 for the left player, 2 for the right player and 3 for the
// tour average. updatePlayer(1) calls updatePlayer(2) once finished,
// updatePlayer(2) calls updatePlayer(3) once finished.
function updatePlayer(side) {
    // disable the average feature for the moment
    if (side == '3') return;
	
    try {
        leftRight = side;
        var urlBegin = "/.element/ssi/sect/1.0/players/" ;
        var urlEnd = "body/comparison-miniStats.xml";
        var playerSplitted;
    
        // get the if of the selected player
        if (side == '3') {
            playerSplitted = '99999';
        } else {
            playerSplitted = document.getElementById("player" + side).value;
        }
        
        playerSplitted = splitPlayerId(playerSplitted);
        var url = urlBegin + playerSplitted + urlEnd;
        
        // Forcing new xmlHttp object
        xmlHttp = GetXmlHttpObject();
        
        // trigger the ajax call, stateChanged is called once the requested file
        // has been received
        xmlHttp.onreadystatechange = stateChanged;
        xmlHttp.open("GET",url,true);
        xmlHttp.send(null);
    } catch (err) {
        // No player has been chosen 
        // for the moment we do simply nothing
        //alert("Error while sending Http request" + err)
        
        // also load tour average if second player hasn't been chosen
        if (side != '3') {
        	updatePlayer ('3');
        }
    }

}

function stateChanged() { 
    if (xmlHttp.readyState == 4 || xmlHttp.readyState == "complete") {
        var xmlDocument;
        // due to a bug in Firefox we have to parse the result text
        // into xml. (document.domain is set in cnn_adspaces.js)
        // https://bugzilla.mozilla.org/show_bug.cgi?id=326337
        // DOMParser is not defined on IE
        if (typeof DOMParser != "undefined") {
           xmlDocument = (new DOMParser()).parseFromString(xmlHttp.responseText, "text/xml");
        } else {
           xmlDocument = xmlHttp.responseXML;
        }
        
        // remove everything if this is the left player column
        if (leftRight == '1') {
            removeRows();
            addRows(xmlDocument);
        }
        
        var player = xmlDocument.getElementsByTagName('player')[0];
        var x = player.getElementsByTagName('stat');
        if (leftRight == '1') {
            var firstTour = player.getElementsByTagName('tour')[0];
            currentTourCode = firstTour.getAttribute('code');
        } else if (leftRight == '3') {
            var tours = player.getElementsByTagName('tour');
            // Putting a default value if no tour of the current code are available
            x = new Array();
            for (var i = 0; i < tours.length; i++) {
                if (tours[i].getAttribute('code') == currentTourCode) {                
                    x = tours[i].getElementsByTagName('stat');
                }
            }
        }
        
        var playerUrl = player.getAttribute('url');
        
        if (leftRight != '3') {
            document.getElementById("player-url-" + leftRight).innerHTML = "<a href=\"" + playerUrl + "\">full stats</a>";
        }
        
        for (var j = 0; j < x.length; j++) {        
            var statId = x[j].getAttribute("statId");
            var rank;
            var value;
            
            try {
                if (leftRight != '3') {
                    rank = x[j].getElementsByTagName("rank")[0].firstChild.nodeValue;
                }
                
                value = x[j].getElementsByTagName("value")[0].firstChild.nodeValue;                
            } catch(err) {
                // just ignore errors here
            }
            
            try {
                if (rank == 999) {                
                    rank = "-";
                }
        
                if (leftRight != '3') {
                    document.getElementById("rank-" + leftRight + "-" + statId).innerHTML = rank;
                }
           
                document.getElementById("value-" + leftRight + "-" + statId).innerHTML = value;
            } catch(err) {            
                // just ignore errors here
            }
            
            updateDiffs(statId);
        }
        
        // update next player
        if (leftRight == '1')  {
            updatePlayer('2');
        } else if (leftRight == '2') {
            updatePlayer('3');
        }
    } 
}

// updates the differences columns
function updateDiffs(statId) {
    var rankValue = new Array("rank", "value");
    for (var i = 0; i < rankValue.length; i++) {
        // get value for left and right player
        if (! document.getElementById(rankValue[i] + "-1-" + statId)) return;
        var left = document.getElementById(rankValue[i] + "-1-" + statId).innerHTML;
        if (! document.getElementById(rankValue[i] + "-2-" + statId)) return;
        var right = document.getElementById(rankValue[i] + "-2-" + statId).innerHTML;
        
        // calculate the difference
        var leftArray = removeDecoration(left);
        var rightArray = removeDecoration(right);
        var result;
        if (i == 1) {
        	result = leftArray[0] - rightArray[0];
        } else {
        	result = rightArray[0] - leftArray[0];
        }

        // set the difference
        if (isNaN(result)) {
            result = '-';
        } else {
        	rightArray[0] = round(result, 3);
        	
        	// check for values where negative is actually positive :-)
        	if (i == 1 && isLowerScoreBetter(statId)) {
                rightArray[0] = rightArray[0] * -1;
        	}
            if (rightArray[0] < 0) {
                result = "<font color=\"red\">" + addDecoration(rightArray) + "</font>";
            } else {
                result = "<font color=\"green\">" + addDecoration(rightArray) + "</font>";
            }
        }
        document.getElementById("diff-" + rankValue[i] + "-" + statId).innerHTML = result;
    }
}

// adds decorations (e.g. +, -, %) to a value 
function addDecoration(someArray) {
    if (someArray[0] < 0) {
        someArray[0] = '' + someArray[0];
        someArray[0] = someArray[0].substr(1, someArray[0].length - 1);
        someArray[1] = '-' + someArray[1];
    } else {
        someArray[0] = '' + someArray[0];
    	// we want a + at the beginning, even before the $
        someArray[1] = '+' + someArray[1];
    }

    // adding commas
    if (someArray[3] != '') {
        for (var i = someArray[0].length - 3; i > 0; i = i - 3) {
            someArray[0] = someArray[0].substring(0, i) + 
                           someArray[3] + 
                           someArray[0].substring(i, someArray[0].length);
        }    
    }

    return someArray[1] + someArray[0] + someArray[2];
}

// Removes all decorations
// - returns an array of the following format:
//   [0] the "undecoracted" string
//   [1] decoration that comes before the string, if any
//   [2] decoration that comes after the string, if any
//   [3] decoration that separates thousands, if any
function removeDecoration(someString) {
    var decorations = new Array(someString, "", "", "");
	
    // removing ','
    if (someString.indexOf(',') != -1) {
    	var pos = -1;    
    	while ((pos = someString.indexOf(',', pos)) != -1) {
        	someString = someString.substr(0, pos) + someString.substr(pos + 1, (someString.length - 1) - pos);
        	decorations[0] = someString;
       	}
        decorations[3] = ',';    
    }
    
    // removing '%'
    if (someString.indexOf('%') != -1) {
        decorations[0] = someString.substr(0, someString.length - 1);
        decorations[2] = someString.charAt(someString.length - 1);
    }

	// removing '$'
    if (someString.indexOf('$') != -1) {    
        decorations[0] = someString.substr(1, someString.length - 1);
        decorations[1] = someString.charAt(0);
    }
    return decorations;
}

// Adds rows for all displayed stats
function addRows(xmlDocument) {

    var table = document.getElementById('comparisonTable');
    var dropDown = document.getElementById('stat_cat');
    
    var categories = xmlDocument.getElementsByTagName('statCat');
    var categoriesDropDown = '';
        
    // Putting the first one as default
    var category = xmlDocument.getElementsByTagName('statCat')[0];

    // save the currently selected category
    var previouslySelected = dropDown.value;

	// we have to use W3C DOM as select.innerHTML doesn't work on IE
    // remove all options currently present    
	if(dropDown.options){
		for(i=0;i<dropDown.options.length;i++){
			dropDown.options[i] = null;
			i--;
		}
	}
	
	// add all options
	for (var i = 0; i < categories.length; i++) {
        var catName = categories[i].getAttribute('catName');        
    
    	var opt = document.createElement('option');
		opt.text = catName;
		opt.value = catName;

        // if we find a category with the same name, select that one
        if (catName == previouslySelected) {
            category = categories[i];
            opt.selected = "selected";
        }
        dropDown.options.add (opt);
    }
    
    xmlDocument.getElementsByTagName('statCat')[0];
    var stats = category.getElementsByTagName('stat');
    
    for (var i = 0; i < stats.length; i++) {    
        var stat = stats[i];
        var statName = stat.getAttribute('statName');
        var statId = stat.getAttribute('statId');
        var row = table.insertRow(3 + i);
        
        // set backgroud color of row
        if ((i % 2) == 1) {
            row.className = "bg2";
        } else {
            row.className = "bg3";
        }

		// stat name
        var cell0 = row.insertCell(0);
        cell0.align = "left";
        cell0.innerHTML = "<a href=\"/r/stats/current/" + statId + ".html\">" + statName + "</a>";

		// spacer cell
        var cell1 = row.insertCell(1);
        cell1.align = "center";
        cell1.innerHTML = "&nbsp;";
        
        // first player rank
        var cell2 = row.insertCell(2);
        cell2.align = "center";
        cell2.innerHTML = "<span id=\"rank-1-" + statId + "\">&nbsp;</span>";
        
        // first player value
        var cell3 = row.insertCell(3);
        cell3.align = "center";
        cell3.innerHTML = "<span id=\"value-1-" + statId + "\">&nbsp;</span>";
        
        // vs. rank
        var cell4 = row.insertCell(4);
        cell4.align = "center";
        cell4.innerHTML = "<span id=\"diff-rank-" + statId + "\">-</span>";
        
        // vs. value
        var cell5 = row.insertCell(5);
        cell5.align = "center";
        cell5.innerHTML = "<span id=\"diff-value-" + statId + "\">-</span>";
        
        // second player rank
        var cell6 = row.insertCell(6);
        cell6.align = "center";
        cell6.innerHTML = "<span id=\"rank-2-" + statId + "\">&nbsp;</span>";
        
        // second player value
        var cell7 = row.insertCell(7);
        cell7.align = "center";
        cell7.innerHTML = "<span id=\"value-2-" + statId + "\">&nbsp;</span>";
        
        // spacer cell
        var cell8 = row.insertCell(8);
        cell8.align = "center";
        cell8.innerHTML = "&nbsp;";
        
        // tour average
        var cell9 = row.insertCell(9);
        cell9.align = "center";
        cell9.innerHTML = "<span id=\"value-3-" + statId + "\">&nbsp;</span>";
    }
}

// removes all but the last and the first two rows from the table
function removeRows() {
    var table = document.getElementById('comparisonTable');
    for (var i = table.rows.length - 2; i > 2; i--) {
        table.deleteRow(i);
    }
}

// Round x to the given precision
function round(x, precision) {
	var xTemp = x * Math.pow(10,  precision);	
	xTemp = Math.round(xTemp);
	return xTemp / Math.pow(10, precision);
}

// Split a player ID into 3 parts of 2 digits
function splitPlayerId (playerId) {
    if (playerId == "PLAYER") {
        throw "You must choose a player";
    }
    var sixDigitPlayerId = fillWithZeros(playerId, 6);
    return sixDigitPlayerId.substr(0, 2) + '/' + 
           sixDigitPlayerId.substr(2, 2) + '/' + 
           sixDigitPlayerId.substr(4, 2) + '/';
}

// expands a string to the given length by prepending it with zeros
function fillWithZeros(someString, length) {
    var finalString = someString;
    if (someString.length < length) {
        finalString = fillWithZeros('0' + someString, length);
    }
    return finalString;
}

// Returns the xmlHttp object, in MS Internet Explorer or Firefox
function GetXmlHttpObject() {
    var objXMLHttp = null;
    
    // IE7 also implements window.XMLHttpRequest,
    // but xmlDocument.getElementsByTagName doesn't
    // work for some reason. For the moment let's use
    // ActiveX even on IE7
    if (window.ActiveXObject) {
        objXMLHttp = new ActiveXObject("Microsoft.XMLHTTP");
    } else if (window.XMLHttpRequest) {
        objXMLHttp = new XMLHttpRequest();
    }
    return objXMLHttp;    
}
