﻿var shadowOpts = { offset : 3, opacity : 0.2 };
var IDMapping = { // this is to speed up DOM lookups. LookByID is 1000s of times faster..
    'buildingsTable' : 'ctl00_ContentPlaceHolder1_tblBuildings'
}
var genericMenuConfig = {
	moveAwayDelay	: 700,	// time in miliseconds!
	timer			: null,	// used internally.
	maxHeight       : 400,
	menus			: 	{
		'fake'	:	[
		    { select : '.header_bar a.reports, .header_bar a.mail, .header_bar a.clan', menuType : 'genericMenuFake' }
		],
		'helpMenu' : [
    		{ select : '.header_bar a.help', menuType : 'genericMenuStart', menuAlign : 'right' , stillClickable : true},
    		{ type: 'markup', 'markup': "<div class='menuHeader' style='background-image : url(http://static.realmofempires.com/images/navIcons/Help2.gif); width : 220px;'><span>Help</span></div>" },
		    { title : 'Beginner Tutorial', url : 'startTutorial.aspx', type : 'item', divider :  true},
			{ title : 'Help! What do I do now? Please advise.', url : 'Advisor.aspx', type : 'item', opts : { target : "_blank", onclick : "return popupAdvisor();" } },
			{ title : 'FAQ - Frequently Asked Questions', url : 'https://roe.fogbugz.com/default.asp?W287', type : 'item', opts : { target : "_blank"} },
			{ title : 'Buildings', url : 'Help.aspx', type : 'item' },
			{ title : 'Units', url : 'Help.aspx?HPN=Unit', type : 'item' },
			//{ type : 'divider' },
			{ title : 'Forum (Discussion board)', url : 'http://www.facebook.com/board.php?uid=10471770557', type : 'item', opts : { target : "_black" }, divider : true },
			{ title : 'Make a Suggestion', url : 'http://www.facebook.com/board.php?uid=10471770557', type : 'item', opts : { target : "_blank" } },
			{ title : 'Contact Support', url : 'ContactSupport.aspx', type : 'item'},
			//{ type : 'divider' },
			{ title : 'About Us', 
			  url : 'http://www.facebook.com/apps/application.php?id=10471770557', 
			  type : 'item', 
			  opts : { target : "_new" }, 
			  divider : true 
			},
			{ title : 'Terms Of Use', url : 'tou.aspx', type : 'item', opts : { target : "_new"} }
		],
		'ranking' : [
		    { select : '.header_bar a.ranking', menuType : 'genericMenuStart', menuAlign : 'right', stillClickable : true },
            { type: 'markup', 'markup': "<div class='menuHeader' style='background-image : url(http://static.realmofempires.com/images/navIcons/Ranking2.gif);'><span>Ranking</span></div>" },
		    { type : 'item', title : 'Player Ranking', url : 'stats.aspx' , divider :  true },
		    { type : 'item', title : 'Friend Network Ranking', url : 'playersFriendRanking.aspx' },
		    { type : 'item', title : 'Clan Ranking', url : 'clanranking.aspx' },
		    { type : 'item', title : 'Player Titles', url : 'TitlesRanking.aspx' },
		    { type : 'item', title : 'Global Stats', url : 'GlobalStats.aspx' },
		    { type : 'item', title : 'Friends of Realm Of Empires', url : 'pfDonors.aspx' }
		],
		'invite' : [
		    { select : '.header_bar a.invite', menuType : 'genericMenuStart', menuAlign : 'right', stillClickable : true },
            { type: 'markup', 'markup': "<div class='menuHeader' style='background-image : url(http://static.realmofempires.com/images/navIcons/Invite2.gif);'><span>Invite Friends</span></div>" },
		    { type : 'item', title : 'Invite Friends', url : 'invite.aspx', divider :  true  },
		    { type : 'item', title : 'Invites Sent', url : 'Invites_InvitedList.aspx' }
		],
		'settings' : [
		    { select : '.header_bar a.settings', menuType : 'genericMenuStart', menuAlign : 'right' , stillClickable : true},
            { type: 'markup', 'markup': "<div class='menuHeader' style='background-image : url(http://static.realmofempires.com/images/navIcons/Settings2.gif);'><span>Tools & Options</span></div>" },
		    { type : 'item', title : 'Unlock Features', url : 'pfBenefits.aspx', divider :  true },
		    { type : 'item', title : 'Kingdom Stewardship', url : 'AccountStewards.aspx'},
		    { type : 'item', title : 'Options', url : 'PlayerOptions.aspx'},
		    { type : 'item', title : 'RoE Mapper', url : 'http://www.realmofempires.com/roepowertools/roept.aspx', opts : { target : "_blank" }, divider :  true },
		    { type : 'item', title : 'Polls', url : 'Polls.aspx'},
		    { type : 'item', title : 'Switch Realm', url : 'logoutOfRealm.aspx', divider :  true }
		],
		'mail' : [
		    { select : '.header_bar a.mail', menuType : 'genericMenuStart', menuAlign : 'right' , stillClickable : true},
            { type: 'markup', 'markup': "<div class='menuHeader' style='background-image : url(http://static.realmofempires.com/images/navIcons/mail2.gif);'><span>Messages</span></div>" },
		    { type : 'item', title : 'Inbox', url : 'messages.aspx?fid=-1&va=false&pageindex=-1', divider :  true },
		    { type : 'item', title : 'Compose Message', url : 'messages_create.aspx'},
		    { type : 'item', title : 'Last View', url : 'messages.aspx'}
		],
		'reports' : [
		    { select : '.header_bar a.reports', menuType : 'genericMenuStart', menuAlign : 'right' , stillClickable : true},
            { type: 'markup', 'markup': "<div class='menuHeader' style='background-image : url(http://static.realmofempires.com/images/navIcons/reports2.gif);'><span>Reports</span></div>" },
		    { type : 'item', title : 'Inbox', url : 'Reports.aspx?fid=-1&va=false&reptid=-1&nosearch=1&pageindex=-1', divider :  true },
		    { type : 'item', title : 'Last View', url : 'Reports.aspx'}
		],
		'clan' : [
		    { select : '.header_bar a.clan', menuType : 'genericMenuStart', menuAlign : 'right' , stillClickable : true},
            { type: 'markup', 'markup': "<div class='menuHeader' style='background-image : url(http://static.realmofempires.com/images/navIcons/clan2.gif);'><span>My Clan</span></div>" },
		    { type : 'item', title : 'Overview', url : 'ClanOverview.aspx', divider :  true },
		    { type : 'item', title : 'Public Message', url : 'ClanPublicProfile.aspx'},
		    { type : 'item', title : 'Invitations', url : 'ClanInvitations.aspx'},
		    { type : 'item', title : 'Members', url : 'ClanMembers.aspx'},
		    { type : 'item', title : 'Forum', url : 'ClanForum.aspx'},
		    { type : 'item', title : 'Diplomacy', url : 'ClanDiplomacy.aspx'},
		    { type : 'item', title : 'Events', url : 'ClanEvents.aspx'}		    		    
		],
		'manage' : [
		    { select : "td.TroopsHeader a, a.jsTroopsMenu", menuType : 'genericMenuStart', menuAlign : 'right' , stillClickable : true},
            { type: 'markup', 'markup': "<div class='menuHeader' style='background-image : url(http://static.realmofempires.com/images/units/infantry.png);'><span>Manage Troops</span></div>" },
		    { type : 'item', url : "CommandTroops.aspx", title : "Command", tooltip : "Attack or support other villages", divider :  true },
            { type : 'item', url : "VillageUnitRecruit.aspx", title : "Recruit", tooltip : "Recruit more troops" },
            { type : 'item', url : "TroopMovementsIn.aspx?vid=-1", title : "Incoming", tooltip : "List of all inbound troops"},
            { type : 'item', url : "TroopMovementsOut.aspx?vid=-1", title : "Outgoing", tooltip : "List of all your outbound troops"},
            { type : 'item', url : "UnitsAbroad.aspx?PS=0", title : "My troops abroad", tooltip : "My troops in (supporting) other villages"},
            { type : 'item', url : "UnitsSupporting.aspx?vid=-1", title : "Support", tooltip : "Troops from other villages supporting my village"},
            { type : 'item', url : "BattleSimulator.aspx", title : "Battle Simulator", tooltip : "Allows you to simulate a battle", divider :  true}
		],
		/*'silver' : [
		    { type : 'item', url : '/', title : 'this is a test' }
		],*/
		'TA' : [
		    { select : 'a.jsTAMenu', menuType : 'genericMenuStart', stillClickable : true },
		    { type : 'item', url : "UnitsAbroad.aspx?PS=1", title : "See this village's troops supporting other villages", tooltip : "" },
            { type : 'item', url : "UnitsAbroad.aspx?PS=0", title : "See all my troops supporting other villages", tooltip : "" }
		],
		'Sup' : [
		    { select : 'a.jsSupMenu', menuType : 'genericMenuStart', stillClickable : true },
		    { type : 'item', url : "UnitsSupporting.aspx", title : "See Support I have at this village", tooltip : "" },
            { type : 'item', url : "UnitsSupporting.aspx?vid=-1", title : "See Support I have at all my villages", tooltip : "" }
		],
		'Outgoing' : [
		    { select : 'a.jsOutgoingMenu', menuType : 'genericMenuStart', stillClickable : true },
		    { type : 'item', url : "TroopMovementsOut.aspx", title : "See outbound troops from this village", tooltip : "" },
            { type : 'item', url : "TroopMovementsOut.aspx?vid=-1", title : "See outbound troops from all my villages", tooltip : "" }
		],
		'VddMenu' : [
		    { select : 'a.jsVddMenu', menuType : 'genericMenuStart' },
		    { type : 'item', url : "MyVillages.aspx", title : "Select a Village", tooltip : "", opts : { OnClick : "return popupVillageSelectionList(this);"  }},
            { type : 'item', url : "VillageSummary.aspx?b=1", title : "Summary: Buildings", tooltip : "", divider :  true },
            { type : 'item', url : "VillageSummary.aspx?u=1", title : "Summary: Units", tooltip : "" },
            { type : 'item', url : "VillageMassRecruit.aspx?u=1", title : "Mass Recruit", tooltip : "", divider :  true },
            { type : 'item', url : "VillageMassUpgrade.aspx?b=1", title : "Mass Upgrade", tooltip : "" },
            { type : 'item', url : "Tags.aspx", title : "Group Villages", tooltip : "" , divider :  true}
		],
		'Incoming' : [
		    { select : 'a.jsIncomingMenu', menuType : 'genericMenuStart', stillClickable : true },
		    { type : 'item', url : "TroopMovementsIn.aspx", title : "See inbound troops to this village", tooltip : "" },
            { type : 'item', url : "TroopMovementsIn.aspx?vid=-1", title : "See inbound troops to all my villages", tooltip : "" }
		]	
	}
	/* Other options for menu items 
	   * type can be 'item' or 'markup'
	     markup is freeform HTML basicly, item will just be a nice link
	   * divider can be true or false, just ture or false, not strigns eg "true"
	     This will make the top of the item a divider / seperator
	   * extra. Extra data it include in a <small> after the item, like the points on the village switch */
	   
	/* example code to enable a menu:
	  $(".header_bar a.ranking")
	    .addClass('genericMenuStart')
	    .attr('menu', 'ranking')
	    .attr('menuAlign', 'right'); */
};

