var browserOS;
var browserName;
var browserVersion;
var strDogID = strGetDogID();
var dogData = new Array();


// --------------------------------------------
var debugWin;
function debugwrite(str) {
alert(str);
/*
    if (debugWin == null || debugWin.closed) {
	    debugWin = window.open("", "debugWin", "width=450,height=600,scrollbars,resizable");
    }
    debugWin.document.write(str + "<BR>");
*/
}

// --------------------------------------------
function getBrowserID() {
    var appVersion = navigator.appVersion;
	if (appVersion.indexOf("Win") > 0) {
        browserOS = "WIN";
    } else if (appVersion.indexOf("Mac") > 0) {
        browserOS = "MAC";
    } else if (appVersion.indexOf("X11") > 0) {
        browserOS = "UNX";
    } else {
        browserOS = "UNK";
    }

	var browser = navigator.appName;
    if (browser.substring(0, 8) == "Netscape") {
        browserName = "NN";
    } else if (browser.substring(0, 9) == "Microsoft") {
        browserName = "IE";
    } else {
        browserName = browser;
    }

	var msidx = appVersion.indexOf("MSIE");
	if (msidx > 0) {
       browserVersion = parseFloat(appVersion.substring(msidx+5)) * 1000;
	} else {
       browserVersion = parseFloat(appVersion) * 1000;
	}
}

function islower(c) {
	if (c >= 'a' && c <= 'z')
		return true;
	else
		return false;
}

// --------------------------------------------
function OneDog(n, d, f) {
    this.name = n;
    this.data = d;
    this.file = f;
    this.score = 0;
    this.rank = 0;
}


//***********************************
function Const() {

}

	Const.Size = 0;
	Const.Coat = 1;
	Const.Barking = 2;
	Const.Type = 3;
	Const.Friendliness = 4;
	Const.Independence = 5;

	Const.Dominance = 6;
	Const.Trainability = 7;
	Const.Exercise = 8;
	Const.Grooming = 9;
	Const.Professional = 10;
	Const.Docking = 11;

	Const.Novice = 12;

	Const.Children = 13;
	Const.Pets = 14;
	Const.Space = 15;
	Const.Weather = 16;

	Const.Service = 17;
	Const.Jogging = 18;

	Const.Hunting = 19;
	Const.Sighting = 20;
	Const.Tracking = 21;
	Const.Retrieving = 22;
	Const.Pointing = 23;
	Const.Herding = 24;
	Const.Watchdog = 25;
	Const.Guarding = 26;
	Const.Police = 27;
	Const.Search_Rescue = 28;
	Const.Water_Rescue = 29;
	Const.Guiding = 30;
	Const.Sledding = 31;
	Const.Carting = 32;
	Const.Weights = 33;
	Const.Agility = 34;
	Const.Lure = 35;
	Const.Obedience = 36;
	Const.Schutzhund = 37;
	Const.Tricks = 38

	Const.FlagLast = 39;

	Const.EXACTMATCH = 50;
	Const.OFFBYONE = Const.EXACTMATCH/5;
	Const.OFFBYTWO = Const.EXACTMATCH/10;
	Const.IMPORTANTMATCH = Const.EXACTMATCH*2;
	Const.SECONDDOM = Const.EXACTMATCH;

// --------------------------------------------
var userSizeM = "";
var userCoatM = "";
var userTypesM = "";
var userTraining = 0;
var userHasTrained = 0;
var userExercise = 0;
var userGrooming = 0;
var userProfGrooming = 0;
var userIndependence = 1;
var userFriendlyM = "";
var userDom1 = 1;
var userDom2 = 0;
var userPeople, userPets;
var userSpace = 1;
var userClimate = 0;
var userTalents = "NNNNNNNNNNNNNNNNNNNNNNN";

var typeNames = "ABCDEFGHIJK";

// --------------------------------------------
function quickSortSwap(idx, odx) {
   temp = dogData[idx];
   dogData[idx] = dogData[odx];
   dogData[odx] = temp;
}

