// todo: when a table is sorted and not in order use disjoint entries
// rather than joint entries or disable the selecting or sort first
// before doing that.

// todo: add support for using ctrl key to select single rows and not
// a range.

// todo: hide partial rows when summing on a table with partial rows.

// The style for the selected area.
var bg_color  = "#def";
var bg_image  = "url(/images/aqua.png)";
var sum_span_url     = "/play-index/span_stats.cgi";

// spans_active is a global that stores the range of values currently selected.
var spans_active = new Array();
var PAGE_ID;

// a boolean that will tell us if there is a cookie set to disable
// span summing by default.
var COOKIE_HL_OFF = 0;

// get the tooltip ready to go and more.
function set_variables(page_id) {

    initTooltip();
    // Set our global var for the page_id
    PAGE_ID = page_id;
    PREVCLICKED = 0;

    $$('table.stats_table').each(function(s) { spans_active[s.id] = '0-0'; });
    var cookie_val = read_cookie('HLDEFAULT');

    
    
    if (cookie_val == 'ON') {
        default_span_on();
    }
    else if (cookie_val == 'OFF') {
        default_span_off();
    }
    highlight_span_from_url(PAGE_ID);
}


/////////////////////////////////////////////////////////////////
// This is called when a row is clicked on.
/////////////////////////////////////////////////////////////////
function sum_span(row_clicked) {
    var row_clicked_parts = row_clicked.id.split('.');
    var table_id = row_clicked_parts[0];
    var row_clicked_num = parseInt(row_clicked_parts[1]);
    
    var span_alert = document.getElementById(table_id +'_span_alert');

    // We have a checkbox, so use the status of the checkbox by
    // default.
    if (span_alert && document.forms[table_id + '_span_alert'].elements['cb']) {
	span_alert.style.backgroundColor = '#ffa';
        
        // If we have a checkbox that can be set to turn the summing
        // on and off, check it here.
        if (document.forms[table_id + '_span_alert'].elements['cb'] &&
             (document.forms[table_id + '_span_alert'].elements['cb'].checked == 0)) {
            return;
        }
    }
    // No checkbox, so use the cookie result.
    else if (COOKIE_HL_OFF) {
        return;
    }


    if (span_alert) {
	span_alert.style.backgroundColor = '#ffa';
    }
    
    // PREVCLICKED is set to one when a tooltip is fired.  This
    // prevents us from both running a career game or PA tooltip and
    // the sum_span tooltip at the same time.
    if (PREVCLICKED != 0) {
	PREVCLICKED = 0;
	return;
    }

    // spans_active gives us the current state of the highlighted
    // rows.
    var arr_rows = spans_active[table_id].split('-');
    arr_rows[0] = parseInt(arr_rows[0]);
    arr_rows[1] = parseInt(arr_rows[1]);

    // alert(table_id + ":" + row_clicked_num + ":" + arr_rows[0] + ":" + arr_rows[1]);
    
    // Store the existing highlighted range for later.
    var min_old = arr_rows[0];
    var max_old = arr_rows[1];

    // The number of endpoints clicked on.
    var endpoints_turned_off = 0;


    // user clicked on the first line which was already selected.
    if (row_clicked_num == arr_rows[0]) {
	endpoints_turned_off++;
        // Check to see if we have a singleto and arr_rows[1] ==
        // row_clicked as well.
	if (!arr_rows[1] || (row_clicked_num == arr_rows[1])) {
            // Set this to zero as we are going to de-select the
            // singleton.
	    arr_rows[0] = 0;
	}
	else {
            // They aren't the same, so we set the first row in the
            // range equal to the last row in the range and we go from
            // a range to a singleton.
	    arr_rows[0] = arr_rows[1];
	}
    }
    // Clicking on a row that is less than the range.  Set the
    // first row to the row_clicked.
    else if ((arr_rows[0] == 0) || (row_clicked_num < arr_rows[0])) {
	arr_rows[0] = row_clicked_num;
    }
    // Nothing was previously selected.
    else if ((arr_rows[0] == 0) && (arr_rows[1] == 0)) {
	arr_rows[0] = row_clicked_num;
    }
  
    // Clicking on the second line.
    if (row_clicked_num == arr_rows[1]) {
	endpoints_turned_off++;

        // Check to see if the first row exists or is equal to the row
        // we clicked.
        if (!arr_rows[0] || (row_clicked_num == arr_rows[0])) {
	    arr_rows[1] = 0;
	}
	else {
	    arr_rows[1] = arr_rows[0];
	}
    }
    // IF we've already turned off a row we do nothing, if a row
    // hasn't been turned off we then check to see if this new row is
    // greater than the existing range and reset the top of the range
    // if so.
    else if ((endpoints_turned_off == 0) &&
             ((arr_rows[1] == 0) ||
              (row_clicked_num > arr_rows[0]))) {
	arr_rows[1] = row_clicked_num;
    }

    // We clicked on a singleton, making us clear out the selection.
    if (endpoints_turned_off == 2) {
	color_span(table_id, 0, 0, min_old, max_old);
    }
    // We set a new range.
    else {        
	color_span(table_id, arr_rows[0], arr_rows[1], min_old, max_old);
    }

    // Set the new spans active.
    spans_active[table_id] = arr_rows[0] + '-' + arr_rows[1];

    // If there is a range of more than one row selected, we get the
    // value.
    if ((arr_rows[0] > 0) && (arr_rows[1] > 0) && (arr_rows[0] < arr_rows[1])) {
	get_span_stats(PAGE_ID, table_id, spans_active[table_id], 1, 0, row_clicked);
    }


}