//var console = { log : function () {} }; // comment this to enable console loggin in FF/Firebug!

var ui_id_helper = 1;
var destroyTimer;
var PreLoadImages = new Array();

function ReceiveIframeInput (name, value) 
{
	input = $('.jsiframeInput[rel="' + name + '"]')[0];
	
	if (input.tagName == "INPUT")
		$(input).attr('value', value);
	if (input.tagName == "TEXTAREA")
		$(input).text(value);
		
	return true;
}

function popupUnlock (link)
{    
    var url = $(link).attr('href');
    var w = popupWindow2(url, 'unlock', 500, 500);
    
    return false;}

function closeIFrame (name)
{
    if (name == "*")
    {
        $('iframe').parents('.iFrameDiv').remove();
    } else {
        // we're just going to hide the iframe/div.. for now.
        var id = 'popupIframe_' + name;
        $('#' + id)
            .attr('keep', 'no')
            .hide();
    }   
    return true;   
}

function popupIFrame (url, name, title, height, width, x, y)
{
    // construct a unique-ish id
    var id = 'popupIframe_' + name;
    
    // create the div, if it doesn't exist!
    if ($('#' + id).length > 0) {
        $('#' + id)
            .show()                // display the (posiably) hidden iframe div
            .attr('keep', 'yes');   // flag it as active
    } else {
        $('body').append('<div id="' + id + '" class="ui_menu genericMenu iFrameDiv" style="height:' + (height + 18) + 'px; width:' + width + 'px;"></div>');
        $('#' + id)
            .css( { top : y + 'px', left : x + 'px' })
            .append('<div class="IFrameDivTitle"><span class="title">' + title + '</span><img onclick="return !closeIFrame(\'' + name + '\');" src="http://static.realmofempires.com/images/delete.gif" /></div>')
            .append('<iframe name="' + name + '" border="0" style="height:' + height + 'px; width:' + width + 'px; border:none;" src="' + url + '" frameborder="0"></iframe>')
            .show()
            .attr('keep', 'yes')    // so that it's not instantly cleaned up.
            .mouseover(function () { $(this).attr('keep', 'yes'); }); // flag as active when it's hovered
    }
    
    return true;
}

