
window.addEvent('domready', main);

var visibleSelectBox = false;


function main ()
{
    if ($('searchWords') && !$('searchWords').get('disabled')) {
        $('searchWords').addEvent('keyup',searchEvent);
        $('searchWords').focus();
    }
	prepareTable();	
}

// Updates the datatable, fills it with correct data
function updateTable() {
    var req = new Request({
		method: 'get',
		url: 'ajax/datatable.php',
		data: {'page' : page, 'state' : getDataTableId()},
		onRequest: function() { },
		onComplete: function(response) {
		    getDataTable().innerHTML = response;
		    reload();
            prepareTable();
		}
	});

	req.send();
}


// Update either the map or the datatable, depending on which is currently shown
function update() {
    var buttonClass = ($("searchWords").value) ? "clearbutton" : "searchbutton";
    $("searchStatus").set("class",buttonClass);   
    switch(getDataTableMode())
    {
    default:
    case '0':
        //alert("!");
        updateTable();
        break;
    case '1':
        updateMap();
        break;
    }
}

// While loading, show it
function isLoading() {  
    $("searchStatus").set("class","loading");
}

// After the table has been reloaded by ajax, all js-code for the table need to be re-initized
function prepareTable()
{
    if (!$('datatable')) return;    // Not a datatable page, do nothing
    var buttonClass = ($("searchWords").value) ? "clearbutton" : "searchbutton";
    $("searchStatus").set("class",buttonClass);   
    mapTab = $("visible_on_map");
    if (mapTab && $("amount_visible_on_map"))
        mapTab.innerHTML = "<br />(" + $("amount_visible_on_map").value + ")";

    $$('.data_header').each(function(el,i){el.addEvent("click",function(){sortCol(i);})});
    if (getDataTableMode() == 0) initDatatableResize();    
    
    //initTooltip();
}

// After the map has been reloaded, prepare it
function prepareMap()
{
        var frame = window.frames.mapFrame;
        if (undefined == (frame)) return; 
        
        try {
            frame.clearMap(); 
            frame.plotActiveEntries();
        } catch (e) {
            // alert(e.toString());
        }
}

// Returns the internal code for the current datatable mode
function getDataTableMode()
{

        switch ($("datatableMode").value)
        {
            case "table":
                return '0';
                break;
            case "map":
                return '1';
                break;
            default:
                return '0';
        }
}

// Change page on the datatable
function page(page)
{
	var req = new Request({
		method: 'get', 
		url: 'ajax/update.php',
		data: {'page' : page, 'dt' : getDataTableId()}, 
		onRequest: function() {isLoading();}, 
		onComplete: function(response) {updateTable();}
	});
	
	req.send();
}

// Set the number of rows to be shown on the datatable
function setNumRows(nrRows)
{
	var req = new Request({
		method: 'get', 
		url: 'ajax/update.php',
		data: {'do' : 'setRows', 'rows' : nrRows, 'dt' : getDataTableId()}, 
		onRequest: function() {isLoading();}, 
		onComplete: function(response) {updateTable();}
	});
	
	req.send();
}

// Increase the number of rows to be shown on the datatable
function incrementRows(amount)
{
	var req = new Request({
		method: 'get', 
		url: 'ajax/update.php',
		data: {'do' : 'incrementRows', 'dt' : getDataTableId(), 'amount' : amount}, 
		onRequest: function() {isLoading();}, 
		onComplete: function(response) {
		    getDataTable().style.height = (parseInt(getDataTable().style.height) + 26 * amount) + "px";
		    updateTable();
		}
	});
	
	req.send();
}

// Order the gyms by the closest ones
function showClosest() {
    var req = new Request({
		method: 'get', 
		url: 'ajax/update.php',
		data: {'do' : 'showClosest', 'dt' : getDataTableId()}, 
		onRequest: function() {isLoading();}, 
		onComplete: function(response) {update();}
	});
	
	req.send();
}

