function getObj(n){return(document.getElementById(n))}
var timesused	= 0;
var analyzed	= false; // gets set to true when we run an analysis - used to make the UI cleaner
var weapon 	= new Array();
var armor		= new Array();
var vehicle	= new Array();
var animal = new Array();
var other		= new Array();
var boosts	= new Array();

var cities		= new Array();
var citypos	= 0; // which city is on the left side of the scroller
var cityIDs		= 1;

var tabs		= new Array(); // array of UI tabs
var eventTab,crateTab;
var formdoc;

var percentiletimer = 0;
var percentileattempt = 0;

//-----------  cookie information ------------------------------------------------
var outputmode 	= 1; // graphics
var lootmode	= 1; // weapon/armor/vehicles/special
var collector	= 0; // I'm a collector (keeps at least one in inventory for gifting) 0 or 1
//-----------------------------------------------------------------------------------------

var importerState 	= true;
var lootOrder	= 0;
var bestAWeapon,bestDWeapon;
var bestAArmor,bestDArmor;
var bestAVehicle,bestDVehicle;
var bestAAnimal,bestDAnimal;

var AttackA,AttackD,DefenseA,DefenseD;
var numAWeapons,numAArmor,numAVehicles,numDWeapons,numDArmor,numDVehicles,numAAnimals,numDAnimals;
var boostAttack,boostDefense,boostRobbing;

var OAPercentile = -1;
var ODPercentile = -1;
var WAPercentile = -1;
var AAPercentile = -1;
var VAPercentile = -1;
var NAPercentile = -1;
var WDPercentile = -1;
var ADPercentile = -1;
var VDPercentile = -1;
var NDPercentile = -1;
var PAPercentile = -1;
var PDPercentile = -1;

var affiliates = [
                    '<a href="http://304caqqrmkoalc20y6bxue1m0t.hop.clickbank.net/?tid=GHBGHSRX" target="_top"><img border="0" style="padding-top: 8px;" src="http://www.dominatemafiawars.com/images/banners/468x60.gif" width="434" /></a>',
                    '<a href="http://cbaffhopdtwyfc0j320jil8va-.hop.clickbank.net/?tid=SUNNY1" target="_top"><img border="0" style="padding-top: 8px;" src="http://images.blofelds.com/MWB468x60.gif" width="434" /></a>',
                    '<a href="http://5d230lshol26qcxj8z-kfn4v1z.hop.clickbank.net/?tid=SUNNY2" target="_top"><img border="0" style="padding-top: 8px;" src="http://images.blofelds.com/MWBB468x60.gif" width="434" /></a>',
                    '<a href="http://cc728cljftxyog6if8o6shzu73.hop.clickbank.net/?tid=SNIPER1" target="_top"><img border="0" style="padding-top: 8px;" src="http://images.blofelds.com/maf728.gif" width="434" /></a>',
                 ];
                 
function getGiftString(type,giftid)
{
	var giftcategory = "1";

	if(type == "B")
		giftcategory = "2";

	var giftstring = "http://apps.facebook.com/inthemafia/track.php?next_controller=loot&next_action=wishlist_add&next_params=%7B%22gift_category%22%3A%22" + giftcategory + "%22%2C%22gift_id%22%3A%22" + giftid + "%22%7D";

	return(giftstring);
}

var WeaponAttackStat=0;
var ArmorAttackStat=0;
var VehicleAttackStat=0;
var AnimalAttackStat=0;
var WeaponDefenseStat=0;
var ArmorDefenseStat=0;
var VehicleDefenseStat=0;
var AnimalDefenseStat=0;

var currentTab;
var currentTypeTab,currentLocTab;


function UITab(name,lootlist,divID,iscity)
{
	this.name = name;
	this.sortedBy = "N";
	this.lootlist = lootlist;
	this.divID = divID;
	this.iscity = iscity;
}

function newtab(name,lootlist,divID,iscity)
{
	var x = new UITab(name,lootlist,divID,iscity);
	tabs[tabs.length] = x;
	return(x);
}

function setCurrentTab(name)
{
	var i;

	for(i=0;i<tabs.length;i++)
		if(tabs[i].name == name)
		{
			currentTab = tabs[i];
			currentTypeTab = name;
            $("#"+tabs[i].divID).css("display","block");
    		return;
		}
}

function city(name,matchtext,key)
{
	this.name = name; // name on the button
	this.sortedBy = "none";
	this.matchtext = matchtext; // what to search for to see if it belongs here
	this.key = key;
	this.loot = new Array(); // put this cities loot here - as loot IDs
}

function newcity(name,matchtext,key)
{
	var obj = new city(name,matchtext,key);
	cities[cities.length] = obj;
	return(obj);
}

function formatCost(num,symbol) 
{
	num = num.toString().replace(/\$|\,/g,'');

	if(isNaN(num))
		num = "0";

	sign = (num == (num = Math.abs(num)));
	num = Math.floor(num*100+0.50000000001);
	num = Math.floor(num/100).toString();

	for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
		num = num.substring(0,num.length-(4*i+3))+','+num.substring(num.length-(4*i+3));

	return (((sign)?'':'-') + symbol + num);
}

function getCurrencySymbol(lootitem)
{
	var symbol = "";

	if(lootitem.cost > 0 )
	{
		var symbol;

		if(lootitem.where.indexOf("NY Mafia Store") == 0)
			symbol = "$";
		else if(lootitem.where.indexOf("Moscow Mafia Store") == 0)
			symbol = "R$";
		else if(lootitem.where.indexOf("Cuba Mafia Store") == 0)
			symbol = "C$";
		else if(lootitem.where.indexOf("Bangkok Mafia Store") == 0)
			symbol = "B$";
		else if(lootitem.where.indexOf("Las Vegas Mafia Store") == 0)
			symbol = "V$";
	}

	return(symbol);
}

function getImageName(lootitem)
{
	var imagename;

	if(lootitem.image)
	{
		imagename = "http://images.blofelds.com/";

		switch(lootitem.type)
		{
			case "W":
				imagename += "weapons/";
			break;

			case "A":
				imagename += "armor/";
			break;

			case "V":
				imagename += "vehicles/";
			break;

            case "N":
                imagename += "animals/";
            break;
            
			case "O":
				imagename += "other/";
			break;

			case "B":
				imagename += "boosts/";
			break;
		}

		imagename += lootitem.image;

	}
	else
		imagename = "noimage.jpg";

	return(imagename);
}