function popupHandicapCalc(link)
{
    var url = $(link).attr('href');
    var p = $(link).position();
    //var w = popupWindow2(url, 'unlock', 450, 350);
    
    return !popupIFrame(url, 'HandicapCalc', "Handicap Calculator", 210, 550, p.left, p.top - 200);
}
function popupQuickSilverTransport (link)
{
    var url = $(link).attr('href');
    var p = $(link).position();
    //var w = popupWindow2(url, 'unlock', 450, 350);
    
    return !popupIFrame(url, 'QuickSilverTransport', "Convenient Silver Transport", 450, 350, p.left, p.top + 10);
}

function popupToOtherPlayersVillageSilverTransport (link)
{
    var url = $(link).attr('href');
    var p = $(link).position();
    //var w = popupWindow2(url, 'unlock', 450, 350);
    
    return !popupIFrame(url, 'ToOtherPlayersVillageSilverTran', "Quick Silver Transport", 450, 350, p.left, p.top + 10);
}

// ToOtherPlayersVillageSilverTransport  - TOPVST
function popupTOPVST(link, windowname)
{
    var url = $(link).attr('href');
    var p = $(link).position();
    //var w = popupWindow2(url, 'unlock', 450, 350);
    
    return !popupIFrame(url, windowname, "Quick Silver Transport", 450, 350, p.left, p.top + 10);
}

function popupVillageSelectionList (link)
{
    var url = $(link).attr('href');
    //var w = popupWindow2(url, 'unlock', 550, 550);
    var p = $(link).position();
    
    return !popupIFrame(url, 'VillageSelectionList', "Village Selection", 500, 450, p.left, p.top + 10);
}

// extend the Array prototype
if (Array.prototype.contains == null)
        Array.prototype.contains = function (t)
        {
                var i;
                for (i = 0; i < this.length; i++)
                        if (t.toLowerCase() == this[i].toLowerCase())
                                return true;

                return false;
        }

// preloader code
jQuery.preloadImages = function()
{
    for(var i = 0; i<arguments.length; i++)
    {
        PreLoadImages[i] = new Image();
		PreLoadImages[i].number = i;
		// PreLoadImages[i].onload = function () { $('#load_' + this.number).text('loaded'); };
		PreLoadImages[i].src = arguments[i];
    }
}

// click menus for the top icons
$(
    function ()
    {
        // preload some images
        $.preloadImages(
            // images for map borders
            'http://static.realmofempires.com/images/map/MapBorderTL2.png',
            'http://static.realmofempires.com/images/map/MapBorderT2.png',
            'http://static.realmofempires.com/images/map/MapBorderTR2.png',
            'http://static.realmofempires.com/images/map/MapBorderR2.png',
            'http://static.realmofempires.com/images/map/MapBorderBR2.png',
            'http://static.realmofempires.com/images/map/MapBorderB2.png',
            'http://static.realmofempires.com/images/map/MapBorderBL2.png',
            'http://static.realmofempires.com/images/map/MapBorderL2.png',
            // menu icons
            'http://static.realmofempires.com/images/navIcons/18.gif',
            // village icons
            'http://static.realmofempires.com/images/map/village1a.png',
            'http://static.realmofempires.com/images/map/village1b.png',
            'http://static.realmofempires.com/images/map/village2a.png',
            'http://static.realmofempires.com/images/map/village2b.png',
            'http://static.realmofempires.com/images/map/village3a.png',
            'http://static.realmofempires.com/images/map/village3b.png',
            'http://static.realmofempires.com/images/map/village4a.png',
            'http://static.realmofempires.com/images/map/village4b.png',
            'http://static.realmofempires.com/images/map/village5a.png',
            'http://static.realmofempires.com/images/map/village5b.png',
            'http://static.realmofempires.com/images/map/village6a.png',
            'http://static.realmofempires.com/images/map/village6b.png',
            // menu buttons
            'http://static.realmofempires.com/images/navIcons/Reports1.gif',
            'http://static.realmofempires.com/images/navIcons/Reports2.gif',
            'http://static.realmofempires.com/images/navIcons/Reports3.gif',
            'http://static.realmofempires.com/images/navIcons/Reports4.gif',
            'http://static.realmofempires.com/images/navIcons/Mail1.gif',
            'http://static.realmofempires.com/images/navIcons/Mail2.gif',
            'http://static.realmofempires.com/images/navIcons/Mail3.gif',
            'http://static.realmofempires.com/images/navIcons/Mail4.gif',
            'http://static.realmofempires.com/images/navIcons/Clan1.gif',
            'http://static.realmofempires.com/images/navIcons/Clan2.gif',
            'http://static.realmofempires.com/images/navIcons/Clan3.gif',
            'http://static.realmofempires.com/images/navIcons/Clan4.gif',
            'http://static.realmofempires.com/images/navIcons/Invite1.gif',
            'http://static.realmofempires.com/images/navIcons/Invite2.gif',
            'http://static.realmofempires.com/images/navIcons/Ranking1.gif',
            'http://static.realmofempires.com/images/navIcons/Ranking2.gif',
            'http://static.realmofempires.com/images/navIcons/Help1.gif',
            'http://static.realmofempires.com/images/navIcons/Help2.gif',
            'http://static.realmofempires.com/images/navIcons/Settings1.gif',
            'http://static.realmofempires.com/images/navIcons/Settings2.gif');
        // execute the PNG fix
        //$(document).pngFix();
        
        // used to store menus
        $('body').append('<div id="allMenus"></div>');
        
        // replace some text/forms with links etc
        //jaxReplace();
        
        // we need to do stuff the user would ntice first
        genericMenusInit(); // new menus
        initHideBuildRequirements();
        initTroopsTable();
        
        // Now we can add click effects and such;
        //initTopMenus();
        //initClickOff();
        //initVillageLink();
        
        // init timers
        
        // Init the help system
        initTutorial();
        initHelpLoadDB();
        
        // init all drop down expanders
        initDropDownExpanders();
        
        // fake selects
        //initFakeSelects();
        
        // upgrade to XX level
        initUpgradeToLevels();
        
        //initConfirm();
        
        checkIE();
        
        // init village Next/Prev
        NextPrevVillage();
        
        //init CoORds, if they're availabe
        try {
            InitCoOrds();
        } catch (e) {
            // ignored
        }
        
        // add hover over effect for get more silver icon
        if ($('.getMoreSilverIcon').length > 0) {
            $('.getMoreSilverIcon')
                .hover(
                    function () { $(this).attr('src', 'http://static.realmofempires.com/images/GetMore3.gif'); },
                    function () { $(this).attr('src', 'http://static.realmofempires.com/images/GetMore2.gif'); }
                );
        }
    }
);

