
function WebRoot()
{
  try
  {
    if(WEBROOT != null) return WEBROOT;
    else return "/";
  }
  catch(e) {
    return "/";
  }
}

var searchTimeout;
function searchOpen()
{
    $("#searchbox").slideDown();
    $("#searchbox").fadeIn();
    $("#searchboxinput").focus();
    searchOut();
}
function searchOver()
{
    window.clearTimeout(searchTimeout);
}
function searchOut()
{
    searchTimeout = window.setTimeout("searchClose()",5000);
}
function searchClose()
{
    $("#searchbox").slideUp();
    $("#searchbox").fadeOut();
}
function searchSubmitOver()
{
    $("#searchboxsubmit").attr("src",WebRoot() + "images/icons/search-light.png");
}
function searchSubmitOut()
{
    $("#searchboxsubmit").attr("src",WebRoot() + "images/icons/search.png");
}
function searchFocus()
{
    if($("#searchboxinput").val() == "search hsk.org.uk") $("#searchboxinput").val("");
    $("#searchboxinput").css("color","black");
}
function searchSubmit()
{
    if($("#searchboxinput").val() == "search.hsk.org.uk") $("#searchboxinput").val("");
}


/*************************
 THERMO
 *************************/

var thermoPageX, thermoOffsetX, thermoWidth, thermoProgressPercent, thermoProgressVal, thermoMercurySize, thermoXChunks, thermoAnimateCallback, thermoForceAnimate;
var thermoUseAnimation = true;
var thermoAnimateDuration = 500;
var thermoPointerFadeDuration = 400;
var thermoDisappearDuration = 600;
var thermoDisappearDelay = 3000;
var thermoDisappearObj = null;
var thermoDonateChunks = 250;

function thermoLoad()
{

    try { if(!thermoTarget) return; } catch(e) { return; }

    $("#thermometerwrapper").show();

    thermoOffsetX = $("#markers").offset().left;
    thermoWidth = $("#markers").width();
    thermoXChunks = thermoWidth / (thermoTarget/thermoDonateChunks);
 
    // set up static text: target and amount achieved
    $("#cash2").html("&pound;" + thermoTarget);
    $("#cash1").html("&pound;" + thermoAchieved);   
   
    // set up the thermometer using the amount raised so far
    thermoProgressVal = thermoAchieved;
    thermoProgressPercent = thermoCalculateProportion(thermoTarget,thermoAchieved);
    
    var targetX = thermoProgressPercent * thermoWidth;
    
    $("#mercury1").width(targetX);
    $("#mercury2").width(0);
    
    $("#pointer1").show(); 
    $("#pointer1").css("left",targetX); 
    $("#pointer2").show();
    
    if(!thermoXML || thermoXML == "") return;
    
    
    $("#markers").mousemove( function(e) { thermoMove(e.pageX,e.pageY); } );
    $("#markers").mouseout ( function(e) { thermoOut(e.pageX,e.pageY); } );
    thermoAnimate(true, null);
    
}

function thermoFinishAnimate(animateCallback)
{
    if(thermoProgressVal == thermoAchieved)
    {
        $("#pointer1text").html("ACHIEVED");
	  $("#bottompointer").stop(true,true);
	  $("#bottompointer").fadeOut(thermoPointerFadeDuration);
    }
    else
    {
        $("#pointer1text").html("&pound;" + (thermoProgressVal - thermoAchieved) + " would&#8230;");
        $("#bottompointer").fadeIn(thermoPointerFadeDuration);
        $("#bottompointertext").html("&#8230;give us " + inspirerDeduce(thermoProgressVal - thermoAchieved));
    }
    if(thermoAnimateCallback) thermoAnimateCallback();
}
function thermoAnimate(isLoading,animateCallback)
{
    thermoStop();
    var targetX = thermoProgressPercent * thermoWidth;
    var mercurySize = targetX - $("#mercury1").width();
    thermoAnimateCallback = animateCallback;
    if(isLoading)
    {
    }
    else
    {
        $("#bottompointer").animate( { left: targetX }, thermoAnimateDuration); 
        $("#pointer1").animate( { left: targetX }, thermoAnimateDuration); 
        $("#mercury2").animate( { width: mercurySize }, thermoAnimateDuration, function() { thermoFinishAnimate(); });
    }
}

function thermoCalculateProportion(overall, position)
{
    // for the time being use a linear scale
    return position/overall;
}