function buildTableRow(lootitem,inCity)
{
	var text ;
	var theattack,thedefense;
	var imagename;
	
	text = "<tr><td style=\"border-bottom: 1px solid #bcd2ea\">";

	theattack = (lootitem.attack == -1) ?  "?" : lootitem.attack;
	thedefense = (lootitem.defense == -1) ? "?" : lootitem.defense;

	imagename = getImageName(lootitem);

	text += "<img style=\"width: 75px; height: 75px\" src='" + imagename + "'/>";
	text += "</td><td style=\"border-bottom: 1px solid #bcd2ea\">";

	var lootname = lootitem.name;

	text += "<span class='mylabel'>" + lootname + "</span><br/>";

	if( (lootitem.type != "O") && (lootitem.type != "B") )
		text += "<img src='attack.png' /> " + theattack + "<img src='defense.png' style='padding-left: 40px'/> " + thedefense;

	text += "<p/><span class='wherefrom'>" + lootitem.where + "</span>";

	if(lootitem.cost > 0 )
	{
		var symbol = getCurrencySymbol(lootitem);

		text += "<br/><span class='wherefrom'>" + formatCost(lootitem.cost,symbol) + "</span>";
	}
	
	text += "</td><td valign='top' style=\"border-bottom: 1px solid #bcd2ea\"><center>";

//	text += "<center>" + insertGoldCoin(lootitem.id) + "</center><br/>";

	if( (lootitem.type != "O") && (lootitem.type != "B") )
	{
		text += "<input type='text' size='5' maxlength='10' id='" +lootitem.uid + "'";

		if(lootitem.quantity > 0 )
			text += " value = '" + lootitem.quantity + "'";
		else
			text += " value=''";

		text += " onchange=\"changeQty('" +lootitem.id + "','"+lootitem.uid + "');\"/>";
	}

	if(lootitem.giftable)
		text += "<br><center><a target=\"new\" href=\"" + getGiftString(lootitem.type,lootitem.lootid) + "\"><img border='0' style=\"padding-top: 3px\" src='images/addtowishlist.jpg' width='29' height='27'></a></center>";
		
	text += "</center></td></tr>";

	return(text);
}

function newitem(name,type,id,where,attack,defense,image,lootid,giftable,needed,single,cost,quantity,city,alt)
{
	var obj = new lootitem(name,type,id,where,attack,defense,image,lootid,giftable,needed,single,cost,quantity,city,alt);
	var cobj;
	var i;
	var CID;

	switch(type)
	{
		case "W":
			weapon[weapon.length] = obj;
		break;

		case "A":
			armor[armor.length] = obj;
		break;

		case "V":
			vehicle[vehicle.length] = obj;
		break;

        case "N":
            animal[animal.length] = obj;
        break;
        
		case "O":
			other[other.length] = obj
		break;

		case "B":
			boosts[boosts.length] = obj;
		break;

	}

	// put this item in the appropriate city 

	for(i=0;i<cities.length;i++) // ignore events/special
	{
		if( (cities[i].key != "E") && (cities[i].key != "R") && (cities[i].key != "Y") ) // skip the event and crate tabs
			if( city.indexOf(cities[i].key) >=0 ) // city can be multiples - see if its in there
			{
				// need to put in a copy of the object - that knows who the master object is
				CID = "C"+cityIDs;
				cobj = new lootitem(name,type,id,where,attack,defense,image,lootid,giftable,needed,single,cost,quantity,city);
				cobj.uid = CID; // UserInterface ID
				cities[i].loot[cities[i].loot.length] = cobj; // store as the object - will make sorting faster
				obj.AddAltID(CID);
				cityIDs++;
			}
	}

}

function lootitem(name,type,id,where,attack,defense,image,lootid,giftable,needed,single,cost,quantity,city,alt)
{
	this.where = where;
	this.name = name;
	this.type = type;
	this.attack = attack;
	this.defense = defense;
	this.id = type + id;
	this.image = image;
	this.lootOrder = 0;
	this.quantity = quantity;
	this.lootid = lootid;
	this.giftable = giftable;
	this.needed = needed;
	this.single = single;
	this.cost = cost;
	
	if(alt)
		this.altname = alt;
	else
		this.altname = name;

	this.giftorsale = 0;
	this.city = city;
	this.uid = type + id;  // in the main lists the uid and id are the same

	return(this);
}

lootitem.prototype.AddAltID = function(ID)
{
	if(!this.AltIDs)
		this.AltIDs = new Array();

	this.AltIDs.push(ID);
}

lootitem.prototype.setquantity = function(quantity)
{
	this.quantity = quantity;
}

lootitem.prototype.buildRow = function(iscity)
{
	return(buildTableRow(this,iscity));
}

lootitem.prototype.UpdateUIQuantity = function()
{
	var i;

	function SetQuantity(uid,item)
	{

		try {
            $("#"+uid).val(item.quantity);
            
//			var obj = getObj(uid);
//			obj.value = item.quantity;
		} catch(e) { }
	}

	// now set the UI values;
	SetQuantity(this.id,this);

	if(this.AltIDs)
		for(i=0;i<this.AltIDs.length;i++)
			SetQuantity(this.AltIDs[i],this);
}

// id = the original master id of the loot item - the one in weapon/armor/vehicle/other list
// uid is the id in the display

function changeQty(id,uid)
{
	var lootitem;
	var qty;

	lootitem = FindLootItemByID(id);

	obj = getObj(uid); // source of the new quantity
	qty = parseInt(obj.value);

	if(isNaN(qty))
		qty = 0;


	lootitem.quantity = qty;
	lootitem.UpdateUIQuantity();

	figureItAllOut(outputmode);
	AllEvents.UpdateEvents(); // recalculates totals of the events
}


function callPublishDefense(msg, attachment, action_link) 
{
	var newsstory = "Hey, I just had to brag a little about my Mafia Wars equipment defense percentile I just got at Blofeld's Loot List & Combat Calculator: My stats are above " + ODPercentile + "% of the other players at my level! Whoot!  Blofeld says he is mighty proud.";
	attachment.description = newsstory;
	FB.ensureInit(function () { FB.Connect.streamPublish('', attachment, action_link); } );
}


function callPublishAttack(msg, attachment, action_link) 
{
//	var newsstory = "Hey, I just had to brag a little about my Mafia Wars equipment attack percentile I just got at Blofeld's Loot List & Combat Calculator: My stats are above " + OAPercentile + "% of the other players at my level! Whoot!  Blofeld says he is mighty proud.";
//	attachment.description = newsstory;
//	FB.ensureInit(function () { FB.Connect.streamPublish('', attachment, action_link); } );
}

function EquipmentPercentile(name,equipment,percentile)
{
	var output = "&nbsp;<img src=\"circle.jpg\">&nbsp;Equip:&nbsp;" + equipment + "&nbsp;<img src=\"circle.jpg\">&nbsp<span id='"+name+"' style='color: " + percentilecolor(percentile) + "'>";

	if(percentile != -1)
		output += "%" + percentile + "%";
	
	output += "</span>";

	return(output);
}

function PersonalPercentile(title,name,stat,percentile)
{
	var output = "<tr><td nowrap>"+title+"</td><td align=\"right\">"+stat+"</td><td align=\"right\"><span id='" + name + "' style='color: " + percentilecolor(percentile) + "'>";

	if(percentile != -1)
		output += "%" + percentile + "%";

	output += "</span></td></tr>";
	return(output);
}