function initDropDownExpanders ()
{
    $('.expandRelated')
        .click( function () { $(".expandable[name='" + $(this).attr('name') + "']").toggle(); } )
        .css( { cursor : 'pointer' });
}

function initFakeSelects ()
{
    $('div.jsFakeSelect').each(
        function ()
        {
            var options = $(this).find('.jsOptions');
            var master = $(this).find('.jsMaster');
            var triger = $(this).find('.jsTriger');
           
            $(triger)
                .mouseover( function () { genericMenusClearNow(); $(this).parent().find('.jsOptions').show(); })
                .mouseout( function () { genericMenuTimer('genericMenusClear();'); });
            
            p = $(master).position();
            if ($(master).hasClass('includeMe')) {
                p.height = 0;
                $(master).clone().prependTo(options);
            } else {
                p.height = $(master).height();
            }
            
            $(options)
                .css({ 'left' : p.left + 'px', 'top' : (p.top + p.height) + 'px' })
                .mouseover( function () { $(this).attr('keep', 'yes');})
                .mouseout( function () { $(this).attr('keep', 'no'); genericMenuTimer('genericMenusClear();'); })
                
        });
    return;
}

function jaxReplace ()
{
    $('.jaxHide')
        .hide()
        .each(
            function () 
            {
                link = $('<a href="#">' + $(this).attr('rel') + '</a>').click(
                    function () { $(this).prev().slideDown().end().remove();return false; }
                );
                $(this).after(link);
            }
        );
    $('.jaxHideFader')
        .hide()
        .each(
            function () 
            {
                link = $('<a href="#">' + $(this).attr('rel') + '</a>').click(
                    function () { $(this).prev().fadeIn().end().remove();return false; }
                );
                $(this).after(link);
            }
        );
        
    $('.rplClanRename').hide().after('<a href="/" onclick="$(this).remove(); $(\'.rplClanRename\').slideDown(); return false;">Rename Clan</a>');
}

function checkIE ()
{
    ie = getIEVersionNumber();
    if (0 < ie && ie < 7) {
        if ($.cookie('ie6Warn') != 'shown') {
            ui_warn(['You are using a very old version of Internet Explorer! This game was designed to work with Internet Explorer 7 or FireFox 2 or above. You will need to upgrade your browser for best experince', 'While the game <b>will</b> work you will experience problems with graphics.']);
            $.cookie('ie6Warn', 'shown');
        }
        
        // replace PNGs with GIF..
        $('img').each(
            function () {
                if ( m=$(this).attr('src').match(/\/vov\/.+png$/) ) {
                    //$(this).attr('src', $(this).attr('src').replace(/png$/, 'gif'));
                }
            }
        );
    }
}

function getIEVersionNumber () {
    var ua = navigator.userAgent;
    var MSIEOffset = ua.indexOf("MSIE ");
    
    if (MSIEOffset == -1) {
        return 0;
    } else {
        return parseFloat(ua.substring(MSIEOffset + 5, ua.indexOf(";", MSIEOffset)));
    }
}

function ui_warn (message)
{
    if ($('#ui_warn').length == 0)
        $('body').append('<div id="ui_warn"></div>');
    
    $('#ui_warn').append('<div class="ui_warn"></div>');
    $(message).each(
        function () {
            $('#ui_warn .ui_warn:last').append('<p>' + this + '</p>');
        }
    );
    $('#ui_warn .ui_warn:last').append('<a href="#" onclick="return ui_warn_dismis(this.parentNode);">Dismiss</a>');
}

function ui_warn_dismis (node)
{
    $(node).fadeOut('fast', function () 
                    {
                        $(this).remove();
                        if ($('#ui_warn').children().length == 0)
                            $('#ui_warn').remove();
                    });
    return false;
}

function initConfirm ()
{
    if ($('.genConfirm').length > 0) {
        //
        p = $('.genConfirm').position();
        //$('.genConfirm').css( { zIndex : 200, top : p.top + 'px', left : p.left + 'px' } );
        $('.genConfirm').css( { position : 'relative' }).click( function () { return false } );
        $('body').prepend('<div id="genConfirmBlock"></div>');
        $('#genConfirmBlock').css({ opacity : 0 }).animate({ opacity : 0.6 }).click( function () { alert('Confirm or cancel'); } );
    }
}

// enable the cose button
$(function () { $('#popUpClose a, #popUpClose button').click(function () { window.close(); }); });

function popupAdvisor ()
{
    newWindow = popupWindow('Advisor.aspx');
    DumperMaxDepth = 3;
    //DumperAlert(newWindow.document.location);
    /*if (!newWindow.document.location.pathname)
        alert('You must disable your popup blocker for this to work');*/
        
    return false;
}

function popupWindow (url, name)
{
    popupWindow2(url, name, 450,500);
}

function popupWindow2 (url, name, height, width)
{
    try {
        this.newWindow = window.open(url, name, 'height='+height+',width='+width+',resizeable=yes,scrollbars=yes,toolbar=no,menubar=no,location=no,status=no,directories=no');
    } catch (e) {
        alert('Popup blocked! Make sure to allow JavaScript popups!');
        return null;
    }
    return this.newWindow;
}


function initHideBuildRequirements ()
{
    $('.hiddenRequirementsShow').click(
        function ()
        {
            line = $(this).siblings('.hiddenRequirements');
            if (line[0].style.display == 'none')
                //$(this).siblings('.hiddenRequirements').attr('style', '').slideDown();
                $(this).siblings('.hiddenRequirements').attr('style', '').show();
            else
                //$(line).slideToggle();
                $(line).toggle();
                
            return false;
        }
    );//.wrap('<a href="#"></a>');
}