// Show or hide a column
function showHideCols(colId)
{
	var req = new Request({
		method: 'get', 
		url: 'ajax/update.php',
		data: {'do' : 'showHideCol', 'col' : colId.toString(), 'dt' : getDataTableId()}, 
		onRequest: function() {isLoading();}, 
		onComplete: function(response) {update();}
	});
	req.send();
    var el = ($("showHideColField_"+colId.toString()));
    el.set('class',el.hasClass("visible") ? "hidden" : "visible");
	
}

// Get the element of the datatable
function getDataTable()
{
    return $('datatable');
}

// Gets the PHP id for the datatable
function getDataTableId()
{
    return $("dtId").value;
}

// Sort the datatable by a column
function sortCol(index, ascending)
{
    asc = 0; // if ascending is null or undefined
    if (ascending == true) asc = 1;
    if (ascending == false) asc = 2;
    
	var req = new Request({
		method: 'get', 
		url: 'ajax/update.php',
		data: {'do' : 'sort', 'col' : index.toString(), 'asc' : asc.toString(), 'dt' : getDataTableId()}, 
		onRequest: function() {isLoading();}, 
		onComplete: function(response) {update();}
	});
	
	req.send();
}


var searchTimer = null;
// Called when searching
function searchEvent (event)
{
    if (searchTimer != null) {clearTimeout(searchTimer);searchTimer = null;}
    searchTimer = setTimeout("searchRequest('"+this.value +"', '" + getDataTable() + "');",300);
    /*
    if (getDataTableMode() == '1') {    // If we are updating the map, set a timeout since this is slower
        if (searchTimer != null) {clearTimeout(searchTimer);searchTimer = null;}
        searchTimer = setTimeout("searchRequest('"+this.value +"', '" + getDataTable() + "');",300);
    } else {
	    searchRequest(this.value, getDataTable());
    }
    */
}

// Perform an actual search
function searchRequest (words, element)
{
	var req = new Request({
		method: 'get', 
		url: 'ajax/update.php',
		data: {'w' : words , 'dt' : getDataTableId(), 'mode' : getDataTableMode(), 'r' : Math.random()},
		onRequest: function() { isLoading(); }, 
		onComplete: function(response) {update();}
	});
	
	req.send();
}

// Reset the datatable
function clearDataTable()
{
    $('searchWords').value = "";
    searchRequest("", getDataTable());
    sortCol(1,true);
}

// Show the advanced controls
function toggleAdvanced()
{
    var newStyle = $("advancedMenu").getStyle('display') == 'none' ? 'block' : 'none';
    $("advancedMenu").setStyle('display', newStyle);
}

// Filter the data by some column
function filterSelection(el)
{
    var colId = (el.name.substring(6));
    var req = new Request({	
		method: 'get',
		url: 'ajax/update.php',
		data: {'do' : 'filter', 'col' : colId, 'dt' : getDataTableId()},
		onRequest: function() {isLoading();},
		onComplete: function(response) {update();}
	});

	req.send();
}

// Manually update the position
function manuallyUpdatePosition()
{
    var req = new Request({
		method: 'get',
		url: 'ajax/update.php',
		data: {'do' : 'updatePosition', 'position' : $("changePosition").value, 'dt' : getDataTableId()},
		onRequest: function() {isLoading();},
		onComplete: function(response) {update();}
	});
	req.send();
}

// Filter the selection by a country
function filterCountry(countryCode)
{
    var req = new Request({
		method: 'get',
		url: 'ajax/update.php',
		data: {'do' : 'filterCountry', 'country' : countryCode, 'dt' : getDataTableId()},
		onRequest: function() {isLoading();},
		onComplete: function(response) {update();}
	});

	req.send();
}

// Show or hide the control which is used to filter by countries
function showHideFilterCountries() {
    disp = $("countryList").style.display;
    disp = (disp == "block") ? "none" : "block";
    $("countryList").style.display = disp;
}

