///////////////////////////////////////////////////////////////////
/* 				 CREATED BY JONATHAN COUSINS, 2009               */
///////////////////////////////////////////////////////////////////



//////////////////////////////////////////////////
/* 				 GLOBAL VARS			 	    */
//////////////////////////////////////////////////

var browser = navigator.appName;
var vendor = navigator.vendor;
var currentSelectedDataElementRef = null;
var currentFilterID = null;
var currentFilterCategory = null;
var orb = null; //SWF
var userNXY = new Array();
var friendsDisplayed = false;
var mID = null;


var url = "/data/users_summary.json";
var lastUrl = "";
var urlCommonValues = "";
var url2ColumnVoteBreakdown = new Array("/data/users_summary.json?vote[vote_topic_id]=", "&vote[value]=");
var urlCategoryFilter = new Array("/data/tile?demographics[category]=", "&demographics[value]=");
var urlCommonValuesSelectionFiltered = new Array("/data/common_values.json?demographics[category]=", "&demographics[value]=");
var urlDataParams = null;
var urlLassoParams = null;
var urlSpecificVoteParams = null;
var curSingleVoteTopicId = null;
var curStatement = null;
var curSelectedColumnID = null;
var curSelectedRowID = null;


var json = {};
var celebSocRecentJson = {};
var voteSpecificJson = {};
var nameColumnTEMPLATE = new Template('<td id=\"#{cellid}\" valign=\"bottom\" class=\"entityItemColumnName\">#{columnPoperty}</td>');	
var columnTEMPLATE = new Template('<td id=\"#{cellid}\" valign=\"bottom\" class=\"entityItemColumn\">#{columnPoperty}</td>');	
var columnTEMPLATE_EMPTY = new Template('<td id=\"#{cellid}\" valign=\"bottom\" class=\"entityItemColumnNOLINK\">#{columnPoperty}</td>');	
var topics = new Array("total_respondents", "work_statuses", "countries", "religious_affiliations", "age_ranges", "family_statuses", "household_incomes", "education_levels", "political_affiliations", "genders", "ethnicities");	
var currentSelectedRow = null;
var updateCommonAlert = false;
var updateDataAlert = false;

var celebFriendListOpen = false;	
var colorLegendOpen = false;
	
//////////////////////////////////////////////////////////////////////////
/* 					 SET UP:  GENERAL + EVENT HANDLING			 	    */
//////////////////////////////////////////////////////////////////////////

Event.observe(window, 'load', function() {
									   
	$('selectOption').selected = "selected";								   
    $('calculatingMsg').setOpacity(0.9);
	orb = window.document['vvo_001'];	
	getMID();
	if(handleVoteSpecificUri()) {
    } else {
	  getBasicData(url);
	  getUserlocation();
	  //getFriends();
	}             
	getCelebrityData();
	// TU zakomentowalem $('showCelebAndFriendSelector').setStyle({ display: 'inline'});
});

function refresh() {
	window.location.reload(true);
}

function iFrameToggle(dir){
	if(dir.toLowerCase() == "up"){
		$('id_frame').setStyle({ position: 'absolute', top: '0px', left: '0px', zIndex: '100', height:'280px', maxHeight:'280px', minHeight:'280px' });

	}else if(dir.toLowerCase() == "down"){
		$('id_frame').setStyle({ position: 'absolute', top: '0px', left: '0px', zIndex: '1', height:'180px', maxHeight:'180px', minHeight:'180px' });
	}
}

function handleVoteSpecificUri() {
  var _topic_id = window.location.href.match(/vote_topic_id=(\d+)/);
  if(_topic_id) {
    var topic_id = _topic_id[1];	
    var _option_id = window.location.href.match(/vote_option_id=(\d+)/);
    if(_option_id) {
      var option_id = _option_id[1];
    
      new Ajax.Request('/data/vote_topic_details/'+topic_id+'.json?vote_option_id='+option_id, {
        method: 'get',
        onSuccess: function(transport) {
          var json = transport.responseText.evalJSON(true);
          var vote_topic = json['vote_topic']['vote_topic'];
          var vote_option = json['vote_option']['vote_option'];
          var statement = json['statement'];
      
          examineCommonValue(vote_topic['id'], vote_option['id'], statement);
        }
      });
      return true;
    } else {
      new Ajax.Request('/data/vote_topic_details/'+topic_id+'.json', {
        method: 'get',
        onSuccess: function(transport) {
          var json = transport.responseText.evalJSON(true);
          var vote_topic = json['vote_topic']['vote_topic'];
          var vote_option = json['vote_option']['vote_option'];
          var statement = json['statement'];
      
          examineCommonValue(vote_topic['id'], vote_option['id'], statement);
        }
      });
      return true;
		}
  } 
  return false;
}

function userIsLoggedIn(){
	if(mID == null){
		return 0;
	}else{
		return 1;	
	}
}
function getMID(){
	var jsonMID = {};
	var userUrl = "/data/users/me.json";
	new Ajax.Request(userUrl, {
	  method:'get',
	  onSuccess: function(transport){	  	
		  jsonMID = transport.responseText.evalJSON(true);
		  if(jsonMID != null){
		  	mID = jsonMID['user']['id'];
			$('showMe').setStyle({ display: 'inline'});
			$('showAllFriends').setStyle({ display: 'inline'});
		  }
		 }
	  }
   );
}

function setUpTab(tabNum){
	var tab = $('orbSection').getElementsByClassName('tabs')[0].descendants()[tabNum]; 
	Event.observe(tab, 'click', 
		function(event) {
			if(this.hasClassName('dataTypeTab')){
		   		this.addClassName('dataTypeTabSelected');
				this.removeClassName('dataTypeTab');
				if(this.nextSiblings()[0]){
					this.nextSiblings()[0].addClassName('dataTypeTab');
					this.nextSiblings()[0].removeClassName('dataTypeTabSelected');
					$('demographicDataColumn').toggle();
					$('socialDataColumn').toggle();
				} else 	if(this.previousSiblings()[0]){
					this.previousSiblings()[0].addClassName('dataTypeTab');
					this.previousSiblings()[0].removeClassName('dataTypeTabSelected');
					$('demographicDataColumn').toggle();
					$('socialDataColumn').toggle();					
				}				
			}
		}
	);	
}