function initUpgradeToLevels ()
{
    // to debug: $('body').append('<td keepers="upgradeMenu1" class="tut" rel="upgrade3"><a class="StandoutLink" href="Upgrade.aspx?bid=3&amp;l=13&amp;vid=2">Upgrade to Level 13</a><span> (</span><a upgrademenu="1" class="jsUpgradeMenu" rel="2/13" href="Upgrade.aspx?bid=3&amp;l=10&amp;vid=2&amp;max=1">level 10</a><span>)</span></td>');
    var i = 0;
    $('.jsUpgradeMenu', $('#' + IDMapping['buildingsTable'])).each(
        function ()
        {
            levels = $(this).attr("rel").split('/');
            $(this).attr('max', levels[1]);
            $(this).attr('min', levels[0]);
            $(this)
                .mouseover(UpgradeToMenu)
                .attr("upgradeMenu", ++i);
            
            $(this)
                .parent()
                .mouseout(genericMenusClearFast)
                .mouseover(keepMine)
                .attr("keepers", "upgradeMenu" + i);
        }
    );
}

function keepMine ()
{
    keep = $(this).attr('keepers');
    $('#' + keep).attr('keep', 'yes');
}

function UpgradeToMenu ()
{
    id = "upgradeMenu" + $(this).attr("upgradeMenu");
    url = $(this).attr("href").replace(/l=\d+/, 'l=###');
    td = $(this).parent()[0];
    p = $(td).position();
    p.top += $(td).height();
    p.width = $(td).width();
    
    if ($('#' + id).length == 0) {
        options = new Array();
        var min = parseInt($(this).attr("min"), 10);
        var max = parseInt($(this).attr("max"), 10);
        var l = Math.round(parseInt(min/5)*5) + 5;
        
        while (l <= (max - 5))
        {
            options.push(l);
            l += 5;
        }
        while (min < max + 1)
        {
            if (min > (max - 5))
                options.push(min);
                
            min++;
        }
        
        $('#allMenus').append('<div style="background-color : rgb(91,102,96); padding : 3px 1px;" id="' + id + '"><span>&nbsp;Upgrade to:</span> </div>');
        for (i=0; i<options.length; i++)
            $('#' + id).append('<a href="' + url.replace('###', options[i]) + '">' + options[i] + '</a>' + ( i < options.length - 1 ? ", "  : "" ));
            
        $('#' + id)
            .css( { 
                position    : 'absolute',
                left        : p.left + 'px',
                top         : p.top  + 'px',
                width       : p.width + 'px' })
            .addClass("ui_menu_fast")
            .mouseover( function () { $(this).attr('keep', 'yes') } )
            .mouseout(genericMenusClearFast)
            .mouseout( function () { $(this).attr('keep', 'no') } )
            .attr('keep', "yes");
    } else {
        $('#' + id)
            .show()
            .attr('keep', 'yes');
    }
}

function initClickOff ()
{
    $(document).click(clickOff);
    
    // Hide out workings. 
    $('span.hide').hide();
}

function clickOff () {
    // Close up any open "building requeirments"
    /*
    $('.show').siblings().hide();
    $('.show').show().children().show();
    old */
    $('.hiddenRequirements').hide();
    
    // Close and open menus
    $('.ui_menu_fast, .ui_menu, .dropMenu').each(
        function ()
        {
            if ($(this).attr('justCreated') == 'yes')
                $(this).attr('justCreated', 'no');
            else if ($(this).attr('ui_type') == "hide")
                $(this).hide().shadowDestroy();
            else
                $(this).shadowDestroy().remove();
        }
    );
}

function initTroopsTable ()
{
    // init the "show more detail" on the troops table.
    $('.hideMe').addClass('hideMeMaybe');
    
    $('a.tlbHideSome').click(
        function ()
        {
            $('.tlbHideSome .hideMeMaybe').toggleClass('hideMe');
            width = $(this).parents('.BasicBox').children(".Box").width();
            if ($(this).text().match(/more/))
                $(this).text('[Show less detail]');
            else
                $(this).text('[Show more detail]');
                
            return false;
        }  
    );
}


function selectVillageURL (newSvid)
{
    url = 'VillageOverview.aspx?svid=';

    // newQuery will hold the values that ARE to be propergated
    newQuery = null;

    try {
        // grab the users current URL
        current = window.location.toString().split(/\?/);

        // break off the query
        url = current[0];
        query = current[1];

        // break apart the query, into name=value pairs
        query = breakQuery(query);

        // some URIs need certin paramitors stripped from thier query_string.
        if (url.match(/(UnitsSupporting.aspx|UnitsAbroad.aspx)/))
            newQuery = stripQuery(query, ['SiVID', 'SdVID', 'svid']);
        else
            newQuery = stripQuery(query, ['svid']);
    } catch (e) {
        ReportException('window.location', e.message, 'menus.js');
    }

    // Find the .aspx filename
    url = url.match(/([a-zA-Z_]+\.aspx)$/);
    url = url[0];

    // For some URLs the village switch doesn't make much sense
    if (url.match(/createmail\.aspx/)) // URL/Query filter for 814
        newQuery = stripQuery(newQuery, ['recid']);

    newQuery = stripQuery(newQuery, ['svid']);
    newQuery.push( { 'name' : 'svid', 'value' : newSvid });
    
    return url + '?' + buildQuery(newQuery);
}

function selectVillage (newSvid)
{
    var url = selectVillageURL(newSvid);
    window.location = url;
}

function initVillageLink () {
    // Add a click effect to the "My Villages" link in the header
    $('.VillageList').click(
        function () {
            // find exectly where the link is. 
            position = $(this).position();
            height = $(this).height();

            url = 'VillageOverview.aspx?svid=';

            // newQuery will hold the values that ARE to be propergated
            newQuery = null;

            try {
                // grab the users current URL
                current = window.location.toString().split(/\?/);

                // break off the query
                url = current[0];
                query = current[1];

                // break apart the query, into name=value pairs
                query = breakQuery(query);

                // some URIs need certin paramitors stripped from thier query_string.
                if (url.match(/(UnitsSupporting.aspx|UnitsAbroad.aspx)/))
                    newQuery = stripQuery(query, ['SiVID', 'SdVID', 'svid']);
                else
                    newQuery = stripQuery(query, ['svid']);
            } catch (e) {
                ReportException('window.location', e.message, 'menus.js');
            }
            
            // Find the .aspx filename
            url = url.match(/([a-zA-Z_]+\.aspx)$/);
            url = url[0];
            
            // For some URLs the village switch doesn't make much sense
            if (url.match(/createmail\.aspx/)) // URL/Query filter for 814
                newQuery = stripQuery(newQuery, ['recid']);
            
            // Find the users villages from the markup
            menuData = [ { 'type' : 'markup', 'markup' : 'Summary: <a class="normal" href="VillageSummary_buildings.aspx">Buildings</a> | <a class="normal" href="VillageSummary_Units.aspx">Units</a>' } ];
            $(myVillages).each(
                function () {
                    if (!this.P)
                        return false;

                    newQuery = stripQuery(newQuery, ['svid']);
                    newQuery.push( { 'name' : 'svid', 'value' : this.id });

                    this.url = url + '?' + buildQuery(newQuery);
                    menuData.push( { 'type'   : 'item', 
                        'title'  : this.name + ' (' + this.X + ',' + this.Y + ') ',
                        'extra'  : "Points: " + addCommas(this.P) + ", Silver: " + addCommas(this.S),
                        'url'    : this.url
                    } );
                }
            );

            // render a drop menu of villages and some stats.
            dropMenu('scroll', position.left, position.top, height, 630, -1, menuData);
            //if ($('#dropMenu_scroll').height() > 300)
            //   $('#dropMenu_scroll').css('height', 300 + 'px');

            return false;
        }
    );
}

