var domainroot = "http://potbs.armeagle.nl/";
/*
 * Functions to show and hide the popup for a given port
 * To be used on mouseover and mouseout
 */
function showPortPopup(DOMobj) {
    popup = document.getElementById('popup-'+DOMobj.id);
    popup.className = 'port-popup-visible';
}

function hidePortPopup(DOMobj) {
    popup = document.getElementById('popup-'+DOMobj.id);
    popup.className = 'port-popup-hidden';
}

/*
 * Open up a popup window with history data/graphs for the given port.
 * Stop propagation because in some occations this function will be called
 *  when parent objects are calling pingPort.
 */
function showPortHistory(event, server, portkey) {
    url = domainroot+'porthistory.php?server='+server+'&port='+portkey;
    portHistory = window.open(url,     
		        'porthistorywindow',
		        'height=480, width=600, location=no, status=no, menubar=no, resizable=1');
    portHistory.focus();

    if (!event) 
        event = window.event;

    event.cancelBubble = true;
    if (event.stopPropagation)
        event.stopPropagation();
}
/*
 * Open up a popup window with history data/graphs for the given server
 * Stop propagation because in some occations this function will be called
 *  when parent objects are calling pingPort.
 */
function showNvNScores(event, server) {
    url = domainroot+'nvnscores.php?server='+server;
    nvnScores = window.open(url,     
		        'nvnscores',
		        'height=420, width=620, location=no, status=no, menubar=no');
    nvnScores.focus();

    if (!event) 
        event = window.event;

    event.cancelBubble = true;
    if (event.stopPropagation)
        event.stopPropagation();
}

/***********************************************************************************/

/*
 * Function to show a visible 'crosshair' over the map
 */
var timeout = null;
var horiLine, vertLine;
function pingPort(portname) {
    horiLine = document.getElementById('ping-horizontal');
    vertLine = document.getElementById('ping-vertical');

    x = portCoordinates[portname].x;
    y = portCoordinates[portname].y;

    // clear any previous timeout
    if ( timeout != null ) {
        clearTimeout(timeout);
        horiLine.className = 'ping-port-hidden';
        vertLine.className = 'ping-port-hidden';
    }

    horiLine.style.top = (y-2)+'px';
    vertLine.style.left = (x-2)+'px';

    horiLine.className = 'ping-port-visible';
    vertLine.className = 'ping-port-visible';

    timeout = setTimeout("unPingPort()", 3000);
}
function unPingPort() {
    horiLine.className = 'ping-port-hidden';
    vertLine.className = 'ping-port-hidden';
}

/***********************************************************************************/

function toggleCircles(rd_obj, type) {
    // if swap circle-visible with circle-hidden and vice versa
    imgs = document.getElementsByTagName('img');
    switch ( type ) {
    case 'unrest' :
    case 'pvp' :
        // reset the dropdown
        var res = document.getElementById('toggleResources');
        res.selectedIndex = 0;
        break;
    case 'resource' :
        // uncheck the radio boxes
        document.getElementById('toggleUnrest').checked = null;
        document.getElementById('togglePvP').checked = null;
        break;
    }
    for(i=0;i<imgs.length;i++) {
        switch ( type ) {
        case 'unrest' :
	 if ( RemoveClassName(imgs[i], 'unrest-hidden') )
	      AddClassName(imgs[i], 'unrest-visible', false);
	 if ( RemoveClassName(imgs[i], 'pvp-visible') )
	      AddClassName(imgs[i], 'pvp-hidden', false);
	 if ( RemoveClassName(imgs[i], 'resource-visible') )
	      AddClassName(imgs[i], 'resource-hidden', false);
	 break;
        case 'pvp' :
	 if ( RemoveClassName(imgs[i], 'pvp-hidden') )
	      AddClassName(imgs[i], 'pvp-visible', false);
	 if ( RemoveClassName(imgs[i], 'unrest-visible') )
	      AddClassName(imgs[i], 'unrest-hidden', false);
	 if ( RemoveClassName(imgs[i], 'resource-visible') )
	      AddClassName(imgs[i], 'resource-hidden', false);
	 break;
        case 'resource' :
	 // first just reset all resource images
	 if ( RemoveClassName(imgs[i], 'resource-visible') )
	      AddClassName(imgs[i], 'resource-hidden', false);
	 if ( RemoveClassName(imgs[i], 'unrest-visible') )
	      AddClassName(imgs[i], 'unrest-hidden', false);
	 if ( RemoveClassName(imgs[i], 'pvp-visible') )
	      AddClassName(imgs[i], 'pvp-hidden', false);
	 break;
        }
    }
    // toggle on the right resource circles
    if ( type == 'resource' ) {
        for (i=0; i<portResources[rd_obj.value].length; i++) {
	 if (portResources[rd_obj.value]) {
	     var resimg = document.getElementById('resource-'+portResources[rd_obj.value][i]);
	     if ( RemoveClassName(resimg, 'resource-hidden') )
	         AddClassName(resimg, 'resource-visible', false);
	 }
        }
    }
}

