var currentSelectedRow_meid = 0;

/***********************************
 * INIT STUFF
 ***********************************/


// Preload the loading img
if (document.images) {
   loadingImg = new Image();
   loadingImg.src = "./img/Loading.gif";
}

var globalSortBy = getVar('sortBy');
var category = getVar('category');

if( globalSortBy.length == 0)
  globalSortBy = 'Pos';
if( category.length == 0)
  category = 'Politici';


// for overlib

ol_fgcolor = '#ffffff';
ol_bgcolor = '#000000';

/***********************************
 * HEADLINES & CHARTS
 ***********************************/

// updates chartDiv and headlinesDiv
function updateDivs( meid ) {
	// chart (yep, just updating an img tag)
	var chartDiv = document.getElementById( 'chartDiv' );
  if( chartDiv != null ) {
		if( chartUrls[ meid ] != null ) {
			chartDiv.innerHTML = '<img src="' + chartUrls[ meid ] + '">';
		}
	}

	// everything else is about headlines
	var headlinesDiv = document.getElementById( 'headlinesDiv' );
	if( headlinesDiv == null ) {
		return;
	}

	if( meid == currentSelectedRow_meid ) return;

  var headlinesHtml = '<table width="100%">';
  var headlineClusters = headlines[ meid ];

  if( headlineClusters && headlineClusters.length > 0 ) {
    for( iCluster=0; iCluster<headlineClusters.length; iCluster++ ) {
			var headline = headlineClusters[iCluster][0][1];

      headlinesHtml += '<tr class="headlineRow">';
			headlinesHtml += '<td>'
				+ '<a href="' + headlineClusters[iCluster][0][2] + '" target="_blank"';

			if( headline && headline.length > 100 ) {
				headlinesHtml += 'alt="' + headline + '"';
				headline = headline.substr(0,97) + '...';
			}

      headlinesHtml += '><span class="headlineSpan">' + headline
					+ '</span>'
					+ '</a>\n<br><span class="headlinedateSpan">'
					+ headlineClusters[iCluster][0][0]
					+ '</span>';


			if( headlineClusters[iCluster].length > 1 ) {
				headlinesHtml += ' - <a onmouseover=\'return headlineClusterOverlib( '
						+ meid + ', ' + iCluster + ' )\''
					  + ' onmouseout="return nd();" style="cursor:pointer" href="JavaScript:var x=42;">'
						+ headlineClusters[iCluster].length;
				
				headlinesHtml += ' bronnen';
				headlinesHtml += '</a>'
			}

			headlinesHtml += '<br><br>';
			headlinesHtml += '</td>';
			headlinesHtml += '<td align="center">';
			if( headlineClusters[iCluster][0].length > 3 ) {
        headlinesHtml += ' <img src ="./img/logo/small/' + headlineClusters[iCluster][0][3]
                         + '.png" border="0"> ';
      }
			headlinesHtml += '</tr></a>';
			if( iCluster >= 5 ) {
				break;
			}
			
    }
  }
  else {
    headlinesHtml = 'geen Headlines beschikbaar\n';
  }

	headlinesHtml += '</table>\n\n';

	//alert( 'Changing headlinesDiv' );

  headlinesDiv.innerHTML = headlinesHtml;
}

function headlineClusterOverlib( meid, iCluster ) {
		//alert( 'clusterOverlib' );
		var headlineClusters = headlines[ meid ];
		var maxWidth = 0;
		var popupHtml = '<center>\n';

    var clusterSize = headlineClusters[iCluster].length;
		if( clusterSize > 20 ) {
			clusterSize = 20;
		}
		for( iHeadline=0; iHeadline < clusterSize; iHeadline++ ) {
				var image = new Image();
				image.src = "./img/logo/small/" + headlineClusters[iCluster][iHeadline][3] + '.png';
				if( image.width > maxWidth ) {
						maxWidth = image.width;
				}
				popupHtml += '<a href="' + headlineClusters[iCluster][iHeadline][2]
					+ '" target="_blank">'
					+ '<img src='
					+ image.src
					+ ' title=\'' + headlineClusters[iCluster][iHeadline][1] + '\''
					+ ' border=0 style="margin:1px 1px 1px 1px" '
					// maybe later something like this
					// "swelling" images onMouseOver
					//+ ' height=' + (image.height / 1.2 )
					//+ ' onmouseover="this.height = 1.2 * this.height" '
					//+ ' onmouseout="this.height = this.height / 1.2" '
					+ '></a> ';
		}
		popupHtml += '</center>\n';
		
    return overlib( popupHtml,
										STICKY,
										MOUSEOFF,
										DELAY, 250,
										RIGHT,
                    VAUTO,
										OFFSETX, -3,
										OFFSETY, -3,
										BORDER, 1,
										WIDTH, 100 + 7 * clusterSize
									);
}