// --------------------------------------------
function quickSort(lower, upper) {
   if (lower < upper) {
      quickSortSwap(lower, Math.floor((upper+lower)/2));
      pivot = dogData[lower];
      m = lower;
      for (var idx = lower + 1; idx <= upper; idx++) {
         if (dogData[idx].score < pivot.score) {
             m++;
             quickSortSwap(m, idx);
         }
      }
      quickSortSwap(lower, m);
      quickSort(lower, m - 1);
      quickSort(m + 1, upper);
   }
}

// ------------------------------
function getVarsFromCookie() {
    var allCookies = "" + document.cookie;
    //debugwrite("allCookies=" + allCookies);
    var start = allCookies.indexOf("breedSelectorData=");
    //debugwrite("start=" + start);

    if (start == -1) {
        alert("In order to use the Breed Selector, you must have cookies enabled in your browser.");
    } else {
        start += "breedSelectorData=".length;
        var end = allCookies.indexOf(':', start);
        if (end == -1) {
            end = allCookies.length;
        }

        var cookieString = unescape(allCookies.substring(start, end));

        //debugwrite("cookieString=" + cookieString);

        var tokens = cookieString.split("&");

        userSizeM = tokens[0];
        userCoatM = tokens[1];
        userTypesM = tokens[2];
        userFriendlyM = tokens[3];
        userIndependence = tokens[4];
        userDom1 = tokens[5];
        userDom2 = tokens[6];
        userTraining = tokens[7];
        userExercise = tokens[8];
        userGrooming = tokens[9];
        userProfGrooming = tokens[10];

        userHasTrained = (tokens[11] == "Y");

        userPeople = tokens[12];
        userPets = tokens[14];
        userSpace = tokens[16];
        userClimate = tokens[17];
        userTalents = tokens[18];

        var semiPos = userTalents.indexOf(";");
        if (semiPos > -1) {
            userTalents = userTalents.substring(0, semiPos);
        }


        //debugwrite("userSizeM=" + userSizeM);
        //debugwrite("userCoatM=" + userCoatM);
        //debugwrite("userTypesM=" + userTypesM);
        //debugwrite("userTalents=" + userTalents);
    }
}