function figureItAllOut(styleoutput)
{
	var temp;
	var tempW,tempA,tempV,tempN;
	var extraWeapons,extraArmor,extraVehicles,extraAnimals;
	var saleableWeapons,saleableArmor,saleableVehicles,saleableAnimals;
	var output;
	var defensecombatscore,attackcombatscore;

	AttackA = AttackD = DefenseA = DefenseD = 0;
	numAWeapons = numAArmor = numAVehicles = numAAnimals = numDWeapons = numDArmor = numDVehicles = numDAnimals = 0;
	boostAttack = boostDefense = boostRobbing = 0;
	bestAWeapon = bestDWeapon = bestAArmor = bestDArmor = bestAVehicle = bestDVehicle = bestAAnimal = bestDAnimal = 0;
	WeaponAttackStat = ArmorAttackStat = VehicleAttackStat = AnimalAttackStat = WeaponDefenseStat = ArmorDefenseStat = VehicleDefenseStat = AnimalDefenseStat = 0;

	tempW = figureAttack(weapon,styleoutput);
	tempA = figureAttack(armor,styleoutput);
	tempV = figureAttack(vehicle,styleoutput);
	tempN = figureAttack(animal,styleoutput);
    
	var attack = "<div style=\"padding: 8px; width: 434px; background-color: #444444; border: 1px solid white\">";
	attack += "<table border='0' cellpadding='0' cellspacing='0' width='100%'><tr><td nowrap style='width: 100%' valign='center'><span style='font-size: 11pt; color: #bcd2ea'><b><img src='bigattack.jpg' alt='' align='top' /> YOUR EQUIPMENT ATTACK: " + AttackA + "</b></span></td>";
	attack += "<td valign='center'><span id=\"idOAttack\" style=\"font-size: 14pt; color: " + percentilecolor(OAPercentile) + "\">";

	if(OAPercentile != -1)
		attack += "%" + OAPercentile + "%";

	attack += "</span></td></tr>";
//	attack += "<tr><td colspan=2 align=right><input style=\"display: none\" id=\"attackbrag\" type=\"button\" onclick=\"callPublishAttack('',{'name':'Blofelds Loot List & Combat Calculator','href':'http://www.blofelds.com','description':'put description here','media':[{'type':'image','src':'http://www.blofelds.com/feedlogo.png','href':'http://www.blofelds.com'}]},null);return false;\" value=\"Brag about it!\" /></td></tr>";
	attack += "<tr><td colspan=2 align=center>" + affiliates[parseInt(Math.random()*4)] + "</td></tr>";

	attack += "</table>";
	attack += "</div>";

	attack += "<div style=\"padding-top: 6px\"><span class='mylabel'>Weapons: " + numAWeapons +  EquipmentPercentile("idWAttack",WeaponAttackStat,WAPercentile) + "</span>";
	attack += "<br>" + tempW + "</div>";

	attack += "<div style=\"padding-top: 6px\"><span class='mylabel'>Armor: " + numAArmor + EquipmentPercentile("idAAttack",ArmorAttackStat,AAPercentile) + "</span>";
	attack +="<br>" + tempA + "</div>";

	attack += "<div style=\"padding-top: 6px\"><span class='mylabel'>Vehicles: " + numAVehicles + EquipmentPercentile("idVAttack",VehicleAttackStat,VAPercentile) + "</span>";
	attack += "<br>" + tempV + "</div>";

  	attack += "<div style=\"padding-top: 6px\"><span class='mylabel'>Animals: " + numAAnimals + EquipmentPercentile("idNAttack",AnimalAttackStat,NAPercentile) + "</span>";
	attack += "<br>" + tempN + "</div>";
	
	tempW = figureDefense(weapon,styleoutput);
	tempA = figureDefense(armor,styleoutput);
	tempV = figureDefense(vehicle,styleoutput);
	tempN = figureDefense(animal,styleoutput);

	var defense = "<div style=\"padding: 8px; width: 434px; background-color: #444444; border: 1px solid white\">";
	defense += "<table border='0' cellpadding='0' cellspacing='0' width='100%'><tr><td nowrap style='width: 100%' valign='center'><span style='font-size: 11pt; color: #bcd2ea'><b><img src='bigdefense.jpg' alt='' align='top' /> YOUR EQUIPMENT DEFENSE: " + DefenseD + "</b></span></td>";
	defense += "<td valign='center'><span id=\"idODefense\"style=\"font-size: 14pt; color: " + percentilecolor(ODPercentile) + "\">";

	if(ODPercentile !=-1)
		defense += "%" + ODPercentile + "%";

	defense += "</span></td></tr>";
//	defense += "<tr><td colspan=2 align=right><input style=\"display: none\" id=\"defensebrag\" type=\"button\" onclick=\"callPublishDefense('',{'name':'Blofelds Loot List & Combat Calculator','href':'http://www.blofelds.com','description':'put description here','media':[{'type':'image','src':'http://www.blofelds.com/feedlogo.png','href':'http://www.blofelds.com'}]},null);return false;\" value=\"Brag about it!\" /></td></tr>";

	defense += "<tr><td colspan=2 align=center>" + affiliates[parseInt(Math.random()*4)] + "</td></tr>";

	defense += "</table>";

	defense += "</div>";

	defense += "<div style=\"padding-top: 6px\"><span class='mylabel'>Weapons: " + numDWeapons + EquipmentPercentile("idWDefense",WeaponDefenseStat,WDPercentile) + "</span>";
	defense += "<br>" + tempW + "</div>";

	defense += "<div style=\"padding-top: 6px\"><span class='mylabel'>Armor: " + numDArmor + EquipmentPercentile("idADefense",ArmorDefenseStat,ADPercentile) + "</span>";
	defense += "<br>" + tempA + "</div>";

	defense += "<div style=\"padding-top: 6px\"><span class='mylabel'>Vehicles: " + numDVehicles + EquipmentPercentile("idVDefense",VehicleDefenseStat,VDPercentile) + "</span>";
	defense += "<br>" +  tempV + "</div>";

	defense += "<div style=\"padding-top: 6px\"><span class='mylabel'>Animals: " + numDAnimals + EquipmentPercentile("idNDefense",AnimalDefenseStat,NDPercentile) + "</span>";
	defense += "<br>" +  tempN + "</div>";
	
	var yourstats = "<div style=\"font-size: 11pt; padding: 8px; width: 434px; background-color: #444444; color: #bcd2ea; border: 1px solid white\"><b>YOUR STATS</b></div>";

	yourstats += "<table border=\"0\" cellpadding=\"5\" cellspacing=\"0\" width=\"434px\">";
	yourstats += "<tr><td>&nbsp;</td><td>Yours</td><td>Percentile</td></tr>";
	yourstats += PersonalPercentile("Personal Attack Stat","idAttack",Nattack,PAPercentile);
	yourstats += PersonalPercentile("Personal Defense Stat","idDefense",Ndefense,PDPercentile);
	yourstats += "</table>";

	output = attack + "<p/>" + defense +  "<p/>" + yourstats + "<p/>";

	var out = getObj("output");
	out.innerHTML = output;

	extraWeapons = makeGiveAwayDisplay(weapon,0);
	extraArmor = makeGiveAwayDisplay(armor,0);
	extraVehicles = makeGiveAwayDisplay(vehicle,0);
    extraAnimals = makeGiveAwayDisplay(animal,0);
    
	var giftable = "<div style=\"font-size: 11pt; padding: 8px; width: 434px; background-color: #444444; color: #bcd2ea; border: 1px solid white\"><b>GIFTABLE</b><br/>";
	giftable += "<span style=\"font-size: 9pt\">The following loot is not used in combat or jobs and can be safely gifted away</div>";
	giftable += "<p>Weapons:  " + extraWeapons + "</p><p>Armor: " + extraArmor + "</p><p>Vehicles: " + extraVehicles + "</p><p>Animals: " + extraAnimals + "</p></span>";

	saleableWeapons = makeGiveAwayDisplay(weapon,1);
	saleableArmor = makeGiveAwayDisplay(armor,1);
	saleableVehicles = makeGiveAwayDisplay(vehicle,1);
    saleableAnimals = makeGiveAwayDisplay(animal,1);
	giftable += "<div style=\"margin-top: 10px; font-size: 11pt; padding: 8px; width: 434px; background-color: #444444; color: #bcd2ea; border: 1px solid white\"><b>SALEABLE</b><br/>";
	giftable += "<span style=\"font-size: 9pt\">The following purchased equipment is not used in combat or jobs and can be safely sold.</div>";
	giftable += "<p>Weapons:  " + saleableWeapons + "</p><p>Armor: " + saleableArmor + "</p><p>Vehicles: " + saleableVehicles + "</p><p>Animals: " + saleableAnimals + "</p></span>";

	out = getObj("output2");
	out.innerHTML = giftable;
	analyzed = true;
}