function setBrowserSpecificStyles(){
	if(browser == "Netscape" && vendor != "Apple Computer, Inc."){
		for(var i = 0; i < $('orbSection').getElementsByClassName('plusMinusBtnOpen').length; i++){
			$('orbSection').getElementsByClassName('plusMinusBtnOpen')[i].setStyle({ marginTop: '-16px'});
		}
		for(var i = 0; i < $('orbSection').getElementsByClassName('plusMinusBtnClosed').length; i++){
			$('orbSection').getElementsByClassName('plusMinusBtnClosed')[i].setStyle({ marginTop: '-16px'});
		}
	}
}

function activateDataboxItem(sectionElem){
	var sElem = sectionElem;
	for(var i = 0; i < $('dataBox').getElementsByClassName('infoColumnEntity').length; i++){	
		if($('dataBox').getElementsByClassName('infoColumnEntity')[i].getStyle('display') == 'block'){
			Effect.DropOut($('dataBox').getElementsByClassName('infoColumnEntity')[i]);
		}
	}
	sectionElem.up().appear({ duration:.5,
		afterFinish : function(){	
			addRemoveHandlers(sElem);
		}
	});
	sectionElem.up(2).setStyle({ backgroundColor: '#dd0000' });
	sectionElem.up(2).morph("background-color:#ffffff;", { duration:0.5 });	
}

function addRemoveHandlers(sectionElem){
	setHandlers(sectionElem.nextSiblings()[0]);
}


function reSetCurrentHandler(){
	for(var i = 0; i < $('orbSection').getElementsByClassName('infoColumnEntity').length; i++){
		var tmpElem = $('orbSection').getElementsByClassName('infoColumnEntity')[i];
		if(tmpElem.getStyle('display') == 'block' && tmpElem.id != 'total_respondents'){
			addRemoveHandlers(tmpElem.down());
		}
	}
}


function setHandlers(sectionElem){
	var entityTableDiv = sectionElem;
	if(sectionElem.up().getStyle('display') == 'block'){ // => inactive to active in data/filter box
		for(var i = 0; i < entityTableDiv.getElementsByClassName('entityItemRow').length; i++){
			if(urlSpecificVoteParams != null){
				for(var j = 0; j < entityTableDiv.getElementsByClassName('entityItemRow')[i].childElements().length; j++){
					if(entityTableDiv.getElementsByClassName('entityItemRow')[i].childElements()[j].id != 'Data_Entity'){
						var cName = entityTableDiv.getElementsByClassName('entityItemRow')[i].childElements()[j].className;
						if(cName == 'entityItemColumnName' || cName == 'entityItemColumn' || cName == 'entityItemColumn entityItemTopRowCol'){					
							valueNum = 0;
							Event.observe(entityTableDiv.getElementsByClassName('entityItemRow')[i].childElements()[j], 'click', 	
							   function(event) {
									if(sectionElem.up().id == 'celebrities' || sectionElem.up().id == 'friends'){	
										var turnMeOn = orb.showHideSelectedVoter(this.id);
										if(turnMeOn){
											var clr = orb.selectedVoterColor(entityTableDiv.getElementsByClassName('entityItemRow')[i].id);
											clr = "#"+clr;
											entityTableDiv.getElementsByClassName('entityItemRow')[i].setStyle({ backgroundColor: clr, color: '#ffffff'});							
										}else{
											entityTableDiv.getElementsByClassName('entityItemRow')[i].setStyle({ backgroundColor: '#ffffff', color: '#000000'});
										}
									}else{
										selectColumn(this, sectionElem.ancestors()[0].id, this.id);
									}				
								}
							);		
						}
					}
				}
			}else{
				if(entityTableDiv.getElementsByClassName('entityItemRow')[i].down().id != 'Data_Entity'){
					Event.observe(entityTableDiv.getElementsByClassName('entityItemRow')[i], 'click', 
					   function(event) {
							if(sectionElem.up().id == 'celebrities' || sectionElem.up().id == 'friends'){	
								var turnMeOn = orb.showHideSelectedVoter(this.id);
								if(turnMeOn){
									var clr = orb.selectedVoterColor(this.id);
									clr = "#"+clr;
									this.setStyle({ backgroundColor: clr, color: '#ffffff'});							
								}else{
									this.setStyle({ backgroundColor: '#ffffff', color: '#000000'});
								}
							}else{
								selectingRow(this, sectionElem.ancestors()[0].id, this.id);
							}				
						}
					);	
				}
			}
		}
		sectionElem.setStyle({ borderBottom:'dotted 1px #ffffff'});				
	} else if(sectionElem.up().getStyle('display') == 'none'){ // => active to inactive in data/filter box
		for(var i = 1; i < entityTableDiv.getElementsByClassName('entityItemRow').length; i++){				
			$(entityTableDiv.getElementsByClassName('entityItemRow')[i]).stopObserving();
			if(urlSpecificVoteParams != null){
				for(var i = 1; i < entityTableDiv.getElementsByClassName('entityItemRow').childElements().length; i++){				
				//	$(entityTableDiv.getElementsByClassName('entityItemRow')[i].childElements()[j]).stopObserving();
				}
			}
		}
		sectionElem.setStyle({ borderBottom:'dotted 1px #dd0000', color: '#000000'});						
	}
}