function updateSelectedHeadlines() {
  //var selectedId = getSelectedId();
  //alert( 'entering updateSelectedHeadlines()' );
  //if( selectedId != null ) {
	if( currentSelectedRow_meid ) {
		//alert( 'actually doing it for id = ' + selectedId );
    //updateHeadlines( selectedId );
		updateDivs( currentSelectedRow_meid );
  }
}

function toggleSelected( rowToSelect, meid ) {
  // selectedRow = document.getElementById( getSelectedId() );

  // Column with the position
  var positionCol = document.getElementById( 'positionCol_' + meid );
  //alert('Updating positionCol_' + meid + ': ' + positionCol);

  // alert('Updating positionCol_' + meid + ': ' + positionCol + ' innerHTML: ' + document.getElementById('row' + meid).innerHTML);

  // Colums with the name
  var nameCol = document.getElementById( 'nameCol_' + meid );
  //alert('Updating nameCol_' + meid + ': ' + nameCol);

  // Column with bars
  var barsCol = document.getElementById( 'barsCol_' + meid );

  // If there is a row selected already
  if( currentSelectedRow_meid ) {
		var currentPositionCol =
			document.getElementById('positionCol_' + currentSelectedRow_meid);

		// deselect the formerly selected row
		if( currentPositionCol.className == 'resultColPosRiser_selected')
			currentPositionCol.className = 'resultColPosRiser';
		else if(currentPositionCol.className == 'resultColPosDropper_selected')
			currentPositionCol.className = 'resultColPosDropper';
		else
			currentPositionCol.className = 'resultColPos';

		document.getElementById('nameCol_' + currentSelectedRow_meid).className
			= 'resultNameCol';
		var currentBarsCol =
			document.getElementById('barsCol_' + currentSelectedRow_meid);
		if( currentBarsCol ) currentBarsCol.className = 'resultBarsCol';

    // if this is the row that is clicked on, we are ready
    if( currentSelectedRow_meid == meid ) {
      currentSelectedRow_meid = 0; // Switch off
      return;
    }
  }

  // Select new row
	if( positionCol.className == "resultColPosRiser_hover")
		positionCol.className = 'resultColPosRiser_selected';
	else if(positionCol.className == 'resultColPosDropper_hover')
		positionCol.className = 'resultColPosDropper_selected';
	else
		positionCol.className = 'resultColPos_selected';

  nameCol.className = 'resultNameCol_selected';
  if( barsCol ) barsCol.className = 'resultBarsCol_selected';

	updateDivs( meid );

  currentSelectedRow_meid = meid;
}

function resultRowHover( row, meid ) {
	if( bHoverable != 'On' ) {
		return;
	}

	row.style.cursor='pointer';

	//alert( row.innerHTML );

	// Highlight, unless this row was selected
	if( currentSelectedRow_meid != meid) {
		// Do it for the entire row
		// row.className = 'resultRow_hover';

		// Do the first column separately
		var positionCol = document.getElementById('positionCol_' + meid);

		if( positionCol.className == "resultColPosRiser" )
			positionCol.className = 'resultColPosRiser_hover';
		else if( positionCol.className == 'resultColPosDropper' )
			positionCol.className = 'resultColPosDropper_hover';
		else
			positionCol.className = 'resultColPos_hover';

		document.getElementById('nameCol_' + meid).className = 'resultNameCol_hover';
		var barsCol = document.getElementById('barsCol_' + meid);
		if( barsCol ) barsCol.className = 'resultBarsCol_hover';

		// Only update if there wasn't another row selected, in which case
		// highlighting can occur all the same
		if( ! currentSelectedRow_meid)
			updateDivs( meid );
	}
}