function makeProfileDisplay(type,styleoutput)
{

	var output = "";
	var i;
	var column;
	var numcolumns = 7;

	if(styleoutput == 0)
	{
		for(i=0;i<type.length;i++)
		{
			if(type[i].used > 0 )
			{
				if(output.length > 0 )
					output += ", ";

				output += type[i].used + ") " + type[i].name;
			}
			
		}
	}
	else
	{
		
		output += "<table border='0' cellpadding='2' cellspacing='0'>";
		column = 0;

		for(i=0;i<type.length;i++)
		{
			if(type[i].used > 0 )
			{

				if(column==0)
					output += "<tr>";

				output += "<td align='center'><img src=\"" + getImageName(type[i]) + "\" style=\"width: 48px; height: 48px; border: 1px solid #444444\" alt=\""+type[i].name+"\" title=\""+type[i].name+"| att: " + type[i].attack + " / def: " + type[i].defense + "\"><br/>";
				output += "<span style='font-size: 8pt'>" + type[i].used + "</span>";

				if(column == numcolumns)
				{
					output += "</tr>";
					column = 0;
				}
				else
					column++;
			}
			
		}

		if(column != 0)
		{
			output += "</tr>";
		}

		output += "</table>";
	}

	return(output);
}

function makeGiveAwayDisplay(type,which) // which == 0 for giftable, 1 for saleable
{
	var i,x;
	var output = "";
	var needed;
	var flag = false;
	var count;
	var mafia;
	var trade;

	function sortAttack(a,b)
	{
		if(a.attack == b.attack)
			return(a.quantity < b.quantity); // most used equipment first
		else
			 return(b.attack - a.attack); // descending
	}
	
	function sortDefense(a,b)
	{
		if(a.defense == b.defense)
			return(a.quantity < b.quantity); // most used equipment first
		else
			 return(b.defense - a.defense); // descending
	}

	type.sort(sortAttack); // sort items by attack, attackused
	mafia = Math.min(parseInt(mafiasize),501);

	for(i=0;i<type.length;i++)
		type[i].attacktrade = 0;

	for(i=0;i<type.length;i++)
	{

		if( parseInt(type[i].quantity) > 0  )
		{
			if(mafia == 0)
				type[i].attacktrade = parseInt(type[i].quantity);  // can trade them all away
			else
			{
				// count all the items with the same attack value (how many total items)
			
				for(count=0,x=i;(x<type.length) && (type[x].attack==type[i].attack);x++)
					count += parseInt(type[x].quantity);

				if(mafia <= count)
				{
					for(x=i;(x<type.length) && (type[x].attack==type[i].attack);x++)
					{
						trade = parseInt(type[x].quantity) - mafia;

						if(trade>0)
							type[x].attacktrade = trade; // how many that were not needed for attack
					}

					mafia = 0;
				}
				else 
					mafia -= count;
				
				i = x-1;
			}
		}
	}

	type.sort(sortDefense); // sort items by attack, attackused
	mafia = Math.min(parseInt(mafiasize),501);

	for(i=0;i<type.length;i++)
		type[i].defensetrade = 0;

	for(i=0;i<type.length;i++)
	{

		if( parseInt(type[i].quantity) > 0  )
		{

			if(mafia == 0)
				type[i].defensetrade = parseInt(type[i].quantity);  // can trade them all away
			else
			{
				// count all the items with the same defense value (how many total items)
			
				for(count=0,x=i;(x<type.length) && (type[x].defense==type[i].defense);x++)
					count += parseInt(type[x].quantity);

				if(mafia <= count)
				{
					for(x=i;(x<type.length) && (type[x].defense==type[i].defense);x++)
					{
						trade = parseInt(type[x].quantity) - mafia;

						if(trade>0)
							type[x].defensetrade = trade; // how many that were not needed for attack
					}

					mafia = 0;
				}
				else 
					mafia -= count;
				
				i = x-1;
			}
		}
	}

	function doGiftable()
	{	
		var i;
		var tradeable;
		var flag = false;
		var output = "";
		var column = 1;
		var needed;

		for(i=0;i<type.length;i++)
		{

			needed = type[i].needed;

			if(needed==0)
				needed += collector;

			if(type[i].giftable)
			{
				tradeable = Math.min(type[i].defensetrade, type[i].attacktrade,parseInt(type[i].quantity)-(needed));

				if(tradeable > 0 )
				{
					type[i].giftorsale = tradeable;
					if(flag==false)
					{
						flag = true;
						output = "<table border=\"0\" cellpadding=\"2\" cellspacing=\"2\" style='width: 434px;'>";
					}

					if(column ==1)
						output += "<tr>";

					output += "<td>" + tradeable + "</td><td>" + type[i].name;
                    output += "&nbsp;(" + type[i].attack + "/" + type[i].defense + ")";

                    output += "</td>";

					if(column == 2)
					{
						output += "</tr>";
						column = 0;
					}

					column++;
				}
				else
					type[i].giftorsale = 0;
			}
		}

		if(flag==true)
		{
			if(column==2)
				output += "<td>&nbsp;</td></tr>";

			output += "</table>";
		}
		else
			output = "none";

		return(output);
	}

	function doSaleable()
	{	
		var i;
		var tradeable;
		var flag = false;
		var output = "";
		var symbol;
		var needed;

		for(i=0;i<type.length;i++)
		{
			if(type[i].cost > 0)
			{

				needed = type[i].needed;

				if(needed==0)
					needed += collector;

				tradeable = Math.min(type[i].defensetrade, type[i].attacktrade,parseInt(type[i].quantity)-(needed));
				type[i].giftorsale = tradeable;

				if(tradeable > 0 )
				{
					type[i].giftorsale = tradeable;
					if(flag==false)
					{
						flag = true;
						output = "<table border=\"0\" cellpadding=\"2\" cellspacing=\"2\" style='width: 434px;'>";
					}

					symbol = getCurrencySymbol(type[i]);
					output += "<tr><td>" + tradeable + "</td><td>" + type[i].name + "</td><td>" + formatCost(type[i].cost/2 * tradeable,symbol) +"</td></tr>";
				}
				else
					type[i].giftorsale = 0;
			}
		}

		if(flag==true)
			output += "</table>";
		else
			output="none";

		return(output);
	}

	if(which == 0)
		output = doGiftable();
	else
		output = doSaleable();

	return(output);
}