function buildQuery (query)
{
    var queryString = null;
    for (i = 0; i < query.length; i++) {
        if (queryString)
            queryString = queryString + '&' + query[i].name + "=" + query[i].value;
        else
            queryString = query[i].name + "=" + query[i].value;
    }
    return queryString;
}

function breakQuery (query)
{
    if (!query)
        return null;
    
    try {
        var newQuery = new Array();
        
        var q = query.split(/&/);
        for (i=0; i < q.length; i++) {
            pair = q[i].split(/=/);
            if (pair[1])
                newQuery.push( { 'name' : pair[0], 'value' : pair[1] } );
        }
        return newQuery;
    } catch (e) {
        DumperAlert([{ 'e' : e }, 'breakQuery' ]);
    }
    return null;
}

function stripQuery (queryString, toStrip)
{
    newQuery = new Array();

    if (!queryString)
        return newQuery;
        
    for (i=0; i < queryString.length; i++) {
        mustKeep = true;
        for (o=0; o < toStrip.length; o++) {
            if (toStrip[o].toLowerCase() == queryString[i].name.toLowerCase())
                mustKeep = false;
        }
        if (mustKeep) {
            newQuery.push(queryString[i]);
        }
    }
    return newQuery;
}

function BuildURL (path, data)
{
    var url = path;
    if (data.length > 0) {
        url = url + '?' + data.join('&');
    }
    return url;
}
function BuildAnchor (text, url, opts)
{
    attr = "";
    if (opts)
        for (x in opts) {
            attr += ' ' + x + '="' + opts[x] + '"';
        }
    return '<a href="' + url + '"' + attr + '>' + text + '</a>';
}


    function InitStripeTable()
    {
        $('.stripeTable tr.highlight').hover(
            function () { $(this).addClass('stripeTableHover'); },
            function () { $(this).removeClass('stripeTableHover'); }
        );
    }

$(
    function ()
    {
        $('.stripeTable tr.popupHighlight').hover(
            function () { $(this).addClass('stripeTablePopupHover'); },
            function () { $(this).removeClass('stripeTablePopupHover'); }
        );
    }
);


function ReportException (name, message, file)
{
    DumperAlert([name, message, file]);
    $.ajax(
        {
            'type'  :   'POST',
            'url'   :   '/ReportException'
            //'data'  :   { 'name' : name, 'message' : 'message', file }
        }
    );
}

function NextPrevVillage ()
{
    if (!window.myVillages)
        return; // we're not on a standard load, so exit.
        
    // prepareMyVillagesArray() adds .url attributes to the village list
    prepareMyVillagesArray();
    
    // find the id of the current village, try cookies first, then parse the URL.
    if (!(svid = $.cookie('svid')))
        svid = parseInt(window.location.href.match(/svid=(\d+)/)[1], 10);
    
    if (myVillages[0].id == svid)
        $('.jPrevVillage').children('img').attr('src', 'http://static.realmofempires.com/images/leftArrow0.png');
    else
        $('.jPrevVillage').attr('href', myVillages[0].url);
    
    // find the last avalaible village
    last = myVillages.pop();
    if (!last)
        last = myVillages.pop();
        
    if (last.id == svid)
        $('.jNextVillage').children('img').attr('src', 'http://static.realmofempires.com/images/rightArrow0.png');
    else
        $('.jNextVillage').attr('href', last.url);
}

function genericMenusInit ()
{
    // for debugging
    //console.log('Init generic menus');

    // the "click off", and mouse away
	$('body')/*.mouseover(bodyHover)*/.click(genericMenusClear);
	
	for (x in genericMenuConfig.menus) {
	    config = genericMenuConfig.menus[x][0];
	    $(config.select)
	        .addClass(config.menuType)
	        .attr('menu', x)
	        .attr('menuAlign', config.menuAlign);
	    if (config.stillClickable)
	        $(config.select).addClass('stillClickable');
	}

	
	
	
	$('.genericMenuStart')
	    .mouseout(genericMenuUnKeep)// function () {  genericMenuTimer('genericMenusClear();'); } )
	    .mouseover(genericMenu)
	    .click( function () { if ($(this).hasClass('stillClickable')) { return true; } return false; });
	    //.mousemove(genericMenu); //.click(genericMenu);
	$('.genericMenuClicker')
	    .mouseout(genericMenuUnKeep)
	    .click(genericMenu);
	$('.genericMenuFake')
	    .mouseover(genericMenusClear);
}

function genericMenuConvert (id)
{   
	$('#genericMenu_' + id)
	    .mouseover( 
	        function (){ 
	            //console.log("Mouse over on the menu! setting keep=yes");
	            $(this).attr('keep', 'yes');
	        })
	    .mouseout( 
	        function () { 
	            //console.log("Mouse Out on menu! Calling genericMenuTimer to set a MenusClear() timeout");
	            $(this).attr('keep', 'no');
	            genericMenuTimer('genericMenusClear();'); 
	        } );
}

function genericMenuUnKeep ()
{
    id = 'genericMenu_' + $(this).attr('menu');
    //console.log('Unkeep for %s!', id);
    
    $('#' + id).attr('keep', 'no'); // mark the menu as "Non-Keep"
    genericMenuTimer('genericMenusClear();'); // clear all non-keep menus
}

function bodyHover ()
{
	genericMenuTimer('genericMenusClear();');
}