function resultRowClick( row, meid ) {
	if( bHoverable != 'On' ) {
		return;
	}
	toggleSelected( row, meid );
}

function resultRowLeave( row, meid ) {
	if( bHoverable != 'On' ) {
		return;
	}
	row.style.cursor='';

	// Un-highlight, unless the row was selected
  if( currentSelectedRow_meid != meid ) {
		// Do the first column separately
		var positionCol = document.getElementById('positionCol_' + meid);

		if( positionCol.className == "resultColPosRiser_hover")
			positionCol.className = 'resultColPosRiser';
		else if(positionCol.className == 'resultColPosDropper_hover')
			positionCol.className = 'resultColPosDropper';
		else if(positionCol.className == 'resultColPos_hover')
			positionCol.className = 'resultColPos';

		document.getElementById('nameCol_' + meid).className = 'resultNameCol';
		var barsCol = document.getElementById('barsCol_' + meid);
		if( barsCol ) barsCol.className = 'resultBarsCol';
	}
}

function isHeadlinesOn() {
  var headlinesDiv = document.getElementById( 'headlines' );
  if( headlinesDiv == null ) {
    // Apparently, bHeadlines = Off
    return false;
  }
	return true;
}

function getVar(name) {
	get_string = document.location.search;
	return_value = '';

	do { //This loop is made to catch all instances of any get variable.
				 name_index = get_string.indexOf(name + '=');

    if (name_index != -1) {
		  get_string = get_string.substr(name_index + name.length + 1,
			 							   							 get_string.length - name_index);
			
			end_of_value = get_string.indexOf('&');
			if (end_of_value != -1)
				value = get_string.substr(0, end_of_value);
			else
				value = get_string;
			if (return_value == '' || value == '')
				return_value += value;
			else
				return_value += ', ' + value;
		}
	}
	while (name_index != -1)
		//Restores all the blank spaces.
		space = return_value.indexOf('+');
	while (space != -1) { 
		return_value = return_value.substr(0, space) + ' ' + 
			return_value.substr(space + 1, return_value.length);
		space = return_value.indexOf('+');
	}
	
	return(return_value);
}

//// AJAX code

// Code van http://www.w3schools.com/ajax/ajax_browsers.asp
function getXMLHtppRequestObject() {
		var xmlHttp;
		try
    {
				// Firefox, Opera 8.0+, Safari
				xmlHttp=new XMLHttpRequest();
    }
		catch (e)
    {
				// Internet Explorer
				try
				{
						xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
				}
				catch (e)
				{
						try
						{
								xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
						}
						catch (e)
						{
								alert("Your browser does not support AJAX!");
								return false;
						}
				}
    }
		return xmlHttp;
}


function fillChart(category, sortBy) {
  //alert("category: " + category + ", sortBy: " + sortBy);
	var obj = document.getElementById('chart');


  obj.innerHTML = "<img src='./chart.cgi?iCategory=" + category + "&sSortBy=" + sortBy + "'>";
/*
	var xmlHttp = getXMLHtppRequestObject();

	xmlHttp.onreadystatechange = function() {
		if(xmlHttp.readyState == 0) {
       obj.innerHTML = "The request is not initialized";
		}
		if(xmlHttp.readyState == 1) {
       // Laat plaatje zien terwijl de data wordt opgehaald
       // (is vantevoren al geladen, zodat dit (hopelijk) snel gaat)
			obj.innerHTML =	"<p>&nbsp;<p><img src='./img/Loading.gif'>";
		}
		if( xmlHttp.readyState == 2) {
			obj.innerHTML = "The request has been sent";
		}
		if( xmlHttp.readyState == 3) {
			obj.innerHTML = "The request is in process";
		}
		if(xmlHttp.readyState == 4)	{
			obj.innerHTML =	xmlHttp.responseText;
		}
	}

	xmlHttp.open("GET", "chart.cgi?sCategory=" + category + "&sSortBy=" + sortBy, true);
  // Die null is ook echt essentieel voor Firefox, die anders blijft hangen...
	xmlHttp.send(null);
*/
}


//// End AJAX code