function figureAttack(type,styleoutput)
{
	var mafia = mafiasize;
	var output = "";
	var i, using;

	if(mafia > 501)
		mafia = 501;

/* ORIGINAL METHOD OF SORTING BY ATTACK */
	function sortByAttack(a,b)
	{
		if(a.attack == b.attack)
			return(a.lootOrder < b.lootOrder); // ascending - oldest to newest
		else
			 return(b.attack - a.attack); // descending
	}


//// ===== NEW METHOD OF SORTING === GFP, $, DROP, PURCHASE
/*	function sortbyattack(a,b)
	{

		if(a.attack == b.attack)
		{
			if( (a.city == "G") && (b.city == "G") ) // both are 25 GFP items
				return(a.defense < b.defense);

			if(a.city == "G")  // only first item is GFP - it takes precedence
		 		return (1);

			if((a.city == "$") && (b.city =="$") ) // both are limited edition loot $10K, or whatever
				return(a.defense < b.defense)

			if(a.city == "$")  // only first item is $10K lel, it takes precedence
				return(1);

			// if it is a drop item (had no $ cost) then it takes priority
			if((a.cost == 0) && (b.cost == 0) )
				return(a.defense < b.defense);

			if(a.cost == 0)
				return(1);
			
		}
		
		return(a.attack < b.attack);

	}
*/

	// sort loot by attack strength 
	type.sort(sortByAttack);
	
	// clear the used "bit"

	for(i=0;i<type.length;i++)
		type[i].used = 0;

	for(i=0;(i<type.length) && (mafia > 0);i++)
	{
		if( type[i].quantity >= mafia )
			using = mafia;
		else
			using = type[i].quantity;

		if(using > 0 )
		{
			AttackA += type[i].attack * using;
			AttackD += type[i].defense * using;

			type[i].used = using;

			switch(type[i].type)
			{
				case "W":
					numAWeapons += Number(using);

					if(bestAWeapon)
					{
						if(type[i].attack > bestAWeapon.attack)
							bestAWeapon = type[i];
					}
					else
						bestAWeapon = type[i];

					WeaponAttackStat += type[i].attack * using;
				break;
	
				case "A":
					numAArmor += Number(using);
			
					if(bestAArmor)
					{
						if(type[i].attack > bestAArmor.attack)
							bestAArmor = type[i];
					}
					else
							bestAArmor = type[i];

					ArmorAttackStat += type[i].attack * using;
				break;

				case "V":
					numAVehicles += Number(using);

					if(bestAVehicle)
					{
						if(type[i].attack > bestAVehicle.attack)
							bestAVehicle = type[i];
					}
					else
						bestAVehicle = type[i];

					VehicleAttackStat += type[i].attack * using;
				break;
				
				case "N":
					numAAnimals += Number(using);

					if(bestAAnimal)
					{
						if(type[i].attack > bestAAnimal.attack)
							bestAAnimal = type[i];
					}
					else
							bestAAnimal = type[i];

					AnimalAttackStat += type[i].attack * using;
				break;
			}

			mafia -= using;
		}

	}

	output = makeProfileDisplay(type,styleoutput);

	return(output);

}

function figureDefense(type,styleoutput)
{
	var mafia = mafiasize;
	var output="";
	var i,using;

	if(mafia > 501)
		mafia = 501;

	function sortByDefense(a,b)
	{
		if(a.defense == b.defense)
			 return(a.lootOrder < b.lootOrder);
		else
			 return(b.defense - a.defense); // descending
	}

	type.sort(sortByDefense);

	for(i=0;i<type.length;i++)
		type[i].used = 0;

	for(i=0;(i<type.length) && (mafia > 0);i++)
	{
		if( type[i].quantity >= mafia )
			using = mafia;
		else
			using = type[i].quantity;

		if(using > 0 )
		{
			DefenseA += type[i].attack * using;
			DefenseD += type[i].defense * using;

			type[i].used = using;

			switch(type[i].type)
			{
				case "W":
					numDWeapons += Number(using);

					if(bestDWeapon)
					{
						if(type[i].defense > bestDWeapon.defense)
							bestDWeapon = type[i];
					}
					else
						bestDWeapon = type[i];

					WeaponDefenseStat += type[i].defense * using;
				break;
	
				case "A":
					numDArmor += Number(using);

					if(bestDArmor)
					{
						if(type[i].defense > bestDArmor.defense)
							bestDArmor = type[i];
					}
					else
							bestDArmor = type[i];

					ArmorDefenseStat += type[i].defense * using;
				break;

				case "V":
					numDVehicles += Number(using);

					if(bestDVehicle)
					{
						if(type[i].defense > bestDVehicle.defense)
							bestDVehicle = type[i];
					}
					else
						bestDVehicle = type[i];

					VehicleDefenseStat += type[i].defense * using;
				break;
				
				case "N":
					numDAnimals += Number(using);

					if(bestDAnimal)
					{
						if(type[i].defense > bestDAnimal.defense)
							bestDAnimal = type[i];
					}
					else
							bestDAnimal = type[i];

					AnimalDefenseStat += type[i].defense * using;
				break;
				
			}

			mafia -= using;
		}

	}

	output = makeProfileDisplay(type,styleoutput);

	return(output);

}

//===========================================================================
// SORTING THE INTERFACE
//===========================================================================