////////////////////////////////////////////////////////////////////////////////////////////////////
/* 							CELEBS AND FRIENDS LIST AND FUNCTIONALITY					    	  */
////////////////////////////////////////////////////////////////////////////////////////////////////

	var celebrityList_TEMPLATE = new Template('<div onclick=\"showHIdeCelebrity(this, #{xLoc}, #{yLoc}, \'#{celebName}\');\" id=\"#{userID}\" class=\"celebFriendListRow\">#{celebName}</div>');		
	
	var jsonResult = '{"celebrities": [{"user": {"x": 8.08827, "y": -15.1348, "username": "wendell@meetro.com", "id": 3}}, {"user": {"x": -33.6969, "y": 194.141, "username": "eli.halliwell@gmail.com", "id": 37}}, {"user": {"x": 15.4359, "y": -111.637, "username": "jnsears@jamesnsears.com", "id": 75}}]}';		
	
	function getCelebrityData(){	
		var thisUrl = "/data/celebrities.json";
		new Ajax.Request(thisUrl, {
		  method:'get',
		  onSuccess: function(transport){	  	
		 	  	jsonResult = transport.responseText.evalJSON(true);
				var accumDivRows = "<div style=\"font-weight:bold; font-size:12px; padding-bottom:5px; color:#dd0000; margin:10px 0px 10px 5px; border-bottom: dotted 1px #cccccc;\">Celebrities</div>";
				for(var i = 0; i < jsonResult.celebrities.length; i++){
					var thisUser = jsonResult.celebrities[i].user;
					accumDivRows += celebrityList_TEMPLATE.evaluate({userID: '_'+thisUser.id, celebName: thisUser.username, xLoc: thisUser.x, yLoc: thisUser.y});
				}
				$('people').innerHTML = accumDivRows;
				getFriendsDataForList(); // augment list with friends as well
		  	}
		});
	}
	function getFriendsDataForList(){
		var jsonFriends = {};
		var userUrl = "/data/friends.json";
			new Ajax.Request(userUrl, {
			  method:'get',
			  onSuccess: function(transport){	  
					var accumDivRows = "<div style=\"font-weight:bold; color:#dd0000;font-size:12px; padding-bottom:5px; margin: 10px 0px 10px 5px; border-bottom: dotted 1px #cccccc;\">Friends</div>";
				  	jsonFriends = transport.responseText.evalJSON(true);
				  	var friends = jsonFriends['friends'];
					
			  	  	for(var i = 0; i < friends.length; i++){
						var f = friends[i]['user']; 
						accumDivRows += celebrityList_TEMPLATE.evaluate({userID: f['id'], celebName: f['username'], xLoc: f['x'], yLoc: f['y']});					 
		  		  	}
					if(friends.length == 0){ accumDivRows += '<div style=\"font-size:10px; color:#666666; margin-left:16px;\">no friends linked at this time</div>'; }
					$('people').innerHTML += accumDivRows;
	  			}
	  		}
   		);
	}
	function showHIdeCelebrity(elem, xLoc, yLoc, celebName){
		var element = $(elem.id);
		if(element.hasClassName('celebFriendListRow')){
			element.addClassName('celebFriendListRowSelected');
			element.removeClassName('celebFriendListRow');
			orb.createIndependentVoterObjs(elem.id, celebName, null, "#222222", new Array(0,0,0), new Array(xLoc,yLoc,0));			
		}else if(element.hasClassName('celebFriendListRowSelected')){
			element.addClassName('celebFriendListRow');
			element.removeClassName('celebFriendListRowSelected');
			orb.createIndependentVoterObjs(elem.id, celebName, null, "#222222", new Array(0,0,0), new Array(xLoc,yLoc,0));			
		}
	}
	var blindInProcess = false;
	/*
	function seeCelebList(){
		if(!blindInProcess){
			blindInProcess = true;
			if($('people').style.display == "none"){
				celebFriendListOpen = true;
				Effect.BlindDown($('people'), {duration: 0.4, afterFinish: function(){ blindInProcess = false; }});
				if(colorLegendOpen){
					colorLegendOpen = false;
					Effect.BlindUp($('colorLegendPanel'), {duration: 0.4, afterFinish: function(){ blindInProcess = false; }}); 
					$('showColorLegendBtn').show();
					$('colorLegendArrow').src = "down.png";
				}		
			}else{
				celebFriendListOpen = false;
				Effect.BlindUp($('people'), {duration: 0.4, afterFinish: function(){ blindInProcess = false; }});				
			}
		}
	}
	function openCloseColorLegend(){
		if(!blindInProcess){
			blindInProcess = true;
			if(colorLegendOpen){
				colorLegendOpen = false;
				Effect.BlindUp($('colorLegendPanel'), {duration: 0.4, afterFinish: function(){ blindInProcess = false; }});; 
				$('showColorLegendBtn').show();
				$('colorLegendArrow').src = "down.png";
			}else{
				colorLegendOpen = true;
				Effect.BlindDown($('colorLegendPanel'), {duration: 0.4, afterFinish: function(){ blindInProcess = false; }}); 
				if(celebFriendListOpen){
					celebFriendListOpen = false;
					Effect.BlindUp($('people'), {duration: 0.4, afterFinish: function(){ blindInProcess = false; }});		
				}
				$('colorLegendArrow').src = "up.png";			
			}
		}
	}
*/
//colorLegendArrow

////////////////////////////////////////////////////////////////////////////////////////////////////
/* 											DATA ACQUISITION					    			  */
////////////////////////////////////////////////////////////////////////////////////////////////////

function urlGenerator(baseUrl){
	var thisUrl = baseUrl;
	if(urlDataParams != null || urlLassoParams != null || urlSpecificVoteParams != null){ // if there are ANY params, add a ?
		thisUrl += "?";
	}	
	thisUrl += (urlDataParams != null) ? urlDataParams : ""; // if there are demo/data params, add them
	thisUrl += (urlDataParams != null && urlSpecificVoteParams != null) ? "&" : ""; // if they have both demo AND single vote 
	thisUrl += (urlSpecificVoteParams != null) ? urlSpecificVoteParams : ""; // if this is a look at a single vote, add those params	
	if(urlLassoParams != null){// && baseUrl != '/data/tile'){ 
		if(urlDataParams != null || urlSpecificVoteParams != null){ 
			thisUrl += "&" + urlLassoParams;
		}else{
			thisUrl += urlLassoParams;
		}
	}	
	lastUrl = thisUrl;
	return thisUrl;
}