function genericMenuTimer (command)
{
    //console.log("genericMenuTimer Called (%s)", command);
	if (!command) {
		// no command, call just wants to cancel a timer
		if (genericMenuConfig.timer) {
			clearTimeout(genericMenuConfig.timer);
			genericMenuConfig.timer = null;
		} else{
		}
	} else {
		// we have a command,
		if (!genericMenuConfig.timer) {
			// no timer set, so we can set one!
			genericMenuConfig.timer = setTimeout(command, genericMenuConfig.moveAwayDelay);
		}
	}
}

function genericMenusClearNow (id)
{
	$(".genericMenu, .ui_menu, .ui_menu_fast").attr('keep', 'no');
	$('#' + id).attr('keep', 'yes');
	
	genericMenusClear();
}

function genericMenusClearFast ()
{
    //alert("Found : " + $(".ui_menu_fast[keep!='yes']").length);
    $(".ui_menu_fast[keep!='yes']").hide();
    $(".ui_menu_fast").attr('keep', 'no');
    setTimeout(genericMenusClearFast_b, 10);
}
function genericMenusClearFast_b ()
{
    //alert("Found : " + $(".ui_menu_fast[keep!='yes']").length);
    $(".ui_menu_fast[keep!='yes']").hide();
}
function genericMenusClear ()
{
    // code for fading
    //if ($(".genericMenu[keep!='yes']").attr('fade') == 'none')
    //	$(".genericMenu[keep!='yes']").attr('fade', 'fast').fadeOut('fast', function () { $(this).attr('fade', 'done'); });
	$(".genericMenu[keep!='yes'], .ui_menu[keep!='yes']").hide();
	
	$(".genericMenu, .ui_menu").attr('keep', 'no');
	
	// cancel the timer (we were just called..)
	//console.log("Clear any non-keep UI menus, calling genericMenuTimer to cancel timers");
	genericMenuTimer(null);
}

function genericMenu (e)
{
    //alert('genericMenu()');
    
    //console.log('genericMenu called. ClientX: %d, ClientY : %d', e.clientX, e.pageY);
    
	if (!(id = 'genericMenu_' + $(this).attr('menu')))
		return;
		
	genericMenusClearNow(id);

	// find the right position
	p = $(this).position();
	p.o = $(this).height();
	p.r = $(this).width()-2; //for some reason on IE, when vertical scroll bar is present, showed tools menu was slighly off screen to the right
	
	// check we have a cache, if we don't we need the build a menu
	if ($('#' + id).length == 0)
		genericMenuCreate(id);
	
	// mark the menu as "to keep", then show the menu.
	$('#' + id).attr('keep', 'yes').attr('fade', 'none').show();
	
	// make sure the ul stays the same width!
	$('#' + id + ' ul').css('width', $('#' + id + ' ul').width() + 'px');
	
	// check size constriants
	if ($('#' + id + ' ul').height() > genericMenuConfig.maxHeight)
		$('#' + id + ' .genericMenuInner').css( { width : ($('#' + id + ' ul').width() + 25) + 'px', height : genericMenuConfig.maxHeight + "px", overflow : 'auto' } );

	// find the width of the menu and the document, and if needed calculate a new menu x co-ord.
	docWidth = $(document).width();
	menuWidth = $('#' + id).width();
	if ($(this).attr('menuAlign') == "right") {
	    p.left = (p.left + p.r) - menuWidth;
	} else {
	    if (p.left + menuWidth > docWidth) // IF the menu + it's left position is greater than the right and side we need to move the menu
		    p.left = docWidth - (menuWidth + 2);
	}
	// reposition the menu
	if ($('#' + id).attr('fix') == 'done')
	    return false;
	    
    
    	
    if ($('#' + id).attr('fix') == 'yes') {
    	$('#' + id).css({ top : (p.top + p.o) + 'px', left : p.left + 'px', width : $('#' + id).width() + 'px' });
        $('#' + id).attr('fix', 'done');
    } else {
        $('#' + id).css({ top : (p.top + p.o) + 'px', left : p.left + 'px' });
    }
	return false;
}
function genericMenuCreate (id)
{
	name = id.match(/_(.+)/)[1];
	markup = genericMenuMarkup(name);
	
  	$('body').append('<div class="ui_menu genericMenu" style="display : none;" id="' + id + '"><div class="genericMenuInner"><ul>' + markup + '</ul></div></div>');
	
	
	// apply mouse overs 
	$('#' + id)
	    .mouseover( 
	        function (){ 
	            //console.log("Mouse over on the menu! setting keep=yes");
	            $(this).attr('keep', 'yes');
	        })
	    .mouseout( 
	        function () { 
	            //console.log("Mouse Out on menu! Calling genericMenuTimer to set a MenusClear() timeout");
	            $(this).attr('keep', 'no');
	            genericMenuTimer('genericMenusClear();'); 
	        } );
	    //.click( function () { return false; } );
}

function genericMenuData (name)
{
	// DumperAlert(genericMenuConfig.menus[name]);
	name = name.replace(/\d+$/, '');
	if (genericMenuConfig.menus[name])
		return genericMenuConfig.menus[name];
}
function genericMenuData_Help ()
{
    rid = $(".header_bar a.help").attr('href').match(/rid=(\d+)/)[1];
    menu = [
    		{ title : 'Beginner Tutorial', url : BuildURL('startTutorial.aspx', []), type : 'item'},
			{ title : 'Help! What do I do now? Please advise.', url : 'Advisor.aspx', type : 'item', opts : { target : "_blank", onclick : "return popupAdvisor();" } },
			{ title : 'Buildings', url : BuildURL('Help.aspx', ['rid=' + rid]), type : 'item' },
			{ title : 'Units', url : BuildURL('Help.aspx', ['rid=' + rid, 'HPN=Unit']), type : 'item' },
			//{ type : 'divider' },
			{ title : 'Forum (Discussion board)', url : 'http://www.facebook.com/board.php?uid=10471770557', type : 'item', opts : { target : "_black" }, divider : true },
			{ title : 'Suggestions', url : 'http://www.facebook.com/edittopic.php?uid=10471770557&action=8', type : 'item', opts : { target : "_blank" } },
			{ title : 'Support / Report a bug', url : 'http://www.facebook.com/edittopic.php?uid=10471770557&action=8', type : 'item', opts : { target : "_blank" } },
			//{ type : 'divider' },
			{ title : 'About Us', 
			  url : 'http://www.facebook.com/apps/application.php?id=10471770557', 
			  type : 'item', 
			  opts : { target : "_new" }, 
			  divider : true 
			},
			{ title : 'Terms Of Use', url : 'tou.aspx', type : 'item', opts : { target : "_new"} }
    ];
    return menu;
}