function sortInterface()
{
	// is this tab currently sorted the way its supposed to be - if not then do it

	if(currentTab.name == "Events")
		return; // we don't change this tab - 

	if(currentTab.name == "Best Of")
		return; // we don't change this tab - 
		
    var type = gSortBySelection;
    
	if(currentTab.sortedBy == type )
		return; // already sorted

	currentTab.sortedBy = type; // remember the new sort

	switch(currentTab.name)
	{
		case "Moscow":
		case "NY":
		case "Cuba":
		case "Bangkok":
		case "Las Vegas":
			buildCityTable(currentTab);
		break;

		case "Crates":
			AllCrates.MakeUITable();
		break;

		default:
			sortLoot(currentTab.lootlist,type);
			tabTable(currentTab);
	}	

}

function sortLoot(lootlist,type)
{

	function sortAD(a,b)
	{
		if(a.attack == b.attack)
			return(b.defense - a.defense); // descending
		else
			 return(b.attack - a.attack); // descending
	}

	function sortAA(a,b)
	{
		if(a.attack == b.attack)
			return(a.defense - b.defense); // descending
		else
			 return(a.attack - b.attack); // descending
	}

	function sortDD(a,b)
	{
		if(a.defense == b.defense)
			return(b.attack - a.attack); // descending
		else
			 return(b.defense - a.defense); // descending
	}

	function sortDA(a,b)
	{
		if(a.defense == b.defense)
			return(a.attack - b.attack); // descending
		else
			 return(a.defense - b.defense); // descending
	}

	function sortN(a,b)
	{
		 return(String(b.name).valueOf() < String(a.name).valueOf() ); // descending
	}

	function sortWF(a,b) // by location
	{
		return(String(b.where).valueOf() < String(a.where).valueOf() );
	}

	switch(type)
	{
		case 'AD':
			lootlist.sort(sortAD);
		break;

		case 'AA':
			lootlist.sort(sortAA);
		break;

		case 'DD':
			lootlist.sort(sortDD);
		break;

		case 'DA':
			lootlist.sort(sortDA);
		break;

		case 'N':
			lootlist.sort(sortN);
		break;

		case 'WF':
			 lootlist.sort(sortWF);
			//quicksort(lootlist,sortWF);
		break;

	}
}

function quicksort(arr,sortfunc) {
	
	if (arr.length == 0)
		return [];
 
	var left = new Array();
	var right = new Array();
	var pivot = arr[0];

	for (var i = 1; i < arr.length; i++) {
		if (sortfunc(arr[i],pivot) ) { // arr[i] < pivot
			left.push(arr[i]);
		} else {
			right.push(arr[i]);
		}
	}
 
	return quicksort(left,sortfunc).concat(pivot, quicksort(right,sortfunc));
}

function FindLootItemByImage(image)
{

	var i;

	for(i=0;i<weapon.length;i++)
		if(weapon[i].image == image)
			return(weapon[i]);

	for(i=0;i<armor.length;i++)
		if(armor[i].image == image)
			return(armor[i]);

	for(i=0;i<vehicle.length;i++)
		if(vehicle[i].image == image)
			return(vehicle[i]);
			
	for(i=0;i<animal.length;i++)
		if(animal[i].image == image)
			return(animal[i]);
			
	return;
}

function FindLootItemByName(name)
{

	var i;

	for(i=0;i<weapon.length;i++)
		if(weapon[i].altname == name)
			return(weapon[i]);

	for(i=0;i<armor.length;i++)
		if(armor[i].altname == name)
			return(armor[i]);

	for(i=0;i<vehicle.length;i++)
		if(vehicle[i].altname == name)
			return(vehicle[i]);
			
	for(i=0;i<animal.length;i++)
		if(animal[i].altname == name)
			return(animal[i]);
	return;
}

function saveLootItem(name,quantity)
{
	var obj,i;

	lootOrder++;

	for(i=0;i<weapon.length;i++)
		if(weapon[i].altname == name)
		{
			weapon[i].quantity = quantity;
			weapon[i].lootOrder = lootOrder;
			weapon[i].UpdateUIQuantity();
			return;			
		}

	for(i=0;i<armor.length;i++)
		if(armor[i].altname == name)
		{
			armor[i].quantity = quantity;
			armor[i].lootOrder = lootOrder;
			armor[i].UpdateUIQuantity();
			return;			
		}

	for(i=0;i<vehicle.length;i++)
		if(vehicle[i].altname == name)
		{
			vehicle[i].quantity = quantity;
			vehicle[i].lootOrder = lootOrder;
			vehicle[i].UpdateUIQuantity();
			return;			
		}

	for(i=0;i<animal.length;i++)
		if(animal[i].altname == name)
		{
			animal[i].quantity = quantity;
			animal[i].lootOrder = lootOrder;
			animal[i].UpdateUIQuantity();
			return;
		}

		// before putting up a dialog box - check and see if its the baseball bat - we "know" the baseball bat is in the tool - so if
		// it isn't found then the user is not using the tool properly (probably not using firefox) and it will generate a dialog box
		// for every single missing item!!

		if(name=="Baseball Bat")
		{
			alert("For some reason we couldn't find the baseball bat in our loot list - though we know it is there.  Make sure you are using Firefox and your lootlist is from Facebook.");
			return(false); // abort loading weapons
		}
		else
			alert("could not find loot item \'" + name + "\' - \r\n\r\nYou don\'t need to tell us - we've been emailed. However, it is also possible you don't have the latest loot list - try refreshing your page.");


	UnknownItem(name);
	return(true);
}

function UnknownItem(name)
{
	var i = new Image();
	i.src = "unknownitem.asp?itemname=" + name;
}

function clearQuantities()
{
	function clearItem(item)
	{
		var i;

		for(i=0;i<item.length;i++)
		{
			item[i].quantity = 0;
			item[i].lootOrder = 0;
		}
	}

    $(":text").val(""); // clears all text input fields
	clearItem(weapon);
	clearItem(armor);
	clearItem(vehicle);
	clearItem(animal);

}

function clearAll()
{
	var temp = getObj('parser');
	temp.value="Paste your loot here";
	clearQuantities();
	temp = getObj('output');
	temp.innerHTML = "";
	temp = getObj('output2');
	temp.innerHTML = "";
	Nattack = Ndefense = boostAttack = boostDefense = boostRobbing = 0;
	mafiasize = 501; // for now - put in a text box later for attack/defense/mafiasize/level (for robbing)
	setmafiasizemenu(501);
}