// Set up the http request (a url and a set of params) that returns
// the full html page that will go into the tooltip and will show the
// summed values for the range selected.
function get_span_stats(page_id, table_id, range_of_values, include_permalink, include_rand, row_clicked) {

    // Find the min and max rows, so we know where to put the tooltip.
    var arr_range;
    if (range_of_values.indexOf('-') > 0) {
        arr_range = range_of_values.split('-');
    }
    else if (range_of_values.indexOf(',') > 0) {
        arr_range = range_of_values.split(',');
    }
    else {
        return;
    }
    var min_row = arr_range[0];
    var max_row = arr_range.pop();

    // try to put the tooltip after the max_row, if it doesn't exist
    // use the first row.
    if (row_clicked) {
        element_user_clicked = row_clicked;
    }
    else {
        element_user_clicked = document.getElementById(table_id + '.' + max_row);
    }

    if (!element_user_clicked) { 
	element_user_clicked = document.getElementById(table_id + '.' + min_row);
    }
    // If we still don't have an element use table_id
    if (!element_user_clicked) { 
        element_user_clicked = document.getElementById(table_id);
    }
    // Still nothing return without running sum_span_url.
    if (!element_user_clicked) { 
        return;
    }

    
    // This is a global variable used to set the location.
    elemCLICKED = element_user_clicked;
    var rand_param = "";
    if (include_rand) {
         rand_param =    "&rand=" +  Math.floor(Math.random()*10000);
    }

    var params  = "html=1&page_id=" + escape(page_id) + "&table_id=" + escape(table_id) + 
	"&range=" + escape(range_of_values) + "&plink=" + include_permalink + 
        rand_param;

    getTooltipData(sum_span_url, params);
}


function clear_span_selection(table_id) {
    clearTooltipData();
    var arr_rows = spans_active[table_id].split('-');

    spans_active[table_id] = '0-0';
    color_span(table_id, 0, 0, parseInt(arr_rows[0]), parseInt(arr_rows[1]));
}

// Color the range set out by the min_new and max_new values.  We may
// also have do uncolor the range of values in min_old and max_old.
function color_span(table_id, min_new, max_new, min_old, max_old) {
    // alert(table_id + ":" + min_new + ":" + max_new + ":" + min_old + ":" + max_old);
    min_new = parseInt(min_new);
    max_new = parseInt(max_new);
    min_old = parseInt(min_old);
    max_old = parseInt(max_old);

    // if min_new greater than max_new swap.
    if (min_new > max_new) {
	var tmp = min_new;
	min_new = max_new;
	max_new = tmp;
    }
    var row_of_span;
    var row_num;
    // We want to uncolor all of the rows previously colored.
    if ((min_new == 0) && (max_new == 0)) {
	for (row_num = min_old; row_num <= max_old; row_num++) {
            _uncolor_row(table_id, row_num);
	}
	return;
    }	

    // If min_old < min_new, uncolor all those from min_old up to
    // min_new
    if (min_old > 0) {
	for (row_num = min_old; row_num < min_new; row_num++) {
            _uncolor_row(table_id, row_num);
	}
    }	

    // Uncolor from max_new to max_old.
    if (max_old > 0) {
	for (row_num = max_new + 1; row_num <= max_old; row_num++) {
            _uncolor_row(table_id, row_num);
	}
    }	

    if (min_new > max_new) {
        // Shouldn't get here, but just in case do nothing.
        return;
    }
    else {
        // Color from min_new to max_new
	for (row_num = min_new; row_num <= max_new; row_num++) {
            _color_row(table_id, row_num);
	}
    }
}