function thermoCapture(pageX,pageY,animateCallback)
{
    /* work out where the pointer is as a proportion of the width of the thermometer
       and from this as an overall value 
	 for the time being use a linear scale - can later change to logarithmic */
    thermoPageX = pageX;
    

    thermoProgressPercent = thermoCalculateProportion(thermoWidth,thermoPageX-thermoOffsetX);
    thermoProgressVal = parseInt(thermoTarget * thermoProgressPercent);
    
    // do not allow the user to move the slider behind the amount currently raised
    if(thermoProgressVal < thermoAchieved)
    {
        thermoProgressPercent = thermoAchieved / thermoTarget;
        thermoProgressVal = thermoAchieved;
    }
    // nor allow them to exceed the thermometer
    if(thermoProgressVal > thermoTarget)
    {
        thermoProgressPercent = 1;
        thermoProgressVal = thermoTarget;
    }

    /* now round the value we've found to the nearest £100
       or whatever has been specified by thermoDonateChunks */
    thermoProgressTopup = thermoProgressVal - thermoAchieved;
    thermoProgressTopup = thermoProgressTopup.toNearest(thermoDonateChunks);
    thermoProgressVal = thermoProgressTopup + thermoAchieved;
    //if(forceAnimate || thermoUseAnimation)
        thermoProgressPercent = thermoProgressPercent.toNearest(thermoCalculateProportion(thermoTarget,thermoDonateChunks)); 

    thermoAnimate(false,animateCallback);

}

  Number.prototype.toNearest = function(num) { // num is an exponent of 10
         return Math.round(this/num)*num;
  }


var thermoJustMovedOver = false;
function thermoOver(pageX,pageY)
{

    thermoJustMovedOver = true;
    thermoCapture(pageX,pageY,true,function(){thermoJustMovedOver=false;});
}
function thermoStop()
{
    $("#pointer1").stop(true,false); 
    $("#mercury2").stop(true,false);
    $("#bottompointer").stop(true,false);
}
function thermoMove(pageX,pageY)
{

    if(thermoDisappearObj) { 
    window.clearTimeout(thermoDisappearObj);
    $("#bottompointer").stop(true,true);
    $("#pointer1").stop(true,true);
    thermoDisappearObj = false;
    }
    if(!thermoJustMovedOver) thermoCapture(pageX,pageY,null);
}
function thermoOut()
{
    thermoDisappearObj = window.setTimeout('thermoDisappear();',thermoDisappearDelay);
}
function thermoDisappear()
{
    var targetX = (thermoAchieved/thermoTarget) * thermoWidth;
    $("#bottompointer").fadeOut(thermoDisappearDuration);
    $("#pointer1").animate( { left: targetX }, thermoDisappearDuration, function() { $("#pointer1text").html("ACHIEVED"); });
    $("#mercury2").animate( { width: 0 }, thermoDisappearDuration);
}






/*************************
 INSPIRER
 *************************/
var inspirerCosts, inspirerAmountDonated, inspirerAmountRemaining, inspirerCostsUsed, inspirerCostsUsedIDs, inspirerFlatCosts;

/* we don't want to display any costs which are less than 5% of the amount donated
this is to stop strings like "Your £50,000 will buy a new school and an art easel!"
set to 0 to disable */
var inspirerMinimumFraction = 0.05;

/* tell the user how much money is remaining? */
var inspirerDisplaySpare = true;