/***********************************************************************************/
/*
 * A server was selected from the dropdown, change to that.
 * ; now cached pages are named 'map-[name].php', so that it can still contain some 
 *  php code (for timestamps).
 */
function serverSelect(select) {
    location.href = domainroot+'map-'+ select.value +'.php';
}

/***********************************************************************************/
/*
 * Two functions to sort the NvNchanges table.
 * This is solely using DOM to scan trough the table rows and find the right content
 * to filter on. This makes it easy to keep all styles, formatting, links, etc.
 *
 * Type specifies what property to sort on and optionally what unrest part to sort on.
 */ 
function sortUnrestChanges(type) {
    var unrestTable = document.getElementById('port-unrest-changes').getElementsByTagName('tbody')[0];
    var allNodes = unrestTable.getElementsByTagName('tr');

    // start with the second element
    for ( var allIndex = 1; allIndex < allNodes.length; allIndex++ ) {
        var targetRows = unrestTable.getElementsByTagName('tr');
        var targetIndex = 0;
        var inserted = false;
        // now, only compare up to the already sorted elements (allIndex)
        while ( targetIndex < allIndex ) {
	 if ( compareElements(type, allNodes[allIndex], targetRows[targetIndex]) < 0 ) {
	     // insert before
	     unrestTable.insertBefore(allNodes[allIndex], targetRows[targetIndex]);
	     inserted = true;
	     break;
	 } else {
	     targetIndex++;
	 }
        }
        // check whether it's inserted already
        if ( !inserted ) {
	 if ( targetIndex + 1 >= targetRows.length ) {
	     unrestTable.appendChild(allNodes[allIndex]);
	 } else {
	     unrestTable.insertBefore(allNodes[allIndex], targetRows[targetIndex+1]);
	 }
        }
    }
    allNodes = null;
}
/*
 * Compares two rows.
 * Type specifies what property to sort on and optionally what unrest part to sort on.
 * Returns -1 if first goes before second, 1 if first goes after second
 */
function compareElements(type, first, second) {
    var nationSortIndex = -1; // What nation(column) to sort on, to use a generic function
    var unrestPart = 0; // What part of the unrest string to sort on. 0: the unrest number  1: -1h  2: -12 h
    switch (type.split(' ')[0]) {
    case "name":
        var firstName = first.getElementsByTagName('td')[0].childNodes[0].textContent.toLowerCase();
        var secondName = second.getElementsByTagName('td')[0].childNodes[0].textContent.toLowerCase();
        var sortedNames = [firstName, secondName];
        sortedNames = sortedNames.sort();
        return (firstName == sortedNames[0] ? -1 : 1);
        break;
    case "time":
        // get the unixtimestamp from the classname (second part)
        var firstTimeAge = parseInt(first.getElementsByTagName('td')[1].className.split(' ')[1]);
        var secondTimeAge = parseInt(second.getElementsByTagName('td')[1].className.split(' ')[1]);
        if ( firstTimeAge == secondTimeAge ) {
	 return compareElements("name", first, second);
        } else {
	 return (firstTimeAge > secondTimeAge ? -1 : 1);
        }
        break;
    case "Britain":
        nationSortIndex = 2;
        break;
    case "Spain":
        nationSortIndex = 3;
        break;
    case "France":
        nationSortIndex = 4;
        break;
    case "Pirate":
        nationSortIndex = 5;
        break;
    case "1h":
        unrestPart = 1; // max of all unrest numbers, 1h part
        break;
    case "12h":
        unrestPart = 2; // max of all unrest numbers, 12h part
        break;
    }
    // sort by a nation
    if ( nationSortIndex != -1 ) {
        // for sorting by nation, the index of the splitted unrest string (normal number, -1h or -12h number)
        unrestPart = (type.split(' ').length > 1 ? type.split(' ')[1] : 0); // type will be of format 'Nation [1|2]' (optional digit, either 1 or 2).
        var firstValue = -1; // default values, combined with the if-statements give a good value
        var secondValue = -1;
        if ( first.getElementsByTagName('td')[nationSortIndex].innerHTML != '&nbsp;' ) {
	 firstValue = Math.abs(parseInt(first.getElementsByTagName('td')[nationSortIndex].textContent.replace(' ','').split(/[()\/]+/g)[unrestPart]));
        }
        if ( second.getElementsByTagName('td')[nationSortIndex].innerHTML != '&nbsp;' ) {
	 secondValue = Math.abs(parseInt(second.getElementsByTagName('td')[nationSortIndex].textContent.replace(' ','').split(/[()\/]+/g)[unrestPart]));
        }
        if ( firstValue == secondValue ) {
	 return compareElements("name", first, second); // fall back to sorting by town name
        } else {
	 return (firstValue < secondValue ? 1 : -1);
        }
    } else {
    // sort by max of all nations combine
        var firstValue = -1;
        var secondValue = -1;
        for ( var nationSortIndex = 2; nationSortIndex <= 5; nationSortIndex++ ) {
	 if ( first.getElementsByTagName('td')[nationSortIndex].innerHTML != '&nbsp;' ) {
	     firstValue = Math.max(firstValue, Math.abs(parseInt(first.getElementsByTagName('td')[nationSortIndex].textContent.replace(' ','').split(/[()\/]+/g)[unrestPart])));
	 }
	 if ( second.getElementsByTagName('td')[nationSortIndex].innerHTML != '&nbsp;' ) {
	     secondValue = Math.max(secondValue, Math.abs(parseInt(second.getElementsByTagName('td')[nationSortIndex].textContent.replace(' ','').split(/[()\/]+/g)[unrestPart])));
	 }
        }
        if ( firstValue == secondValue ) {
	 return compareElements("name", first, second); // fall back to sorting by town name
        } else {
	 return (firstValue < secondValue ? 1 : -1);
        }
    }
}