function _uncolor_row(table_id, row_num)
{
    var row_of_span = document.getElementById(table_id + '.' + row_num);
    if (row_of_span) {
        row_of_span.style.backgroundColor = '';
        row_of_span.style.backgroundImage = '';
    }
}

function _color_row(table_id, row_num)
{
    var row_of_span = document.getElementById(table_id + '.' + row_num);
    if (row_of_span) {
        row_of_span.style.backgroundColor = bg_color;
        row_of_span.style.backgroundImage = bg_image;
    }
}

//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////


// Get the span set in the page url hash if one is found.  These have
// four forms min_row-max_row:table_id or min_row-max_row, or
// row_1,row_2,...,row_n:table_id  or row_1,row_2,...,row_n
function highlight_span_from_url(page_id) {
    // Read the page's hash looking for a thing to sum.
    var rows_highlight_from_hash = location.hash.slice(1);

    // Get the rows_highlighted and table id if given.
    var rows_highlighted = rows_highlight_from_hash.split(':')[0];
    var table_id         = rows_highlight_from_hash.split(':')[1];


    // if no table_id look up the first stats_table
    if (!table_id) {
        table_id = $$('table.stats_table')[0].id;
    }

    // Return with no action if no hash to highlight or no table_id.
    if ((rows_highlight_from_hash.length == 0) || (!table_id)) {
        return;
    }
    
    var arr_rows_joint   = rows_highlighted.split('-');
    var arr_rows_disjoint = rows_highlighted.split(',');


    // Only one entry.  Do nothing here.
    if ((arr_rows_joint.length <= 1) && (arr_rows_disjoint.length <= 1)) {
        _color_row(table_id,arr_rows_joint[0]);
        var focus_element = document.getElementById(table_id + '.' + arr_rows_joint[0]);
        // If we have a focus element, set the focus here.
        if (focus_element) {
            var arr_focus_loc = findPos(focus_element);
            // move the focus 100 pixels up and set the left value to
            // zero as we don't want to horizontal scroll.
            window.scrollTo(0,arr_focus_loc[1] - 100);
        }
        spans_active[table_id] = arr_rows_disjoint[0] + '-' + arr_rows_disjoint[0];


    }
    // We have a range of rows to highlight and sum.
    else if (arr_rows_joint.length > 1) {
        arr_rows_joint.sort(function(a,b)
                               {  if (a == 'sum') {
                                       return 999999999999;
                                   }
                                   else if (b == 'sum') {
                                       return -99999999999;
                                   }
                                   else {
                                       return a - b;
                                   }
                               });

        color_span(table_id, parseInt(arr_rows_joint[0]), parseInt(arr_rows_joint[1]), 0, 0);


        // Check to see if we have spans_active[table_id] defined.
        if (typeof(spans_active[table_id]) != "undefined") {
            spans_active[table_id] = arr_rows_joint[0] + '-' + arr_rows_joint[1];
        }
        // Span the rows if we are asked to do so.
        if (arr_rows_joint[2] == 'sum') {
            get_span_stats(page_id,table_id, spans_active[table_id], 0, 1);
        }
        else {
            // setting the tooltip makes certain the range is in view
            var focus_element = document.getElementById(table_id + '.' + arr_rows_joint[0]);
            // If the first does not exist on this page or we are doing a
            // sum, check on if the end of the range exists.
            if (!focus_element || (arr_rows_joint[2] == 'sum')) {
                var second_focus_element = document.getElementById(table_id + '.' + arr_rows_joint[1]);
                if (second_focus_element) {
                    focus_element = second_focus_element;
                }
            }
            
            // If we have a focus element, set the focus here.
            if (focus_element) {
                var arr_focus_loc = findPos(focus_element);
                // move the focus 100 pixels up and set the left value to
                // zero as we don't want to horizontal scroll.
                window.scrollTo(0,arr_focus_loc[1] - 100);
            }
        }

    }
    // We have a disjoint set of rows.
    else if (arr_rows_disjoint.length > 1) {
        var i;
        var last_row;
        var next_to_last_row;
        // sort the order of the disjoint elements, if there is a sum,
        // we want to make sure that is last in the array..
        arr_rows_disjoint.sort(function(a,b)
                               {  if (a == 'sum') {
                                       return 999999999999;
                                   }
                                   else if (b == 'sum') {
                                       return -99999999999;
                                   }
                                   else {
                                       return a - b;
                                   }
                               });

        // Color all of the rows in our set.
        for (i = 0; i < arr_rows_disjoint.length; i++) {
            _color_row(table_id, arr_rows_disjoint[i]);
            next_to_last_row = last_row;
            last_row = arr_rows_disjoint[i];
        }

        var do_sum = 0;
        if (last_row == 'sum') {
            arr_rows_disjoint.pop();
            do_sum = 1;
            last_row = next_to_last_row;
        }
        
	// If we want to sum run get_span_stats
        if (do_sum) {
            get_span_stats(page_id, table_id, arr_rows_disjoint.join(','), 0);
        }
        else {
            // Move the window to either the first or last element.  Use
            // the first by default.  
            var focus_element = document.getElementById(table_id + '.' + arr_rows_disjoint[0]);
            // If the first does not exist on this page or we are doing a
            // sum, check on if the end of the range exists.
            if (!focus_element || do_sum) {
                var second_focus_element = document.getElementById(table_id + '.' + last_row);
                if (second_focus_element) {
                    focus_element = second_focus_element;
                }
            }
            
            // If we have a focus element, set the focus here.
            if (focus_element) {
                var arr_focus_loc = findPos(focus_element);
                // move the focus 100 pixels up and set the left value to
                // zero as we don't want to horizontal scroll.
                window.scrollTo(0,arr_focus_loc[1] - 100);
            }
        }

        
        // Check to see if we have spans_active[table_id] defined.
        if (typeof(spans_active[table_id]) != "undefined") {
            spans_active[table_id] = arr_rows_disjoint[0] + '-' + last_row;
        }
        
    }
    return;
}