function getBasicData(incomingUrl){	
	var thisUrl = urlGenerator(incomingUrl);
	new Ajax.Request(thisUrl, {
	  method:'get',
	  onSuccess: function(transport){	  	
	 	  json = transport.responseText.evalJSON(true);
		  drawDatabox();
		  setImageTile();
		  // getDataAboutIndividuals("celebrities");
		  // getDataAboutIndividuals("friends"); 
	  	}
	  }
   );
}

function hideUserlocation(){
	orb.hideHighlight();
	$('showMe').show();
	$('hideMe').hide();	
}

function getUserlocation(){
	//hideHighlight getHidelocation
	$('showMe').hide();
	$('hideMe').show();
	var thisUserID = mID; // eli's user number for the time being
	var jsonForuserNXY = {};
	var userUrl = "/data/users/me.json";
	new Ajax.Request(userUrl, {
	  method:'get',
	  onSuccess: function(transport){	  	
		  jsonForuserNXY = transport.responseText.evalJSON(true);
		  userNXY['username'] = jsonForuserNXY['user']['username'];
		  userNXY['x'] = jsonForuserNXY['user']['x'];
		  userNXY['y'] = jsonForuserNXY['user']['y'];
		  //userNXY['username']
		  orb.showUser(userNXY['username'], userNXY['x'], userNXY['y']);

	  	}
	  }
   );
}

function hideFriends(){
	if(friendsDisplayed){
		orb.hideFriends();
		friendsDisplayed = false;
	}
}
function getFriends(){
	//$('showMe').hide();
	//$('hideMe').show();
	var jsonFriends = {};
	var userUrl = "/data/friends.json";
	new Ajax.Request(userUrl, {
	  method:'get',
	  onSuccess: function(transport){	  
	  	  friendsDisplayed = true;
		  jsonFriends = transport.responseText.evalJSON(true);
		  var friends = jsonFriends['friends'];
		  for(var i = 0; i < friends.length; i++){
			 var f = friends[i]['user']; 
		  	 orb.createIndependentVoterObjs(f['id'], f['username'], null, f['color'], new Array(0,0,0), new Array(f['x'],f['y'],0));
		  }
	  	}
	  }
   );
}

function getBasicDataFLASHlasso(urlParams, clearHighlight){
	if(clearHighlight){
		overlayMessage("REMOVING VOTER HIGHLIGHT<BR/>(Re-calculating Data/Filters box)");
		$('clearCircle').hide();
	}else{
		overlayMessage("CALCULATING VOTER HIGHLIGHT<BR/>(The circled portion of the orb)");
		$('clearCircle').show();
	} 
	urlLassoParams = (urlParams != "") ? urlParams : null;
	var thisUrl = urlGenerator(url);
	new Ajax.Request(thisUrl, {
	  method:'get',
	  onSuccess: function(transport){
		  updateDataAlert = true;
		  json = transport.responseText.evalJSON(true);
		  drawDatabox();
		  hideCalulatingMessage();
		}
	  }
   );	
}

function topic_id_from_url(_url) {
	var matches = _url.match(/vote\[vote_topic_id\]=(\d+)/);
	if(matches && matches[1]) return matches[1];
	return null;
}