// --------------------------------------------
function doTheRankings() {
    var idx, dogIdx, dogAttr, usrAttr, dogAttr2;
    var	maxScore, oneDogData;

    if (dogData == null) {
	    initDogData();
    }
    if (dogData.length == 0) {
	    initDogData();
    }

	/* --------------------------------------*/
	maxScore = 0;

	if (userTypesM != null && userTypesM.length > 0)
		maxScore += Const.IMPORTANTMATCH*2;
	if (userSizeM != null && userSizeM.length > 0)
		maxScore += Const.IMPORTANTMATCH;
	if (userCoatM != null && userCoatM.length > 0)
		maxScore += Const.EXACTMATCH;

	if (userTraining == 1 ||
	    userTraining == 5)
		maxScore += Const.IMPORTANTMATCH;
	else if (userTraining > 0)
		maxScore += Const.EXACTMATCH;

	if (userExercise != 0)
		maxScore += Const.EXACTMATCH;
	if (userGrooming != 0)
		maxScore += Const.EXACTMATCH;
	if (userProfGrooming != 0)
		maxScore += Const.EXACTMATCH;

	maxScore += Const.EXACTMATCH;

	maxScore += Const.IMPORTANTMATCH;
	if (userDom2 > 0)
		maxScore += Const.SECONDDOM;

	if (userFriendlyM != null && userFriendlyM.length > 0)
		maxScore += Const.EXACTMATCH;

	if (userPeople > 0)
		maxScore += Const.EXACTMATCH;
	if (userPets > 0)
		maxScore += Const.EXACTMATCH;
	if (userSpace > 0)
		maxScore += Const.EXACTMATCH;
	if (userClimate > 0)
		maxScore += Const.EXACTMATCH;

	for (idx=Const.Service; idx <= Const.Tricks+1 && /* the extra 1 is for companion dog */
										idx-Const.Service < userTalents.length; idx++)
		if (userTalents.charAt(idx-Const.Service) == 'Y')
			maxScore += Const.EXACTMATCH;
		else if (userTalents.charAt(idx-Const.Service) == 'I')
			maxScore += Const.IMPORTANTMATCH;

	// --------------------------------------------
	for (dogIdx=0; dogIdx < dogData.length; dogIdx++) {
		oneDogData = dogData[dogIdx].data;
		var thisScore = 0;

		dogAttr = null;
		dogAttr = oneDogData.charAt(Const.Size);
		for (idx=0; idx < userSizeM.length; idx++) {
			if (userSizeM.charAt(idx) == dogAttr) {
				thisScore += Const.IMPORTANTMATCH;
				break;
			} else if (Math.abs(dogAttr - userSizeM.charAt(idx)) == 1) {
				thisScore += Const.OFFBYONE;
				break;
			}
		}

		dogAttr = oneDogData.charAt(Const.Type);
		if (islower(dogAttr)) {
			dogAttr = dogAttr.toUpperCase();
			dogAttr2 = 'F';
		} else if (dogAttr == 'Z') {
			dogAttr = 'A';
			dogAttr2 = 'J';
		} else {
			dogAttr2 = 0;
		}

		for (idx=0; idx < userTypesM.length; idx++) {
			if (userTypesM.charAt(idx) == dogAttr) {
				thisScore += Const.IMPORTANTMATCH*2;
				break;
			}
			if (userTypesM.charAt(idx) == dogAttr2) {
				thisScore += Const.IMPORTANTMATCH*2;
				break;
			}
		}

		dogAttr = oneDogData.charAt(Const.Coat);
		for (idx=0; idx < userCoatM.length; idx++) {
			if (userCoatM.charAt(idx) == dogAttr)
				thisScore += Const.EXACTMATCH;
		}

		dogAttr = oneDogData.charAt(Const.Friendliness);
		for (idx=0; idx < userFriendlyM.length; idx++)
			if (userFriendlyM.charAt(idx) == dogAttr)
				thisScore += Const.EXACTMATCH;

		dogAttr = oneDogData.charAt(Const.Independence);
		usrAttr = userIndependence;
		if (dogAttr != 0 && usrAttr != 0) {
			if (dogAttr >= usrAttr)
				thisScore += Const.EXACTMATCH;
			else if (Math.abs(dogAttr - usrAttr) == 1)
				thisScore += Const.OFFBYONE;
		}

		if (userTraining == 1) {
			dogAttr = oneDogData.charAt(Const.Dominance);
			if (dogAttr <= 2)
				thisScore += Const.IMPORTANTMATCH;
			else if (dogAttr == 3)
				thisScore += Const.OFFBYONE;
		} else if (userTraining == 5) {
			dogAttr = oneDogData.charAt(Const.Trainability);
			if (dogAttr == 5)
				thisScore += Const.IMPORTANTMATCH;
			else if (dogAttr == 4)
				thisScore += Const.EXACTMATCH;
		} else if (userTraining > 0) {
			dogAttr = oneDogData.charAt(Const.Trainability);
			if (dogAttr >= userTraining)
				thisScore += Const.EXACTMATCH;
		}

		dogAttr = oneDogData.charAt(Const.Exercise);
		if (dogAttr != 0 && userExercise != 0) {
			if (dogAttr <= userExercise)
				thisScore += Const.EXACTMATCH;
			else if (Math.abs(dogAttr - userExercise) == 1)
				thisScore += Const.OFFBYONE;
		}

		dogAttr = oneDogData.charAt(Const.Grooming);
		if (dogAttr != 0 && userGrooming != 0) {
			if (dogAttr <= userGrooming)
				thisScore += Const.EXACTMATCH;
			else if (Math.abs(dogAttr - userGrooming) == 1)
				thisScore += Const.OFFBYONE;
		}

		dogAttr = oneDogData.charAt(Const.Professional);
		if (dogAttr != 0 && userProfGrooming != 0) {
			if (dogAttr <= userProfGrooming)
				thisScore += Const.EXACTMATCH;
			else if (Math.abs(dogAttr - userProfGrooming) == 1)
				thisScore += Const.OFFBYONE;
		}

		dogAttr = oneDogData.charAt(Const.Children);
		if (dogAttr != 0 && userPeople != 0) {
			if (dogAttr == userPeople)
				thisScore += Const.EXACTMATCH;
			else if (Math.abs(dogAttr - userPeople) == 1)
				thisScore += Const.OFFBYONE;
		}

		dogAttr = oneDogData.charAt(Const.Pets);
		if (dogAttr != 0 && userPets != 0) {
			if (dogAttr == userPets)
				thisScore += Const.EXACTMATCH;
			else if (Math.abs(dogAttr - userPets) == 1)
				thisScore += Const.OFFBYONE;
		}

		dogAttr = oneDogData.charAt(Const.Space);
		if (dogAttr != 0 && userSpace != 0) {

			if (dogAttr <= userSpace)
				thisScore += Const.EXACTMATCH;
			else if (Math.abs(dogAttr - userSpace) == 1)
				thisScore += Const.OFFBYONE;
		}

		dogAttr = oneDogData.charAt(Const.Weather);
		if (dogAttr != 0 && userClimate != 0) {

			if (dogAttr == 3)
				thisScore += Const.EXACTMATCH;
			else
				if (dogAttr == userClimate)
					thisScore += Const.EXACTMATCH;
		}

		if (userTalents.charAt(0) == 'Y' || userTalents.charAt(0) == 'I') {		// Service
			if (oneDogData.charAt(Const.Service) > '0') {
				if (userTalents.charAt(0) == 'I')
					thisScore += Const.IMPORTANTMATCH;
				else
					thisScore += Const.EXACTMATCH;
			}
		}

		if (userTalents.charAt(1) == 'Y' || userTalents.charAt(1) == 'I') {		// Jogging
			dogAttr = oneDogData.charAt(Const.Jogging);
			if (dogAttr == 5) {
				if (userTalents.charAt(1) == 'I')
					thisScore += Const.IMPORTANTMATCH;
				else
					thisScore += Const.EXACTMATCH;
			} else if (dogAttr == 4) {
				if (userTalents.charAt(1) == 'I')
					thisScore += Const.EXACTMATCH;
				else
					thisScore += Const.OFFBYONE;
			} else if (dogAttr == 3)
				thisScore += Const.OFFBYTWO;
		}

		if (userTalents.charAt(22) == 'Y' || userTalents.charAt(22) == 'I') {
			dogAttr = oneDogData.charAt(Const.Children);
			if (dogAttr == 5) {
				if (userTalents.charAt(22) == 'I')
					thisScore += Const.IMPORTANTMATCH;
				else
					thisScore += Const.EXACTMATCH;
			} else if (dogAttr == 4) {
				if (userTalents.charAt(22) == 'I')
					thisScore += Const.EXACTMATCH;
				else
					thisScore += Const.OFFBYONE;
			}
			else if (dogAttr == 3)
				thisScore += Const.OFFBYTWO;
		}

		for (idx=Const.Hunting; (idx <= Const.Tricks)
							&& ((idx-Const.Service) < userTalents.length); idx++) {
			if (oneDogData.charAt(idx) == 'Y') {
				if (userTalents.charAt(idx-Const.Service) == 'Y')
					thisScore += Const.EXACTMATCH;
				else if (userTalents.charAt(idx-Const.Service) == 'I')
					thisScore += Const.IMPORTANTMATCH;
			}
		}

		if (!userHasTrained && (oneDogData.charAt(Const.Novice) == 'Y')) {
			thisScore += Const.EXACTMATCH;
	    }

		dogAttr = oneDogData.charAt(Const.Dominance);
		dogAttr = dogAttr * 2;
		if (userDom1 == dogAttr) {
			thisScore += Const.IMPORTANTMATCH;
		} else if (Math.abs(userDom1 - dogAttr) <= 2) {
			thisScore += Const.OFFBYONE;
		} else if (Math.abs(userDom1 - dogAttr) > 5) {
			var toSubtract = Const.EXACTMATCH;

			if (dogAttr > userDom1) {
				toSubtract = Const.IMPORTANTMATCH;

				if (!userHasTrained) {
					toSubtract = toSubtract * 2;

					if (oneDogData.charAt(Const.Novice) == 'N') {
						toSubtract = toSubtract * 2;
					}
				}
			}
			thisScore -= toSubtract;
		}

		if (userDom2 > 0) {
			if (userDom2 == dogAttr) {
				thisScore += Const.SECONDDOM;
			} else if (Math.abs(userDom2 - dogAttr) <= 2) {
				thisScore += Const.OFFBYONE;
			} else if (Math.abs(userDom2 - dogAttr) > 5) {
				thisScore -= Const.SECONDDOM;
			}
		}

		//---------------------------------------------
		if (thisScore < 0)
			thisScore = 0;
		thisScore = (((thisScore) * 100) / maxScore);

		dogData[dogIdx].score = Math.round(thisScore);

	}

	quickSort(0, dogData.length - 1);
	
//	CalculateRank();
}