// http://www.quirksmode.org/js/cookies.html
function read_cookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
}

function default_span_on () {
    // set a cookie
    document.cookie = 'HLDEFAULT=ON; expires=Thu, 31 Dec 2013 23:59:59 UTC; path=/';

    COOKIE_HL_OFF = 0;
    // set the checkbox on.
    $$('table.stats_table').each(function(s) {
            if ((document.forms[s.id + '_span_alert']) &&
                (document.forms[s.id + '_span_alert'].elements['cb']) ) {
                document.forms[s.id + '_span_alert'].elements['cb'].checked = 1;
            }
        }
        );

    // change the style of the default_span_on span to black and change to 'IS ON'
    if ($('default_span_on')) {
        $('default_span_on').innerHTML = 'IS ON';
        $('default_span_on').className = 'black_text';
    }
    // change the style of the default_span_off back to the default (reset it's style and then it's class?)
    if ($('default_span_off')) {
        $('default_span_off').innerHTML = 'OFF';
        $('default_span_off').className = 'tooltip';
    }
}

function default_span_off () {
    // set a cookie
    document.cookie = 'HLDEFAULT=OFF; expires=Thu, 31 Dec 2013 23:59:59 UTC; path=/';
    COOKIE_HL_OFF = 1;

    // set the checkbox on.
    $$('table.stats_table').each(function(s) {
            if ((document.forms[s.id + '_span_alert']) &&
                (document.forms[s.id + '_span_alert'].elements['cb']) ) {
                document.forms[s.id + '_span_alert'].elements['cb'].checked = 0;
            }
        }
        );

    // change the style of the default_span_on span to black and change to 'IS ON'
    if ($('default_span_on')) {
        $('default_span_on').innerHTML = 'ON';
        $('default_span_on').className = 'tooltip';
    }	
    // change the style of the default_span_off back to the default (reset it's style and then it's class?)
    if ($('default_span_off')) {
        $('default_span_off').innerHTML = 'IS OFF';
        $('default_span_off').className = 'tooltipOff';
    }
}