function parse(text)
{
	var results = text.match(/\s+\*\n\s+.+\n\s+X\s+[0-9]+/g);

	var lootName;
	var x,a,b,quantity;
	boostAttack = boostDefense = boostRobbing = 0;
	lootOrder = 0;
	var i;

	if(results == null)
	{
		alert("Load Loot didn't work.  Be sure you are using Firefox and you are copying from your Profile page, not your Loot page.");
		return(false);
	}

	clearQuantities();

	for(i=0;i<results.length;i++)
	{
		x = results[i];
		a = String(x.match(/\s+\*\n\s+/));
		b = results[i].substring(a.length);
		lootName = String(b.match(/.+/));

		if( lootName.match(/.+\(.+\)/) ) // if the loot Name is of the form /.+(.+)/ then it is a boost 
			continue;

		switch(lootName)
		{
			case "Abandoned Lot":
			case "Commercial Block":
			case "Beachfront Property":
			case "Louie's Deli":
			case "Rent House":
			case "Italian Restaurant":
			case "Apartment Complex":
			case "Mafia Mike's":
			case "Valu-Mart":
			case "Marina Tourist Shops":
			case "Office Building":
			case "Prime Downtown Lot":
			case "5-Star Hotel":
			case "Mega Casino":
				continue;
		}

		if(lootName.indexOf("Louie's Deli") != -1 )
			continue;

		a = b.substring(lootName.length+1); // this is the next line
		quantity = a.match(/[0-9]+/);

		// any < or > with &lt; or &gt; or &amp;
		lootName = lootName.replace(/</g,"&lt;");
		lootName = lootName.replace(/>/g,"&gt;");

		if(saveLootItem(lootName,quantity) == false)
			break;
	}

	getPlayerStats(text);

	figureItAllOut(outputmode);
	AllEvents.UpdateEvents();

	return(true);
}

function parseIt()
{
	var ourtext = getObj('parser').value;

	if(parse(ourtext))
		GrabStats();
}

function FindLootItemByID(itemID)
{
	var type = itemID.charAt(0);
	var lootlist;
	var i;

	switch(type)
	{
		case "W":
			lootlist = weapon;
		break;

		case "A":
			lootlist = armor;
		break;

		case "V":
			lootlist = vehicle;
		break;

        case "N":
			lootlist = animal;
		break;
		
		case "O":
			lootlist = other;
		break;
	}

	for(i=0;i<lootlist.length;i++)
	{
		if(lootlist[i].id == itemID)
			return(lootlist[i]);
	}

	return(0); // this is bad - shouldn't happen

}

function slideCitiesLeft()
{
	if(citypos < (tabs.length-7) )
	{
		var obj = getObj("locscroller");
		var left = parseInt(obj.style.left);

		obj.style.left =  (left - 103) + "px";
		citypos++;
	}
}

function slideCitiesRight()
{

	if(citypos > 0 )
	{
		var obj = getObj("locscroller");
		var left = parseInt(obj.style.left);

		obj.style.left =  (left + 103) + "px";
		citypos--;
	}
}

function tabTable(tab)
{
	var i;
	var output = "<table border='0' cellpadding='5' cellspacing='0' width='100%' style='margin-bottom: 30px'>";

	for(i=0;i<tab.lootlist.length;i++)
		output += tab.lootlist[i].buildRow(tab.iscity);

	output += "</table>";
	// get the table and replace it's contents

    $("#"+tab.divID).html(output);
//	obj = getObj(tab.divID);
//	obj.innerHTML = output;
}

function buildCityTable(tab)
{
	//organize by Weapons/Armor/Vehicles

	var i;
	var temp = new Array();
	// show the rest by episode

	var output = "<table border='0' cellpadding='5' cellspacing='0' width='100%' style='margin-bottom: 30px'>";

	function makeCityBlock(blockname)
	{
		var output = "";
		var index = 0;
		var i;
		output += "<tr><td colspan='3' style='background-color: DimGray; color: white'>" + blockname + "</td></tr>";

		for(i=0;i<tab.lootlist.length;i++)
			if(tab.lootlist[i].where.indexOf(blockname) >=0 )
				temp.push(tab.lootlist[i]);

		// sorting doesn't work for some reason in chrome and IE (works fine in firefox) - so we do our own sort (insertion)
		// find each item - render it - and remove from the list

		while(temp.length)
		{
			index = 0;

			for(i=0;i<temp.length;i++)
				switch(tab.sortedBy)
				{
					case "N":
						if(temp[i].name < temp[index].name)
							index = i;
					break;

					case "AA":
						if(temp[i].attack < temp[index].attack)
							index = i;
					break;

					case "AD":
						if(temp[i].attack > temp[index].attack)
							index = i;
					break;

					case "DA":
						if(temp[i].defense < temp[index].defense)
							index = i;
					break;
				
					case "DD":
						if(temp[i].defense > temp[index].defense)
							index = i;
					break;
				}

				// index point at item to be rendered
				output += temp[index].buildRow(tab.iscity);
				temp.splice(index,1);
		}

		return(output);
	}

	output += makeCityBlock("Mafia Store");

	for(i=0;i<tab.episodes.length;i++)
		output += makeCityBlock(tab.episodes[i]);

	output += "</table>";
	
	// get the table and replace it's contents
    $("#"+tab.divID).html(output);
}

function buildTabTables()
{
	var i;
	// build the weapon table last - so it doesn't display until all tabs are built

	for(i=0;i<tabs.length;i++)
	{
		switch(tabs[i].name)
		{
			case "Moscow":
			case "NY":
			case "Cuba":
			case "Bangkok":
			case "Las Vegas":
				buildCityTable(tabs[i]);
			break;

			case "Events": // not here
			case "Crates":
			case "Best Of":
			break;

			default:
				tabTable(tabs[i]);
		}
		
	}
}

function Init()
{
	newcity("NY","NY ","N");
	newcity("Cuba","Cuba ","C");
	newcity("Moscow","Moscow ","M");
	newcity("Bangkok","Bangkok","K");
	newcity("Las Vegas","Las Vegas","V");
	newcity("Best Of","Best Of","Y");
	newcity("Crates","Crates","R");
	newcity("Limited","$10,000","$");
	newcity("LimitedGFP","25 GFP","G");
	newcity("Events","Events","E");
	newcity("Special","xxxxxxxxxxxxxxxx","S"); // if it doesn't go above then it goes here

	newtab("Weapons",weapon,"weapontab",false);
	newtab("Armor",armor,"armortab",false);
	newtab("Vehicles",vehicle,"vehicletab",false);
	newtab("Animals",animal,"animaltab",false);
	newtab("Special Loot",other,"othertab",false);
	newtab("Boosts",boosts,"booststab",false);
	
	tab = newtab("NY",cities[0].loot,"NYtab",true);
	tab.episodes = ['Street Thug','Associate','Soldier','Enforcer','Hitman','Capo','Consigliere','Underboss','Boss','Special'];
	tab = newtab("Cuba",cities[1].loot,"Cubatab",true);
	tab.episodes = ['El Soldado','El Capitan','El Jeffe','El Patron','El Padrino','El Cacique'];
	tab = newtab("Moscow",cities[2].loot,"Moscowtab",true);
	tab.episodes = ['Baklany','Boets','Brigadir','Avtoritet','Vor ','Pakhan','Expansion Reward'];
	tab = newtab("Bangkok",cities[3].loot,"Bangkoktab",true);
	tab.episodes = ['Brawler','Criminal','Pirate','Commandant','Oyabun','Dragon Head','Saboteur','Assassin'];
	tab = newtab("Las Vegas",cities[4].loot,"LasVegastab",true);
	tab.episodes = ['North Las Vegas','Paradise City','The Lower Strip','Shogun Casino','Mojave Desert','District 6'];
	newtab("Best Of",cities[5].loot,"Bestoftab",true);
	crateTab = newtab("Crates",cities[5].loot,"Cratetab",true);
	newtab("Limited",cities[7].loot,"Limitedtab",true);
	newtab("LimitedGFP",cities[8].loot,"LimitedGFPtab",true);
	eventTab = newtab("Events",cities[9].loot,"Eventstab",true); // need the event tab for special processing
	newtab("Special",cities[10].loot,"Specialtab",true);

    if(window.showThankYou)
        showThankYou();
        
	createLootTables();
	BuildEvents();
	BuildCrates();
	BuildBestOf();
	buildTabTables();

	currentTypeTab = "Weapons";
	setCurrentTab("Weapons");

	getCookieOutputMode();
	getCookieCollector();

	if(bookmarklet)
	{
		figureItAllOut(outputmode);
		GrabStats();
	}

}