function getSingleVoteData(incomingUrl){	
	var thisUrl = urlGenerator(incomingUrl);
	new Ajax.Request(thisUrl, {
	  method:'get',
	  onSuccess: function(transport){	  	
	 	  json = transport.responseText.evalJSON(true);
		  if(json['error']){
				var topic_id = topic_id_from_url(lastUrl);
				var elem = $('comValID');
				if(elem && elem.down('#'+topic_id)) elem = elem.down('#'+topic_id);

				if(mID == null) {
					elem.innerHTML += " <div class='login_vote_from_common_values_prompt'>Before filtering by vote, you'll need to tell us who you are and what <em>you</em> think.<div class='login_vote_links_from_common_values_prompt'><a href='/login'>Login</a> | <a href='/register'>Register</a></div></div>";					
				} else {
					elem.innerHTML += " <div class='login_vote_from_common_values_prompt'>Before filtering by vote, you'll need to tell us what <em>you</em> think. &nbsp;<a href='/vote/" + topic_id + "'>Vote now</a>.<p style='margin-top:0.8em;'>If you just voted, it might take up to a minute for your vote to be registered with the Orb.  Please try <a href='javascript:refresh();'>refreshing</a> after a few seconds or <a href='/orb/'>removing the vote filter</a>.</p></div>";
					
					var uri = window.location.href.replace(/\#(.*)$/, '');
					uri += '#vote_topic_id=' + topic_id;
					window.location.href = uri;
				}

			 // hideCalulatingMessage();

			  Effect.DropOut('calculatingMsg');
		  }else{
			  drawDatabox();
			  setImageTile();
			  $('specificVote').appear();
			  $('specificVote').innerHTML = "VIEWING SINGLE VOTE TOPIC: <div style=\"display:inline; float:right; font-size:9px;\">(<a style=\"font-size:9px; color:#ffffff; text-decoration:underline;\" href=\"javascript:removeSingleVoteView();\">restore all vote topics</a>)</div><div id=\"statement\">" + curStatement + "</div>";
	  		  //getDataAboutIndividuals("celebrities");
			  //getDataAboutIndividuals("friends"); 
		  }
	  	}
	  }
   );
}

function getDataAboutIndividuals(type){	
	// ADD var thisUrl = urlGenerator(incomingUrl) TO THIS
	var socialUrl = "/data/" + type + ".json?limit=50&minimum_move=10&";
	new Ajax.Request(socialUrl, {
	  method:'get',
	  onSuccess: function(transport){	  	
	 	  celebSocRecentJson = transport.responseText.evalJSON(true);	
		  drawCelebSocialData(type);
	  	}
	  }
   );
}


function getDataOnVote(voteTopicId, voteValue){
	// un-used in favor of "getSingleVoteData" above
	// ADD var thisUrl = urlGenerator(incomingUrl) TO THIS
	var voteDataUrl = url2ColumnVoteBreakdown[0] + voteTopicId + url2ColumnVoteBreakdown[1] + voteValue;
	new Ajax.Request(voteDataUrl, {
	  method:'get',
	  onSuccess: function(transport){	  	
	 	  voteSpecificJson = transport.responseText.evalJSON(true);	
		  //drawVoteSpecificData();
	  	}
	  }
   );
}


////////////////////////////////////////////////////////////////////////////////////////////////////
/* 				  								DRAW TABLES									 	  */
////////////////////////////////////////////////////////////////////////////////////////////////////


function drawDatabox(){
  var datagrid = {};
  var ignore_categories = ['vote_count', 'total_respondents', 'common_values', 'vote_options', 'vote_topic'];

  var js_vote_options = json['vote_options'];
  var vote_options = [];
  var categories = [];
  var rows = {};
  var num_options = js_vote_options.length;

  // Get & vote options
  for(var i = 0; i < num_options; i++) {
    vote_options.push(js_vote_options[i]['vote_option']); 
  } 

  vote_options.sort(function(a,b) { 
    if(a['value'] < b['value']) return 1;
    if(a['value'] > b['value']) return -1;
    return 0;
  });


  // Get categories and rows
  for(var category in json) {
    if(ignore_categories.indexOf(category) < 0) {
      categories.push(category); 
      if(json[category] == 'not available') {
        
      } else {
        var numRows = json[category].length;
        if(!rows[category]) rows[category] = {};
        for(var i = 0; i < numRows; i++) {
          var element = json[category][i];
          rows[category][element['name']] = true; 
        }
      }
    }
  }

  categories.sort();


  // Create empty grid
  var numCategories = categories.length;
  for(var i = 0; i < numCategories; i++) {
    var category = categories[i];
    datagrid[category] = {};
    for(var rowName in rows[category]) {
      datagrid[category][rowName] = {};
      for(var j = 0; j < num_options; j++) {
        var option = vote_options[j];
        datagrid[category][rowName][option['name']] = (num_options > 1) ? "0%" : (0).toString();
      } 
    }
  }



  
  // Populate grid with available data points
  for(var category in json) {
    if(ignore_categories.indexOf(category) < 0) {
      var numRows = json[category].length;
      if(json[category] == 'not available') {
        //$('footer').innerHTML += category + ' not available.  ';
      } else {
        for(var i = 0; i < numRows; i++) {
          var element = json[category][i];
          var name = element['name'];
		  var percentage = element['percentage'];
          var value = element['value'];
          var count = element['count'];
          var vote_option_name = element['vote_option_name'];
          if(vote_option_name == null) vote_option_name = 'Total Votes';
          if(value == null) value = '-1';
          datagrid[category][name][vote_option_name] = (percentage) ? Math.floor((percentage*100)+.5) + "%": count;
        }
      }
    }
  } 
          
	var real_vote_options = [];
	for(var i = 0; i < num_options; i++) {
		real_vote_options.push(vote_options[i]);
	}


	var this_common_value = null;
	if(num_options >= 2) {
		var vote_topic_id = json['vote_topic'][0]['vote_topic']['id'];
		var common_values = json['common_values'];
		var num_common_values = common_values.length;
		for(var i = 0; i < num_common_values; i++) {
			var common_value = common_values[i];
			if(common_value['vote_topic_id'] == vote_topic_id) {
				this_common_value = common_value
				break;
			}
		}
	}

  if(num_options == 2) {
		if (/\[nnot\]/.test(json['vote_topic'][0]['vote_topic']['statement_template']) || /should not/.test(json['vote_topic'][0]['vote_topic']['desc'])) {
			if(!(/not/.test(this_common_value['statement']))) {			
		    vote_options.sort(function(a,b) {
		      if(a['value'] < b['value']) return -1;
		      if(a['value'] > b['value']) return 1;
		      return 0;
		    });
			}
	  }	else {
			if(this_common_value) {
				if(/not/.test(this_common_value['statement'])) {
			    vote_options.sort(function(a,b) {
			      if(a['value'] < b['value']) return -1;
			      if(a['value'] > b['value']) return 1;
			      return 0;
			    });
				}
			}
		}
	}
	
          
	var cellids = 0;
	for (var category in json){
		if(json[category] == "not available"){ 
			$(category).getElementsByClassName('entityTable')[0].innerHTML = "<span style=\"font-size:11px; color:#000000;\">In order to see these statistics,<br/>you first need to <a style=\"font-size:11px; color:#dd0000; text-decoration:underline;\" href=\"http://votavox.com/accounts/myprofile/\">enter your details</a><br/> for this demographic data topic.</span>";
		}else{
			if(category == 'vote_count'){
				$('totalVoteCount').innerHTML = "Total votes: " + json[category];
			}
			if(category != 'common_values' && category != 'vote_topic' && category != 'vote_count' && category != 'vote_options'){
				var tableOpen = '<table cellspacing=\"0"\>';
				var topRow = '';				
				topRow = '<tr id=\"gridTopRow\" class=\"entityItemRow\"><td id="Data_Entity" valign=\"bottom\" class=\"entityItemColumnNOLINK\" style=\"text-align:left; color:#dd0000;\">Data Entity</td>';
				var topRow_column_id = 0;
				for(var i = 0; i < num_options; i++) {
 				   var option_name = vote_options[i]['name'];
				   var topRowColumnVoteOptID = real_vote_options[topRow_column_id]['id'];
				   topRow_column_id++;
				   topRow += '<td id="' + topRowColumnVoteOptID + '" valign=\"bottom\" class=\"'; 
				   if(num_options == 1){ // one column version
					topRow += 'entityItemColumnNOLINK';
				   }else{
				    topRow += 'entityItemColumn';
				   }
				   topRow += ' entityItemTopRowCol\">' + option_name +'</td>';
				}				
				topRow += '</tr>';
				var rows = '';
				if(category != 'total_respondents'){
					var nodeNamesArr = new Array();
					var haveItem = false;
					for (var i = 0; i < json[category].length; i++){							
						for(var j = 0; j < nodeNamesArr.length; j++){
							if(nodeNamesArr[j] == json[category][i]['name']){
								haveItem = true;
								break; 
							}
						}
						if(!haveItem){
							var thisRowName = json[category][i]['name'];
							nodeNamesArr.push(thisRowName);//json[category][i]['name']);
							rows += '<tr id=\"' + json[category][i]['id'].toString() + '\" class=\"entityItemRow\">';
							cellids++;
							rows += columnTEMPLATE_EMPTY.evaluate({cellid: cellids.toString(), columnPoperty: thisRowName});// nameColumnTEMPLATE json[category][i]['name']});						
							var column_id = 0;	
							for(var columnCell in datagrid[category][thisRowName]){ // columns
								if(num_options == 1){ // one column version
									cellids++;
									rows += columnTEMPLATE.evaluate({cellid: cellids.toString(), columnPoperty: datagrid[category][thisRowName][columnCell].toString() });											
								}else{
									var myColumnVoteOptID = real_vote_options[column_id]['id'];
									rows += columnTEMPLATE.evaluate({cellid: myColumnVoteOptID.toString(), columnPoperty: datagrid[category][thisRowName][columnCell].toString() });									
									column_id++;
								}
							}
							rows += '</tr>';
						}
						haveItem = false;
					}					
				}	
				var tableClose = '</table>';		
				if(category == 'total_respondents'){ // json[category]['value'] !=  undefined
					$('totalRespondentsBlock').innerHTML = " &bull; Total respondents: " + json[category]['value']+ "";					
				}else{
					$(category).getElementsByClassName('entityTable')[0].innerHTML = tableOpen + topRow + rows + tableClose;
				}
			}else if(category == 'common_values'){
			//	if(json[category].length > 0){ // so long as there ARE common values
					drawCommonValues(json);
			//	}
			}
		}
	}
	reSetCurrentHandler(); // goes thru and finds if any are open (display:block;).... sometimes browser will do this
}

function drawCommonValues(jsonCommon){	
	updateCommonAlert = true;
	var commonValueHTML = "";
	for (var i = 0; i < jsonCommon['common_values'].length; i++){
		commonValueHTML += "<div id='" + jsonCommon['common_values'][i]['vote_topic_id'] + "' onclick=\"\" class=\"commonVal\">" + (Math.ceil(jsonCommon['common_values'][i]['percentage']*100)).toString() + "% agree: " + jsonCommon['common_values'][i]['statement'] + " <a title=\"Click to see voters and data on this topic.\" style=\"font-style:italic;\" href=\"javascript:examineCommonValue('" + jsonCommon['common_values'][i]['vote_topic_id'] + "', " + jsonCommon['common_values'][i]['vote_option_id'] + ", '" + jsonCommon['common_values'][i]['statement'] + "');\">orb</a></div>";
	}
	$('common_values').getElementsByClassName('entityTableCommonValues')[0].innerHTML = "<div style=\"\">" + commonValueHTML + "</div>";
	
	if($('statement')) {
		$('statement').update(jsonCommon['statement']);
		// var this_common_value = null;		
		//   	var _topic_id = lastUrl.match(/vote\[vote_topic_id\]\=(\d+)/);
		// if(_topic_id && _topic_id[1]) {
		// 	var topic_id = _topic_id[1];
		// 	var common_values = jsonCommon['common_values'];
		// 	var num_common_values = common_values.length;
		// 	for(var i = 0; i < num_common_values; i++) {
		// 		var common_value = common_values[i];
		// 		if(common_value['vote_topic_id'] == topic_id) {
		// 			this_common_value = common_value;
		// 			break;
		// 		}
		// 	}
		// 	
		// 	if(this_common_value) {
		// 		$('statement').update(this_common_value['statement']);
		// 	}
		// }
	}
}

function testFlashCall(c){
	alert(c);
	}
	
function drawCelebSocialData(section){
  	var tableOpen = '<table cellspacing=\"0"\>';
  	var rows = '';
  	for (var i = 0; i < celebSocRecentJson[section].length; i++){
		for(var people in celebSocRecentJson[section][i]){
			//rows += '<tr onclick=\"selectingRow(this, \'' + section + '\', \'' +  celebSocRecentJson[section][i][people].id.toString() + '\');\" id=\"' +  celebSocRecentJson[section][i][people].id.toString() + '\" class=\"entityItemRow\">';
			rows += '<tr id=\"' +  celebSocRecentJson[section][i][people].id.toString() + '\" class=\"entityItemRow\">';
				rows += nameColumnTEMPLATE.evaluate({columnPoperty: celebSocRecentJson[section][i][people].username});
			rows += '</tr>';
			var voter = celebSocRecentJson[section][i][people];
			orb.createIndependentVoterObjs(voter.id, voter.username, voter.last_vote_category_id, new Array(voter.last_x, voter.last_y, 0), new Array(voter.x, voter.y, 0));
		}
	}
	var tableClose = '</table>';		
	$(section).getElementsByClassName('entityTable')[0].innerHTML = tableOpen + rows + tableClose;	
}



////////////////////////////////////////////////////////////////////////////////////////////////////
/* 				  						CONTROL FUNCTIONS					 					  */
////////////////////////////////////////////////////////////////////////////////////////////////////

function orbButtonPress(divElem){
	if(divElem.id == 'clearDemographic'){ 
		selectingRow($(currentFilterID), currentFilterCategory, currentFilterID);
	}else if(divElem.id == 'clearCircle'){
		$('clearCircle').hide();		
		orb.executeCancelLasso();
	}else if(divElem.id == 'showAllFriends'){
		$('showAllFriends').hide();
		$('hideAllFriends').show();		
		if(friendsDisplayed){
			orb.repositionFriends();
		}else {
			getFriends();
			friendsDisplayed = true;
		}
	}else if(divElem.id == 'hideAllFriends'){
		$('hideAllFriends').hide();
		$('showAllFriends').show();		
		if(friendsDisplayed){
			orb.hideFriends();
			friendsDisplayed = false;
		}
	}
}

function generalResetFlush(){
	modifyDataReqsList($(currentFilterID), currentFilterCategory, currentFilterID);
	currentFilterID = null;	
	currentFilterCategory = null;	
	$('clearDemographic').hide();
	$('clearAllLinkDiv').hide();
	$('clearCircle').hide();
	orb.executeCancelLasso();
}

function removeSingleVoteView(){
	urlSpecificVoteParams = null;
	curSingleVoteTopicId = null;
	$('specificVote').fade();
	getBasicData(url);
}

function selectingRow(thisElem, category1, thisElemID){
	if(currentFilterID == thisElemID){
		urlDataParams = null;	
		currentSelectedDataElementRef = null;
		currentFilterID = null;	
		currentFilterCategory = null;
		$('clearDemographic').hide();
		$('clearAllLinkDiv').hide();		
		getBasicData(url);
	}else{
		updateDataAlert = true;
		urlDataParams = "demographics[category]=" + category1 +  "&demographics[value]=" + thisElemID + "";	
		currentSelectedDataElementRef = thisElem; 
		currentFilterID = thisElemID;
		currentFilterCategory = category1;	
		resetCommonValues();
		setImageTile();
		$('clearDemographic').show();
		$('clearAllLinkDiv').show();
		var respondentSpecifics = "";
		for(var i = 0; i < thisElem.getElementsByClassName('entityItemColumn').length; i++){
			respondentSpecifics += thisElem.getElementsByClassName('entityItemColumn')[i].innerHTML;
		}
		if(urlSpecificVoteParams == null){
			$('totalRespondentsBlock').innerHTML = " &bull; Total respondents for this demographic: " + respondentSpecifics + "";		
		}
	}		
	modifyDataReqsList(thisElem, category1, currentFilterID);
}

function selectColumn(thisElem, category1, thisElemID){

	var statementAugment = ""; 
	var overlayM = ""; 
	urlSpecificVoteParams = "vote[vote_topic_id]=" + curSingleVoteTopicId + "&vote[vote_option_id]=" + thisElemID;
	if((curSelectedColumnID != $(thisElem).id || curSelectedRowID != thisElem.up("tr").id)){ 
		curSelectedColumnID = $(thisElem).id;
		curSelectedRowID = thisElem.up("tr").id;
		updateDataAlert = true;
		if(thisElem.up("tr").id == 'gridTopRow'){
			urlDataParams = "";				
		}else{
			urlDataParams = "demographics[category]=" + category1 +  "&demographics[value]=" + thisElem.up("tr").id + "";				
		}
		currentSelectedDataElementRef = thisElem; 
		currentFilterID = thisElemID;
		currentFilterCategory = category1;			
		resetCommonValues();
		setImageTile();
		$('clearDemographic').show();
		$('clearAllLinkDiv').show();
		var respondentSpecifics = "";
		for(var i = 0; i < thisElem.getElementsByClassName('entityItemColumn').length; i++){
			respondentSpecifics += thisElem.getElementsByClassName('entityItemColumn')[i].innerHTML;
		}
		if(urlSpecificVoteParams == null){
			$('totalRespondentsBlock').innerHTML = " &bull; Total respondents for this demographic: " + respondentSpecifics + "";		
		}
		overlayM = "<u>ADDING</u> DEMOGRAPHIC FILTER FROM THIS SINGLE-TOPIC VIEW";
		if(thisElem.className == "entityItemColumnName"){
			statementAugment = thisElem.innerHTML;
		}		
		
		var td = thisElem;
		var tr = thisElem.up('tr');
		var first_td = tr.firstDescendant();
		var tds = first_td.siblings();		
		if(tds.length == 2) {
			var selectedColumn = -1;
			if(tds[0] == td) selectedColumn = 0;
			if(tds[1] == td) selectedColumn = 1;
			
			var table = tr.up('table');
			var first_tr = table.down('tr');
			var data_entity = first_tr.firstDescendant();
			var labels = data_entity.siblings();
			if(selectedColumn == 0) {
				labels[0].innerHTML = "Agree";
				labels[1].innerHTML = "Disagree";
			} else if(selectedColumn == 1) {
				labels[0].innerHTML = "Disagree";
				labels[1].innerHTML = "Agree";
			}
		}



	} else if(curSelectedColumnID == $(thisElem).id){
		urlDataParams = null;	
		currentSelectedDataElementRef = null;
		currentFilterID = null;	
		currentFilterCategory = null;
		curSelectedColumnID = null;
		curSelectedRowID = null;
		$('clearDemographic').hide();
		$('clearAllLinkDiv').hide();		
		getBasicData(url);	
		overlayM = "<u>REMOVING</u> DEMOGRAPHIC FILTER FROM THIS SINGLE-TOPIC VIEW";
		statementAugment = "";
	}
	$('filteringDemographic').show();
	var rowName = "";
	/*
	if(thisElem.className == 'entityItemColumn'){
		if(thisElem.previousSiblings()[0].className == 'entityItemColumnName'){
			rowName = thisElem.previousSiblings()[0].innerHTML;
		} else if(thisElem.previousSiblings()[1].className == 'entityItemColumnName'){
			rowName = thisElem.previousSiblings()[1].innerHTML;			
		}				
	} */
//	$('filteringDemographic').innerHTML = "Displayed demographic:  " + rowName ;// " + statementAugment; //curStatement + statementAugment
	overlayMessage(overlayM);
	modifyDataReqsList(thisElem, category1, currentFilterID);
}


function resetCommonValues(){
	var thisUrl = urlGenerator("/data/common_values.json");
	new Ajax.Request(thisUrl, {
	  	method:'get',
	  	onSuccess: function(transport){	  	
	 		jsonCommon = transport.responseText.evalJSON(true);
   		  	drawCommonValues(jsonCommon);
		}
	});
}


function setImageTile(){
	var thisUrl = urlGenerator("/data/tile");
	orb.loadImage(thisUrl);	
}


function examineCommonValue(voteTopicId, voteOptionID, statement){
	curSingleVoteTopicId = voteTopicId;
	curStatement = statement;
	$('specificVote').hide();
	overlayMessage("SETTING UP SINGLE-TOPIC VIEW");
	urlSpecificVoteParams = "vote[vote_topic_id]=" + voteTopicId + "&vote[vote_option_id]=" + voteOptionID.toString() + "";
	getSingleVoteData(url);
	$$('.login_vote_from_common_values_prompt').each(function(div, index) {div.remove();});
	//$('specificVote').appear();
	//$('specificVote').innerHTML = "VIEWING SINGLE VOTE TOPIC: <div style=\"display:inline; float:right; font-size:9px;\">(<a style=\"font-size:9px; color:#ffffff; text-decoration:underline;\" href=\"javascript:removeSingleVoteView();\">restore all vote topics</a>)</div><div id=\"statement\">" + statement + "</div>";
}


function overlayMessage(msg){
	$('calculatingMsg').show();
	if(msg == null){
		$('filteringForOverlayMsg').innerHTML = "CALCULATING DATA WITH<i><u>OUT</u></i> FILTER<br/>(removing demographic filter)";
	} else {
		$('filteringForOverlayMsg').innerHTML = msg;
	}
}


function hideCalulatingMessage(){
	Effect.DropOut('calculatingMsg');
	if(friendsDisplayed){
		orb.repositionFriends();
	}
	if(updateCommonAlert){
		updateAlert($('updateCommon'), 1.25);
		updateCommon = false;
		setTimeout ( "fadeCommonAlert()", 3000 );
	}
	if(updateDataAlert){
		updateAlert($('updateData'), 1.5);
		updateDataAlert = false;
		setTimeout ( "fadeDataAlert()", 3700 );
	}	
}

function fadeCommonAlert(){ hideAlert($('updateCommon')); }

function fadeDataAlert(){ hideAlert($('updateData')); }

function updateAlert(element, duration){
	element.appear({ duration: 0.5 });
	if(browser == "Netscape" && vendor != "Apple Computer, Inc."){ // FIREFOX
		element.setStyle({ marginLeft: '-275px'});
		new Effect.Morph(element, {
  			style: 'margin-left: -160px;',
			transition:Effect.Transitions.BouncePast, //EaseTo,			
  			duration: duration 
		});
	} else if(browser == "Netscape" && vendor == "Apple Computer, Inc."){ // SAFARI
		element.setStyle({ marginLeft: '0px'});
		new Effect.Morph(element, {
  			style: 'margin-left: 115px;',
			transition:Effect.Transitions.BouncePast, //EaseTo,			
  			duration: duration 
		});	
	}/* else { // OTHER
		new Effect.Morph(element, {
  			style: 'margin-left: 0px;',
			transition:Effect.Transitions.BouncePast,			
  			duration: 1.25 
		});	
	}*/
}

function hideAlert(element){
	element.fade({ duration: 0.5 });
}

function expandDashboardComponent(componentID, myPlusMinusElem){
	if($(myPlusMinusElem).down().className == 'minus'){
		if(myPlusMinusElem.id == "colorsDash" || myPlusMinusElem.id == "friendsDash"){
			new Effect.Morph($(componentID), {
				style: 'height: 0px; max-height: 0px;', 
				duration: 0.25 
			});
			new Effect.Morph($(componentID).up(), {
				style: 'height: 0px; max-height: 0px;',  
				duration: 0.25  
			});	
			if(myPlusMinusElem.id == "friendsDash") Effect.Fade($('people'), {duration: 0.25});
			if(myPlusMinusElem.id == "colorsDash") Effect.Fade($('colorLegendPanel'), {duration: 0.25});			
		}else{
			new Effect.Morph($(componentID), {
				style: 'height: 200px; max-height: 188px;', 
				duration: 0.25 
			});
			new Effect.Morph($(componentID).up(), {
				style: 'height: 200px; max-height: 188px;',  
				duration: 0.25  
			});
		}
		$(myPlusMinusElem).innerHTML = "<img class=\"plus\" style=\"display:inline; margin-top:3px; margin-left:4px;\" align=\"top\" src=\"images/plusGray.png\" border=\"0\" />";
	}else{
		if(myPlusMinusElem.id == "colorsDash" || myPlusMinusElem.id == "friendsDash"){		
			new Effect.Morph($(componentID), {
				style: 'height: 200px; max-height: 188px;',  
				duration: 0.25  
			});
			new Effect.Morph($(componentID).up(), {
				style: 'height: 200px; max-height: 188px;', 
				duration: 0.25 
			});
			if(myPlusMinusElem.id == "friendsDash") Effect.Appear($('people'), {duration: 0.5});
			if(myPlusMinusElem.id == "colorsDash") Effect.Appear($('colorLegendPanel'), {duration: 0.5});						
		}else{
			new Effect.Morph($(componentID), {
				style: 'height: 400px; max-height: 400px;',  
				duration: 0.25  
			});
			new Effect.Morph($(componentID).up(), {
				style: 'height: 400px; max-height: 400px;', 
				duration: 0.25 
			});
		}
		$(myPlusMinusElem).innerHTML = "<img class=\"minus\" style=\"display:inline; margin-top:3px; margin-left:4px;\" align=\"top\" src=\"images/minusGray.png\" border=\"0\" />";
	}
}

function modifyDataReqsList(element, category1, currentFilterID){
	var infoColumnEntity = element.ancestors()[3];
	if(currentSelectedRow != null){
	   var morph = new Effect.Morph(currentSelectedRow, {
 		 style: 'background-color:#ffffff; color:#000000;', // CSS Properties
  		 duration: 0.4
	   });
	}
	if(currentFilterID == null){  // remove req		
		element.setStyle({ backgroundColor: '#ffffff', color: '#000000'});	
		currentSelectedRow = null;
		$('filteringDemographic').innerHTML = "";
		overlayMessage(null);
	}else{  // add new req		
		element.setStyle({ backgroundColor: '#dd0000', color: '#ffffff'});
		currentSelectedRow = element;
		var ovrStrMsg = ($(element).down() == null) ? "" : $(element).down().innerHTML;
		$('filteringDemographic').innerHTML = "Displayed Demographic: " + $(category1).down(1).innerHTML;// + ("+ ovrStrMsg + ")";
		overlayMessage("CALCULATING DATA FOR:<br/><span style=\"color:#ffffff; background-color:#dd0000; padding: 2px 5px 2px 5px;\">" + ovrStrMsg + "</span>");
	} 
}