function inspirerDeduce(amount)
{
    if (window.DOMParser)
    {
        var doc = (new DOMParser()).parseFromString(thermoXML,"text/xml");
    }
    else // Internet Explorer
    {
        var doc=new ActiveXObject("Microsoft.XMLDOM");
        doc.async="false";
        doc.loadXML(thermoXML);
    } 
 
    
    inspirerAmountDonated = amount;
    inspirerAmountRemaining = inspirerAmountDonated;
    
    /* all the costs which have been met by the donation. associative array ordered by the 
    'for' tag, eg [one classroom] = Array(), [walls of a classroom] = Array(), [] = Array() */
    inspirerCostsUsed = new Array();
    inspirerCostsUsedIDs = new Array();
   
    // set all costs as unused
    inspirerCosts = doc.getElementsByTagName("cost");
    for(i=0;i<inspirerCosts.length;i++)
    { 
        inspirerCosts[i].setAttribute("id",i);
	  inspirerCosts[i].setAttribute("used",0);
    }
    
    // create a flat list of all the costs, sorted by amount
    inspirerFlatCosts = new Array();
    for(i=0;i<inspirerCosts.length;i++)
    {
        /* create a key like this:  XXXXXXXXXX.YYY
	     where X is the amount (padded to 10 chars) and Y the ID*/
	  var key = inspirerCosts[i].getAttribute("amount").toString();
	  while(key.length < 10) key = "0" + key;
	  key += "." + inspirerCosts[i].getAttribute("id");
        inspirerFlatCosts.push(key);
    }
    inspirerFlatCosts.sort();
    inspirerFlatCosts.reverse();

    /* traverse the tree looking for the biggest single cost that we can absorb with
    the amount we have remaining. continue until we have nothing remaining */
    while(inspirerAmountRemaining > 0)
    {
    
        var costToAbsorb = inspirerAbsorbCost();
	  
	  // can't absorb any more costs so quit
	  if(!costToAbsorb) break;
	  
	  
	  // parse the data: returned is the <cost> object we are going to absorb
	  inspirerAmountRemaining -= Number(costToAbsorb.getAttribute("amount"));
	  
	  costFor = costToAbsorb.getAttribute("context");
        if(!costFor) costFor = "";
	  if(!inspirerCostsUsed[costFor]) inspirerCostsUsed[costFor] = new Array();
	  inspirerCostsUsed[costFor].push(costToAbsorb);
	  
	  // deactivate this cost, and all sub-costs, as they have now been absorbed
        inspirerSetUsed(costToAbsorb);
	  
    } 
     
    var outString = new Array();
    for(var forCategory in inspirerCostsUsed)
    {
        subOutString = new Array();
        for(j=0;j<inspirerCostsUsed[forCategory].length;j++)
	  {
	      subOutString.push(inspirerCostsUsed[forCategory][j].getAttribute("name"));
	  }
	  subOutString = inspirerArrayToString(subOutString);
	  if(forCategory.substring(forCategory.length-2,forCategory.length) == "'s") outString.push(forCategory + " " + subOutString);
	  else if(forCategory != "") outString.push(subOutString + " " + forCategory);
	  else outString.push(subOutString);
    }
    
    var finalMessage = inspirerArrayToString(outString);
    if(inspirerDisplaySpare && inspirerAmountRemaining > 0) finalMessage += " with &pound;" + inspirerAmountRemaining + " spare!"
    else finalMessage += "!";
    return finalMessage;
}
function inspirerArrayToString(arr)
{
    var str = "";
    str += arr[0];
    for(i=1;i<arr.length-1;i++)
    {
       str += ", " + arr[i];
    }
    if(arr.length > 1)
    {
        str += " and " + arr[arr.length-1];
    }
    return str;
}
function inspirerAbsorbCost()
{
    for(i=0;i<inspirerFlatCosts.length;i++)
    {
        var key = inspirerFlatCosts[i].split(".");
	  var id = Number(key[1]);
	  var cost = inspirerCosts[id];

	  var amt = Number(cost.getAttribute("amount"));
	  if(cost.getAttribute("used") == 1) continue;
	  if(inspirerCostsUsedIDs[parseInt(id)]) continue;
	  
	  // don't notice any really small donations, unless it's the biggest possible donation
	  // this catches problems where someone donates say £5,000,000 and so no costs are picked up
	  if(amt < inspirerAmountDonated * inspirerMinimumFraction && id > 0) continue;
	  

	  if(amt <= inspirerAmountRemaining) return inspirerCosts[id];
    }
    return null;
}
function inspirerSetUsed(cost)
{
//    inspirerCosts[cost.getAttribute("id")].setAttribute("used",1);
    inspirerCostsUsedIDs[parseInt(cost.getAttribute("id"))] = true;
    if(cost.hasChildNodes())
    {
        for(i=0;i<cost.childNodes.length;i++)
	  {
	      try 
		{
	      if(cost.childNodes[i].getAttribute("id"))
		{
                inspirerSetUsed(cost.childNodes[i]);
		}
		} catch(e) {}
	  }
    }
}










/*************************
 MAPPER
 *************************/
 
var mapperActive = null;
var mapperMapX, mapperMapY, mapperMouseX, mapperMouseY, mapperW, mapperH;

function mapperLoad()
{
    $(".gilgilmap_moveable").mouseup  (function(e) { mapperUp(e,this); return false; });
    $(".gilgilmap_moveable").mouseout (function(e) { mapperUp(e,this); return false; });
    $(".gilgilmap_moveable").mousedown(function(e) { mapperDown(e,this); return false; });
    $(".gilgilmap_moveable").mousemove(function(e) { mapperMove(e,this); return false; });
}
function mapperDown(mapEvent,mapObj)
{
    
    mapperActive = mapObj;
    
    mapperMapX = parseInt($("#" + mapObj.id + "_inner").css("left").split("px")[0]);
    mapperMapY = parseInt($("#" + mapObj.id + "_inner").css("top").split("px")[0]);
    mapperMouseX = mapEvent.pageX;
    mapperMouseY = mapEvent.pageY;
    mapperW = $("#" + mapObj.id).width();
    mapperH = $("#" + mapObj.id).height();
}
function mapperUp(mapEvent,mapObj)
{
    mapperActive = null;
}
function mapperMove(mapEvent,mapObj)
{
    if(mapperActive == null) return;
    var newX = mapperMapX + (mapEvent.pageX - mapperMouseX);
    var newY = mapperMapY + (mapEvent.pageY - mapperMouseY);
    if(newX > 0) newX = 0;
    if(newY > 0) newY = 0;
    
    var minX = -600 + mapperW;
    var minY = -510 + mapperH;
    if(newX < minX) newX = minX;
    if(newY < minY) newY = minY;
    
    $("#" + mapperActive.id + "_inner").css("left", newX + "px");
    $("#" + mapperActive.id + "_inner").css("top", newY + "px");
}


/*************************
 WINDOW LOAD
 *************************/

function windowLoad()
{
    mapperLoad();
    thermoLoad();
}


$(window).load( function() { windowLoad(); } );