function genericMenuMarkup (name)
{
	if (name == "villages") {
		data = genericMenuData_Villages();
	/* replaced with click menu div } else if (name == "silver") {
	    data = []; */
	} else if (name == "help") {
	    data = genericMenuData_Help();
	} else {
		data = genericMenuData(name);
	}
	//DumperAlert(data);
	markup = '';
	
	// compile the data into markup
	for (i=0; i<data.length; i++) {
		extra = '';
		
		// for stuff like class="" and rel='x'
		if (data[i].opts)
			for (opt in data[i].opts)
				extra += ' ' + opt + '="' + data[i].opts[opt] + '"';

		// work out what to do with the item
		if (data[i].type == "item") {
			if (data[i].divider == true)
				markup += '<li class="divider">';
			else
				markup += '<li>';
				
			markup += '<a href="' + data[i].url + '"' + extra + '><span class="title">' + data[i].title + '</span>&nbsp;';
			if (data[i].extra)
				markup += '<small>' + data[i].extra + '</small>';
			
			markup += '</a></li>';
		} else if (data[i].type == "title") {
			markup += '<li id="' + itemID + '"><a><span class="title">' + this.title + '</span>&nbsp;</a></li>';
		} else if (data[i].type == "divider") {
			markup +='<div class="divider"><hr /></div>';
		} else if (data[i].type == "markup") {
			markup += '<li class="markup">' + data[i].markup + '</li>';
		}
	}
	
	return markup;
}

// function to make the village menu code
function genericMenuData_Villages ()
{
	menudata = [];
	
	// Summery is on the villages menu, no mather how many village you have
	menudata.push({ 'type' : 'markup', 'markup' : '<span class="summary">Summary: <a class="normal" href="VillageSummary_buildings.aspx">Buildings</a> | <a class="normal" href="VillageSummary_Units.aspx">Units</a></span>' });
	
	// defualt URL, failing all else..
	url = 'VillageOverview.aspx?svid=';
	
	// newQuery will hold the values that ARE to be propergated
    newQuery = null;

    try {
        // grab the users current URL
        current = window.location.toString().split(/\?/);

        // break off the query
        url = current[0];
        query = current[1];

        // break apart the query, into name=value pairs
        query = breakQuery(query);

        // some URIs need certin paramitors stripped from thier query_string.
        if (url.match(/(UnitsSupporting.aspx|UnitsAbroad.aspx)/))
            newQuery = stripQuery(query, ['SiVID', 'SdVID', 'svid']);
        else
            newQuery = stripQuery(query, ['svid']);
    } catch (e) {
        ReportException('window.location', e.message, 'menus.js');
    }
    
    // Find the .aspx filename
    url = url.match(/([a-zA-Z_]+\.aspx)$/);
    url = url[0];
    
    // For some URLs the village switch doesn't make much sense
    if (url.match(/createmail\.aspx/)) // URL/Query filter for 814
        newQuery = stripQuery(newQuery, ['recid']);
	
	// for loop over the myVillages array
	for (v=0; v< myVillages.length; v++)
	{
		// skip if i isn't valid
		if (!myVillages[v])
		    continue;
		
		if (!myVillages[v].url) {
		    // build a Query
		    newQuery = stripQuery(newQuery, ['svid']);
            newQuery.push( { 'name' : 'svid', 'value' : myVillages[v].id });

		    // build a URL
		    myVillages[v].url = url + '?' + buildQuery(newQuery);
		}
		try {
		    menudata.push( { type 	: 'item', 
					         title	: myVillages[v].name + ' (' + myVillages[v].X + ',' + myVillages[v].Y + ')',
					         extra	: 'Points: ' + addCommas(myVillages[v].P) + ', Silver: ' + addCommas(myVillages[v].S),
					         url	: myVillages[v].url,
					         divider: v == 0 ? true : false});
	    } catch (e) {
	    }
	}
	// format : { 'id':7596,'name':'Alex village','X':'69','Y':'-12','P':'63','S':'20793'},
	//DumperAlert(menudata);
	return menudata;
}

function prepareMyVillagesArray ()
{
	// defualt URL, failing all else..
	url = 'VillageOverview.aspx?svid=';
	
	// newQuery will hold the values that ARE to be propergated
    newQuery = null;

    try {
        current = window.location.toString().split(/\?/);
        url = current[0];
        query = current[1];
        query = breakQuery(query);

        // some URIs need certin paramitors stripped from thier query_string.
        if (url.match(/(UnitsSupporting.aspx|UnitsAbroad.aspx)/))
            newQuery = stripQuery(query, ['SiVID', 'SdVID', 'svid']);
        else
            newQuery = stripQuery(query, ['svid']);
    } catch (e) {
        ReportException('window.location', e.message, 'menus.js');
    }
    
    // Find the .aspx filename
    url = url.match(/([a-zA-Z_]+\.aspx)$/);
    url = url[0];
    
    // For some URLs the village switch doesn't make much sense
    if (url.match(/createmail\.aspx/)) // URL/Query filter for 814
        newQuery = stripQuery(newQuery, ['recid']);
	
	// for loop over the myVillages array
	for (v=0; v< myVillages.length; v++)
	{
		// skip if i isn't valid
		if (!myVillages[v])
		    continue;
		
		if (!myVillages[v].url) {
		    // build a Query
		    newQuery = stripQuery(newQuery, ['svid']);
            newQuery.push( { 'name' : 'svid', 'value' : myVillages[v].id });

		    // build a URL
		    myVillages[v].url = url + '?' + buildQuery(newQuery);
		}
	}
}

function reloadParent ()
{
    if (opener) {
        // we're executing from a popup window
        opener.windowReload();
        window.close();
    } else {
        // executing from an IFrame
        // Just close the ifrme (we have to know the name): window.parent.closeIFrame('QuickSilverTransport');
        window.parent.windowReload();
    }
       
    return false;
}
function loadInParent (element)
{
    var url = element.href ? element.href : element;
    
    if (opener) {
        // in a popup window
        opener.window.location.href = url;
        window.close();
    } else {
        window.parent.location.href = url;
    }
    
    return false;
}
function selectVillageInParent (link)
{
    var id = $(link).attr('href').match(/svid=(\d+)/)[1];
    
    window.parent.selectVillage(id);
    
    return false;
}
function bench (string, start)
{
    var now = new Date();
    $('body').append('<p>' + string + ": " + (now - start) + "</p>");
    
    return new Date();
}
