// ==UserScript==
// @name           AccountAbility
// @namespace      http://bilumi.org
// @description    Add social responsibility information to online bank statements.
//                 In particular:
//                     inserts ratings next to merchant names in transaction lists
//                     inserts google map (iframe to bilumi page) of merchant locations
//                 Ultimately should show other merchants that meet social responsibility criteria.
//                 Currently only works with Bank of America credit cards.
// ==/UserScript==

// Add jQuery
    var GM_JQ = document.createElement('script');
    GM_JQ.src = 'http://jquery.com/src/jquery-latest.js';
    GM_JQ.type = 'text/javascript';
    document.getElementsByTagName('head')[0].appendChild(GM_JQ);

// Check if jQuery is loaded
    function GM_wait() {
        if(typeof unsafeWindow.jQuery == 'undefined') { window.setTimeout(GM_wait,100); }
	else { $ = unsafeWindow.jQuery; realwork(); }
    }
    GM_wait();

// All your GM code must be inside this function
    function realwork() {
	bank_of_america();
    }

    var RATING_SPAN_CLASS = "accountability_rating";
    var RATING_TD_CLASS = "accountability_td";
    var RATING_HEADER_CLASS = "accountability_header";

    function bank_of_america() {
	if (! $(".acctdetaillinks").length > 0 ) { return; }
	var names = [];
    
	$(".acctdetaillinks").each( function() {
		if ($(this).siblings(".icontags").children("img").attr("title") == "Purchase" ||
		    $(this).siblings(".icontags").children("img").attr("title") == "Temporary Authorization") {
			var name = $(this).children("a").html();
			//$(this).after("<td class='"+RATING_TD_CLASS+"'></td>");
			//insert_ratings( $(this).next(), encodeURIComponent( name ) );
			insert_ratings( $(this), encodeURIComponent( name ) );
			names[names.length] = name;
		}
	});

	// TODO: add as column in table and permit sorting (yikes, scrape and sort)! catch ajax calls in order to re-insert ratings when other columns are sorted.
	//$(".headeracctdetail").after("<td class='"+RATING_HEADER_CLASS+"'>Soc.Resp.Index</td>");
	//$("."+ RATING_HEADER_CLASS).css("font-size", $(".headeracctdetail").css("font-size") );
	insertMap(names);
	//$(this).children("a").css("background","red").click();
   }

    function insert_ratings( elem, name ) {
	$.getJSON(
		"http://staging.thoughtandmemory.org/Main/api/get/rating/?name="+name+"&return_fake_data=True&callback=?",
	        function(data) {
			var r = '?';
			if (data.score != '') { r = parseInt(data.score) }
			//elem.append("<span class='"+RATING_SPAN_CLASS+"'>("+r+")</span>");
			elem.prepend("<span class='"+RATING_SPAN_CLASS+"'>("+r+")</span>");
			$("."+RATING_SPAN_CLASS).css("float","right");
		}
	);
    }

// insert iframe into bilumi page that hosts a google map
// send over company names
    function insertMap(names) {
	var MAP_DIV_ID = "accountability_map";

	// if map is already inserted return
	if ( $("#"+MAP_DIV_ID).length > 0 ) { return; }

	var mapurl = 'http://staging.thoughtandmemory.org/Main/api/map/?return_fake_data=True&names=' + encodeURIComponent(names.join());
    
	var mapdiv = " \
		<div id='" + MAP_DIV_ID + "' style='font-size: .8em; clear: both; text-align: center; background: white; padding-top:7px;'> \
			<span class='info'> \
				View stores and purchases that meet your social responsibility interests</span> \
			<span class='linkback'> \
				Find out more at <a href='http://bilumi.org'>bilumi.org</a></span> \
			<span class='close'> \
				close map</span> \
			<span class='open'> \
				open map</span> \
		</div> \
		";

	$("#activityheader").before(mapdiv);

	$("#"+MAP_DIV_ID+" > span.linkback, #"+MAP_DIV_ID+" > span.close, #"+MAP_DIV_ID+" > span.open").css("font-size", ".8em").css("padding-top", "3px");
	$("#"+MAP_DIV_ID+" > span.linkback").css("float", "left");
	$("#"+MAP_DIV_ID+" .close, #"+MAP_DIV_ID+" .open").css("float", "right").css("cursor", "pointer");

	$("#"+MAP_DIV_ID+" .close").click( function() {
		$(this).siblings("iframe").remove();
		$(this).hide();
		$(this).siblings(".open").show();
	});
	$("#"+MAP_DIV_ID+" .open").click( function() {
		show_map();
		$(this).hide();
		$(this).siblings(".close").show();
	});
	$("#"+MAP_DIV_ID+" > span.open").hide();

	function show_map () {
		if ($("#"+ MAP_DIV_ID+" > iframe").length > 0) { return; }
			var f = document.createElement('iframe');
			f.setAttribute('width', '520px');
			f.setAttribute('height', '320px');
			f.setAttribute('style', 'padding: 0px; margin: 0px; clear: both; border: none;');
			f.setAttribute('src', mapurl);
			$("#"+MAP_DIV_ID).append(f);
		}
	show_map();
    }