function setCollector(x)
{
    imacollector = x;
	collector = x;
	$("#imacollector").attr("src",x?"images/collectorON.png":"images/collector.png");
}


function selectType(whichone,image,position)
{
    var obj;

    $("#"+currentTab.divID).css("display","none");
    $("#ourmenubutton").css("left",(position+2) + "px").attr("src","http://images.blofelds.com/buttons/" + image);

	setCurrentTab(whichone);
	sortInterface();

}


function showFAQ()
{
    window.open("http://www.blofelds.com/faq.asp", "Blofeld's Loot List FAQ");
}

function setOutputMode(mode)
{
	setCookie("OM",mode,365); // output mode	

    $("#textoutputbutton").toggleClass("buttonon",(mode!=1)).toggleClass("buttonoff",(mode==1));
    $("#graphicoutputbutton").toggleClass("buttonon",(mode==1)).toggleClass("buttonoff",(mode!=1));

	outputmode = mode;
}

function changeToGraphicOutput()
{
	if(outputmode==0)
	{
		setOutputMode(1);
		if(analyzed)
			figureItAllOut(outputmode);
	}
}

function changeToTextOutput()
{
 	if(outputmode == 1)
	{
		setOutputMode(0);
		if(analyzed)
			figureItAllOut(outputmode);
	}
}

//// event code ----- transitory
function insertGoldCoin(id)
{
/*
	if( IsContestOn() )
	{
		var value = "<img title=\"Click me to add to contest\" src='images/gold_coin.jpg' width='15' border='0' onclick=\"addguess('" + id + "')\"'>";

		return(value);
	}
	else
*/
		return("");

}

function setCookie(c_name,value,expiredays)
{
	var exdate=new Date();
	exdate.setDate(exdate.getDate()+expiredays);
	document.cookie=c_name+ "=" +escape(value)+((expiredays==null) ? "" : ";expires="+exdate.toGMTString());
}

function getCookie(c_name)
{
	if (document.cookie.length>0)
	{
		c_start=document.cookie.indexOf(c_name + "=");

		if (c_start!=-1)
		{
			c_start=c_start + c_name.length+1;
			c_end=document.cookie.indexOf(";",c_start);

			if (c_end==-1) 
				c_end=document.cookie.length;

			return unescape(document.cookie.substring(c_start,c_end));
		}
	}

	return "";
}

function getCookieOutputMode()
{
	var x = getCookie("OM");

	if( (x != null) && (x != "") )
		setOutputMode(parseInt(x));
	else
		setOutputMode(1); // graphics mode by default
}

function getCookieLootMode() // type or location tab
{

}

function getCookieCollector() // type or location tab
{
	var x = getCookie("IAC");

	if( (x != null) && (x != "") )
		setCollector(parseInt(x));
	else
		setCollector(0); // not by default
}

function insertEventItem(lootlist,obj)
{
	for(i=0; i < lootlist.length; i++)
		if( obj.where < lootlist[i].where)
		{
			lootlist.splice(i,0,obj);
			return;
		}
	lootlist.push(obj);
}

function toggleCollector()
{
	collector = imacollector;
	setCookie("IAC",collector,365);

	if(analyzed)
		figureItAllOut(outputmode);
}

//------------------------------------------------------------
//----------- percentile code -------------------------
//------------------------------------------------------------

function percentilecolor(value)
{
    var color = (value<=25)?'red':(value<=50)?'orange':(value<=75)?"yellow":"limegreen";
    return(color);
}

function CheckPercentiles(percs)
{

	function setPercentile(stat,value)
	{
		var obj;
        var color = 'red';
        
		switch(stat)
		{
			case "idOAttack":
				OAPercentile = value;
			break;

			case "idODefense":
				ODPercentile = value;
			break;

			case "idWAttack":
				WAPercentile = value;
			break;

			case "idAAttack":
				AAPercentile = value;
			break;

			case "idVAttack":
				VAPercentile = value;
			break;
			
			case "idNAttack":
				NAPercentile = value;
			break;
			
			case "idWDefense":
				WDPercentile = value;
			break;

			case "idADefense":
				ADPercentile = value;
			break;

			case "idVDefense":
				VDPercentile = value;
			break;
			
			case "idNDefense":
				NDPercentile = value;
			break;
			
			case "idAttack":
				PAPercentile = value;
			break;

			case "idDefense":
				PDPercentile = value;
			break;
		}

        $("#"+stat).css("color", percentilecolor(value) ).text("%"+value+"%");

	}

	function parseStats()
	{
		// format perc=value,perc=value,perc=value
		var x = percs.split(","); // array of perc=values
		var i,z;
		var stat,value;

		for(i=0;i<x.length;i++)
		{
			z = x[i].indexOf("=");
			stat = x[i].substring(0,z);
			value = parseInt(x[i].substring(z+1));
			setPercentile(stat,value);
		}
	}

	parseStats();

}

function GrabStats()
{
	var query = "";

	query += "Level=" + NLevel;
	query += "&Attack=" + Nattack;
	query += "&Defense=" + Ndefense;
	query += "&Mafia=" + mafiasize;
	query += "&WAS="+WeaponAttackStat;
	query += "&AAS="+ArmorAttackStat;
	query += "&VAS="+VehicleAttackStat;
	query += "&NAS="+AnimalAttackStat;
	query += "&WDS="+WeaponDefenseStat;
	query += "&ADS="+ArmorDefenseStat;
	query += "&VDS="+VehicleDefenseStat;
	query += "&NDS="+AnimalDefenseStat;
	query += "&SAVE=1";

    $.get("grabstats3.asp", query, function(data){ CheckPercentiles(data); } );
   
}