function CalculateRank()
{
    var intIndex = 1;
    var intLastScore = 101;
    var intCurrentRank = 1;
    
    for (var dogIdx = dogData.length - 1; dogIdx >= (dogData.length - 30); dogIdx--)
	{
	    if (dogData[dogIdx].score < intLastScore)
	    {
    	    intLastScore = dogData[dogIdx].score;
    	    dogData[dogIdx].rank = intIndex;
    	    intCurrentRank = intIndex;
    	}
    	else
    	{
    	   dogData[dogIdx].rank = intCurrentRank;
    	}
	    
	    intIndex++;
	}
}


function initResults()
{
     getVarsFromCookie();
     doTheRankings();
     showResultsTable();
}


function showResultsTable()
{
    var intIndex = 0;
    var intPage = intGetCurrentPage();
    showResults(intPage);
}


// --------------------------------------------
function showResults(intPage)
{
	var intResultsStart = dogData.length - 1;
	var intIndex = 0;
	
	
	if (intPage > 1)
	{
	    intResultsStart -= ((intPage - 1) * 5)
	}
	
	for (var dogIdx = intResultsStart; dogIdx >= (intResultsStart - 4); dogIdx--)
	{
	    intIndex = (intResultsStart - dogIdx);
    	
    	if (strDogID == dogData[dogIdx].file)
    	{
    	    document.getElementById('spnDog' + intIndex).innerHTML = dogData[dogIdx].name;
    	}
    	else
    	{
    	    document.getElementById('spnDog' + intIndex).innerHTML = '<p><a style="text-decoration:none" href="' + strGetUrlPath() + '/dog-breeds/' + dogData[dogIdx].file + '/' + intPage + '">' + dogData[dogIdx].name + '</a></p>';
        }
    	
    	document.getElementById('spnRank' + intIndex).innerHTML = dogData[dogIdx].score + "%";
	}
	
	
	for (intIndex = 1; intIndex < 6; intIndex++)
	{
	    if (intPage == intIndex)
	    {
	        document.getElementById('spnPage' + intIndex).innerHTML = intIndex;
	    }
	    else
	    {
	        document.getElementById('spnPage' + intIndex).innerHTML = '<a style="color:#555555; text-decoration:none" href="javascript:showResults(' + intIndex + ');">' + intIndex + '</a>';
	    }
	}
}


function strGetUrlPath()
{
    var m = location.href.match(/(.*)\/([^\/\\]+\.\w+)$/);
    return RegExp.$1;
}


function strGetDogID()
{
    var intPageStart = location.search.indexOf("&page=");
    
    if (intPageStart > -1)
    {
        return location.search.substr(7, (intPageStart - 7));
    }
    else
    {
        return location.search.substr(7);
    }
}

function intGetCurrentPage()
{
    if (location.search.length > 0)
    {
        var m = location.search.split("&page=");
        
        if (isNaN(m[1]))
        {
            m = m[1].split("&");
            
            if (isNaN(m[0]))
            {
                return 1;
            }
            else
            {
                 return parseInt(m[0]);
            }
        }
        else
        {
            return parseInt(m[1]);
        }
    }
    else
    {
        return 1;
    }
}