/***********************************************************************************/

// ----------------------------------------------------------------------------
// HasClassName
//
// Description : returns boolean indicating whether the object has the class name
//    built with the understanding that there may be multiple classes
//
// Arguments:
//    objElement              - element to manipulate
//    strClass                - class name to add
//
function HasClassName(objElement, strClass)
{

   // if there is a class
    if ( objElement.className )
    {

        // the classes are just a space separated list, so first get the list
        var arrList = objElement.className.split(' ');

      // get uppercase class for comparison purposes
        var strClassUpper = strClass.toUpperCase();

      // find all instances and remove them
        for ( var i = 0; i < arrList.length; i++ )
        {

         // if class found
	 if ( arrList[i].toUpperCase() == strClassUpper )
            {

            // we found it
                return true;

            }

        }

    }

   // if we got here then the class name is not there
    return false;

}
// 
// HasClassName
// ----------------------------------------------------------------------------


// ----------------------------------------------------------------------------
// AddClassName
//
// Description : adds a class to the class attribute of a DOM element
//    built with the understanding that there may be multiple classes
//
// Arguments:
//    objElement              - element to manipulate
//    strClass                - class name to add
//
function AddClassName(objElement, strClass, blnMayAlreadyExist)
{

   // if there is a class
    if ( objElement.className )
    {

        // the classes are just a space separated list, so first get the list
        var arrList = objElement.className.split(' ');

      // if the new class name may already exist in list
        if ( blnMayAlreadyExist )
        {

         // get uppercase class for comparison purposes
	 var strClassUpper = strClass.toUpperCase();

         // find all instances and remove them
	 for ( var i = 0; i < arrList.length; i++ )
            {

            // if class found
                if ( arrList[i].toUpperCase() == strClassUpper )
                {

               // remove array item
                    arrList.splice(i, 1);

               // decrement loop counter as we have adjusted the array's contents
                    i--;

                }

            }

        }

      // add the new class to end of list
        arrList[arrList.length] = strClass;

      // add the new class to beginning of list
        //arrList.splice(0, 0, strClass);
      
      // assign modified class name attribute
        objElement.className = arrList.join(' ');

    }
   // if there was no class
   else
    {

      // assign modified class name attribute      
        objElement.className = strClass;
   
    }

}
// 
// AddClassName
// ----------------------------------------------------------------------------


// ----------------------------------------------------------------------------
// RemoveClassName
//
// Description : removes a class from the class attribute of a DOM element
//    built with the understanding that there may be multiple classes
//
// Arguments:
//    objElement              - element to manipulate
//    strClass                - class name to remove
//
function RemoveClassName(objElement, strClass)
{
    var foundAndRemoved = false;
    // if there is a class
    if ( objElement.className )
    {

        // the classes are just a space separated list, so first get the list
        var arrList = objElement.className.split(' ');

      // get uppercase class for comparison purposes
        var strClassUpper = strClass.toUpperCase();

      // find all instances and remove them
        for ( var i = 0; i < arrList.length; i++ )
        {

         // if class found
	 if ( arrList[i].toUpperCase() == strClassUpper )
            {
	     foundAndRemoved = true;
            // remove array item
                arrList.splice(i, 1);

            // decrement loop counter as we have adjusted the array's contents
                i--;

            }

        }

      // assign modified class name attribute
        objElement.className = arrList.join(' ');

    }
   // if there was no class
   // there is nothing to remove
    return foundAndRemoved;
}
// 
// RemoveClassName
// ----------------------------------------------------------------------------

