var calculator = {
	
	skills: [],			// skills[1].perks[46]		|  1 = skill id, 46 = perk id
	chosenPerks: [],	// chosenperks[1][46] = 5	|  1 = skill id, 46 = perk id, 5 = rank
	loading: false,		// true when a skill is currently loading - prevent loading something else
	//ui.currentSkill <- reference
	
	init: function(){
		
		//load build
		var buildID = window.location.hash.replace('#', '');
		if(buildID){
			buildID = parseInt(buildID);
			api.post('perks/loadbuild', {build_id: buildID}, function(data){
				calculator.chosenPerks = $.parseJSON(data.perks);
				//window.location.hash = '';
			}, null, false);
		}
		
		
		/* Skilltree drop (for moving perks around). To potential 'hackers': Don't be so foolish as to think this isn't properly secured back-end ;) */
		$('.skilltree').droppable({
			drop: function(e, ui){
				var $perk = ui.draggable;
				var perk_id = $perk.data('id');
				var position = ui.position;				
				api.post('perks/saveperkpos', {perk_id: perk_id, position: position});
			}
		});
		
		//clicking a perk to (both right and left)
		$('.star').live('mousedown', function(e){
			//prevent contextmenu on rightclick
			if(e.which == 3){
				window.oncontextmenu = function () {return false;}
				setTimeout(function(){
					window.oncontextmenu = function () {return true;}		//DIRTY!!! Chrome >.<
				}, 500);
				e.preventDefault();
			}			
			$target = $(e.target).hasClass('name') ? $(e.target).parent() : $(e.target);
			if(e.which == 3){	//rightclick - remove				
				calculator.removePerk($target.data('id'));
			}else{				//leftclick - add				
				calculator.addPerk($target.data('id'));
			}			
			ui.showTooltip($target);
			return true;
		});
	},
	
	//pass skill id, skill gets loaded (not displayed, ui{} handles that)
	loadSkill: function(skill_id){
		if(calculator.skills[skill_id] != undefined){
			calculator.updateStars();
			calculator.updateStats();
			return;
		}
		
		calculator.loading = true;
		calculator.chosenPerks[skill_id] = calculator.chosenPerks[skill_id] != undefined ? calculator.chosenPerks[skill_id] : [];
		
		api.post('perks/getperks', {skill_id: skill_id}, function(data){
			
			//molest and add it to calculator.skills
			var newPerks = []
			calculator.skills[data.id] = data;
			for(var index in data.perks){				
				perk = data.perks[index];
				newPerks[perk.id] = perk;
			}
			calculator.skills[data.id].perks = newPerks;
			
			//prepare the tree for stars
			var $tree = $('.skilltree[data-skill='+skill_id+']');
			$tree.empty();

			//create the individual stars stars and their names
			for(var index in calculator.skills[data.id].perks){
				var perk = calculator.skills[data.id].perks[index];
				
				//create placeholder for dependants and explode dependencies into an array
				perk.dependants = [];
				perk.dependencies = perk.dependencies.length ? perk.dependencies.split(',') : [];

				//create the actual star + name
				var $star = $("<div class='star' data-id='"+perk.id+"'></div>").hide().appendTo($tree)
					.css({left: parseInt(perk.position_x), top: parseInt(perk.position_y)});						
				var $name = $("<div class='name'>"+perk.name+" <strong>(<span class='currentrank'>0</span>/"+perk.ranks.length+")</strong></div>").appendTo($star);
			}			

			//loop through the perks them again and save their dependants
			for(var index in calculator.skills[data.id].perks){
				var perk = calculator.skills[data.id].perks[index];
				//let their dependencies know that i need them, for going up the tree
				for(var index2 in perk.dependencies){
					calculator.skills[data.id].perks[perk.dependencies[index2]].dependants.push(perk.id);
				}					
			}
			
			//fade the stuff in + position + tooltips
			$tree.find(".star").show();
			$tree.find(".name").each(function(){$(this).css({left: -$(this).width() / 2});});
			//ui.tipsy(skill_id);
			
			calculator.loading = false;			
			calculator.updateStats();
			calculator.updateStars();
			
		});	//end api callback		
	},
	
	canAddPerk: function(perk_id, flashDependencies){
		var perk = calculator.skills[ui.currentSkill].perks[perk_id];		//reference
		var currentRank = calculator.chosenPerks[ui.currentSkill][perk_id];	//reference
		
		//level 81? piss off
		if(parseInt($('#levelrequired').text()) >= 81)
			return false;
		
		//compare current rank to max, if already maxed, return false
		if(currentRank >= perk.ranks.length)
			return false;
		
		//check if dependancies have at least one point, if one doesnt -> return false
		//edit: only onde dependency needs to have a point, not both
		var inactiveDependencies = [];
		for(var index in perk.dependencies){
			var dependency = perk.dependencies[index];
			if(calculator.chosenPerks[ui.currentSkill][dependency] < 1 |
			calculator.chosenPerks[ui.currentSkill][dependency] == undefined){
				inactiveDependencies.push(dependency);
			}else{
				return true;
			}
		}
	
		if(inactiveDependencies.length){
			if(flashDependencies){
				for(var index2 in inactiveDependencies){
					dependant = inactiveDependencies[index2];
					$('.star[data-id='+dependant+']').stop().fadeTo(100, 0.25).fadeTo(500, 1).fadeIn(1);
				}
			}
			return false;
		}
		
		return true;
	},	
	
	addPerk: function(perk_id){
		var perk = calculator.skills[ui.currentSkill].perks[perk_id];		//reference
		var currentRank = calculator.chosenPerks[ui.currentSkill][perk_id];	//reference
		
		if(calculator.canAddPerk(perk_id, true)){
			calculator.chosenPerks[ui.currentSkill][perk_id] = currentRank == undefined ? 1 : currentRank + 1;
		}
		
		calculator.updateStats();
		calculator.updateStars();
	},

	canRemovePerk: function(perk_id, flashDependants){
		var perk = calculator.skills[ui.currentSkill].perks[perk_id];		//reference
		var currentRank = calculator.chosenPerks[ui.currentSkill][perk_id];	//reference
		
		//if we dont even have any ranks to being with, return false
		if(currentRank == 0 | currentRank == undefined) return false;
		
		//if rank > 2 return true, since dependant perks only require 1/5
		if(currentRank > 1) return true;
		
		//check if dependants have any points, if so - return false (after checking all), and (possibly) flash them
		//edit: dependants must have at least one dependant active, not both
		var activeDependants = [];
		for(var index in perk.dependants){
			var dependant = perk.dependants[index];
			if(calculator.chosenPerks[ui.currentSkill][dependant] > 0){
				
				//check if it has other dependencies, which are active
				var dependentPerk = calculator.skills[ui.currentSkill].perks[dependant];
				for(var index2 in dependentPerk.dependencies){
					var dependencyId = dependentPerk.dependencies[index2];
					if(dependencyId == perk_id) continue; 
					//var dependency = dependentPerk.dependencies[dependencyId];
					if(calculator.chosenPerks[ui.currentSkill][dependencyId] > 0){
						return true;
					}
				}
				
				activeDependants.push(dependant);
			}
		}
		
		if(activeDependants.length){
			if(flashDependants){
				for(var index2 in activeDependants){
					dependant = activeDependants[index2];
					$('.star[data-id='+dependant+']').stop().fadeTo(100, 0.25).fadeTo(500, 1);
				}
			}
			return false;
		}
		
		return true;
	},
	
	removePerk: function(perk_id){
		var perk = calculator.skills[ui.currentSkill].perks[perk_id];		//reference
		var currentRank = calculator.chosenPerks[ui.currentSkill][perk_id];	//reference
		
		if(calculator.canRemovePerk(perk_id, true)){
			calculator.chosenPerks[ui.currentSkill][perk_id] = currentRank - 1;
		}
		
		calculator.updateStats();
		calculator.updateStars();		
	},
	
	updateStars: function(){
		var $tree = $('.skilltree[data-skill='+ui.currentSkill+']');
		for(var perk_id in calculator.skills[ui.currentSkill].perks){
			var rank = calculator.chosenPerks[ui.currentSkill][perk_id];
			var $star = $tree.find('.star[data-id='+perk_id+']');
			$star.find('.currentrank').text(rank);
			
			$star.removeClass('active available unavailable');
			if(rank) $star.addClass('active');
			else if(calculator.canAddPerk(perk_id)) $star.addClass('available');
			else $star.addClass('unavailable');
		}		
	},
	
	updateStats: function(){
		var requiredLevel = 1;
		var pointsInSkill = [];
		var skillRequired = 0;
		
		//gather stats
		for(var skill_id in calculator.chosenPerks){
			pointsInSkill[skill_id] = 0;
			for(var perk_id in calculator.chosenPerks[skill_id]){
				var rank = calculator.chosenPerks[skill_id][perk_id];
				requiredLevel += rank;
				pointsInSkill[skill_id] = pointsInSkill[skill_id] == undefined ? 0 : pointsInSkill[skill_id];
				pointsInSkill[skill_id] += rank;
				if(skill_id == ui.currentSkill && rank > 0){
					//see if the current rank has a higher req_skill then what it is now, if so - save it
					//console.log(calculator.skills[skill_id].perks[perk_id]);
					var req_skill = parseInt(calculator.skills[skill_id].perks[perk_id].ranks[rank-1].req_skill);
					skillRequired = req_skill > skillRequired ? req_skill : skillRequired;
				}
				
			}
		}
		
		//fill in everything
		if(requiredLevel > 50) $('#levelrequired').addClass('over50'); else $('#levelrequired').removeClass('over50');
		$('#levelrequired').text(requiredLevel);
		$('#pointsinskill').text(pointsInSkill[ui.currentSkill]);
		$('#skillrequired').text(skillRequired);
		
		$('#skills .count').each(function(){
			var pis = pointsInSkill[$(this).data('skill-id')];
			$(this).text(pis);
			if(!pis) $(this).addClass('none'); else $(this).removeClass('none');
		});

	}
	
}