/* 
 This file was generated by Dashcode.  
 You may edit this file to customize your widget or web page 
 according to the license.txt file included in the project.
 */

// for local testing, calling the API directly
var apiHost = "http://api.kivaws.org";
var bizURL =  apiHost + "/v1/loans/newest.json";

// for the server, where cross-site data calls aren't allowed
var proxyURL = 'http://socialology.org/api_proxy.rb?method='
var bizURL = proxyURL+'loans';
var partnersURL = proxyURL+'partners';
var statsFeedURL = 'http://socialology.org/statsfeed.rb';
var businesses = [];
var liveStats = [];
var partners = {};

Date.prototype.setISO8601 = function (string) {
    var regexp = "([0-9]{4})(-([0-9]{2})(-([0-9]{2})" +
        "(T([0-9]{2}):([0-9]{2})(:([0-9]{2})(\.([0-9]+))?)?" +
        "(Z|(([-+])([0-9]{2}):([0-9]{2})))?)?)?)?";
    var d = string.match(new RegExp(regexp));

    var offset = 0;
    var date = new Date(d[1], 0, 1);

    if (d[3]) { date.setMonth(d[3] - 1); }
    if (d[5]) { date.setDate(d[5]); }
    if (d[7]) { date.setHours(d[7]); }
    if (d[8]) { date.setMinutes(d[8]); }
    if (d[10]) { date.setSeconds(d[10]); }
    if (d[12]) { date.setMilliseconds(Number("0." + d[12]) * 1000); }
    if (d[14]) {
        offset = (Number(d[16]) * 60) + Number(d[17]);
        offset *= ((d[15] == '-') ? 1 : -1);
    }

    offset -= date.getTimezoneOffset();
    time = (Number(date) + (offset * 60 * 1000));
    this.setTime(Number(time));
}

var listController = {
    // This object acts as a controller for the list UI.
    // It implements the dataSource methods for the list.
    
    numberOfRows: function() {
        // The List calls this dataSource method to find out how many rows should be in the list.
        return businesses.length;
    },
    
    prepareRow: function(rowElement, rowIndex, templateElements) {
        // The List calls this dataSource method for every row.  templateElements contains references to all elements inside the template that have an id. We use it to fill in the text of the rowTitle element.
        businesses[rowIndex].amountNeeded = businesses[rowIndex].loan_amount -
                businesses[rowIndex].funded_amount;
        businesses[rowIndex].iconPhoto = 'http://www.kiva.org/img/w80h80/' + businesses[rowIndex].image.id + '.jpg';
        businesses[rowIndex].location.description = businesses[rowIndex]['location']['town'] + ', ' +
            businesses[rowIndex]['location']['country'];

        // all of these fields are guaranteed
        templateElements.borrowerName.innerText = businesses[rowIndex].name;
        templateElements.borrowerLocation.innerText = businesses[rowIndex].location.description;
        templateElements.amountNeeded.innerText = '$'+businesses[rowIndex].amountNeeded;
        templateElements.borrowerIndustry.innerText = businesses[rowIndex].activity;
        templateElements.borrowerPhoto.style.backgroundImage = 'url('+businesses[rowIndex].iconPhoto +')';

        // We also assign an onclick handler that will cause the browser to go to the detail page.
        var self = this;
        var handler = function() {
            var biz = businesses[rowIndex];
            detailController.setBusiness(biz);
            var browser = document.getElementById('browser').object;
            // The Browser's goForward method is used to make the browser push down to a new level.  Going back to previous levels is handled automatically.
            browser.goForward(document.getElementById('entrepDetailLevel'), biz['name']);
        };
        rowElement.onclick = handler;
    }
};

var detailController = {
    // This object acts as a controller for the detail UI.
    
    setBusiness: function(biz) {
        this.biz = biz;
        this._representedObject = biz.id;
        biz.percentComplete = biz.funded_amount / biz.loan_amount;
        biz.percentComplete = Math.floor(biz.percentComplete*100);
        biz.postedDate = new Date();
        if(biz.posted_date) {
            biz.postedDate.setISO8601(biz.posted_date);
        }
        
        document.getElementById('loanBorrower').innerText = biz.name;
        document.getElementById('loanDescription').innerText = (biz.use.length < 256)? biz.use : biz.use.substr(0,255)+'...';
        document.getElementById('loanPhoto').style.backgroundImage = 'url(' + 'http://www.kiva.org/img/w130h130/' + biz.image.id + '.jpg' + ')';
        document.getElementById('loanPhoto').onclick = function() { window.location = 'http://www.kiva.org/img/w450h360/'+ biz.image.id + '.jpg'; };
        document.getElementById('loanProgressBar').style.width = biz.percentComplete + '%';
        document.getElementById('loanTotalAmount').innerText = '$'+biz.loan_amount;
        document.getElementById('loanPostedDate').innerText = biz.postedDate.toLocaleString();
        document.getElementById('loanNeededAmount').innerText = '$'+biz.amountNeeded+' still needed';
        document.getElementById('loanLocation').innerText = biz.location.description;
        document.getElementById('loanIndustry').innerText = biz.activity;
        document.getElementById('lendButton').onclick = function() { window.location ='http://www.kiva.org/app.php?page=businesses&action=about&id='+biz.id; };
        
        document.getElementById('partnerName').innerText = partners[biz.partner_id].name;
        var partnerRating = Math.floor(partners[biz.partner_id].rating);
        for(var k=1;k<=5;k++) {
            document.getElementById('star'+k).style.visibility = (k<=partnerRating) ? 'visible' : 'hidden';
        }
    }
    
};

//
// Function: load()
// Called by HTML body element's onload event when the web application is ready to start
//
function load()
{
    dashcode.setupParts();

    // load loans
    document.getElementById('pagingText').innerText  = '(fetching new loans...)';
    var loanRequest = new XMLHttpRequest();
    loanRequest.onload = function(){ loansLoaded(loanRequest) };
    loanRequest.open("GET", bizURL);
    loanRequest.setRequestHeader("Cache-Control", "no-cache");
    loanRequest.send(null);

    // load stats
    var statsRequest = new XMLHttpRequest();
    statsRequest.onload = function(){ statsLoaded(statsRequest) };
    statsRequest.open("GET", statsFeedURL);
    statsRequest.setRequestHeader("Cache-Control", "no-cache");
    statsRequest.send(null);
}


function loadPartners()
{
    // load loans
    var partnerRequest = new XMLHttpRequest();
    partnerRequest.onload = function(){ partnersLoaded(partnerRequest) };
    partnerRequest.open("GET", partnersURL);
    partnerRequest.setRequestHeader("Cache-Control", "no-cache");
    partnerRequest.send(null);
}

// Called when an XMLHttpRequest loads a feed; works with the XMLHttpRequest setup snippet
function loansLoaded(jsonRequest) 
{
	if (jsonRequest.status == 200) {
		// Parse and interpret results
        var results = eval('var cowData = '+jsonRequest.responseText);
        if(cowData.loans && cowData.loans.length > 0)
        {
            businesses = cowData.loans;
            document.getElementById("businessList").object.reloadData();
            document.getElementById('pagingText').innerText = '('+cowData.loans.length 
                +' of '+cowData.paging.total+' available)';
            loadPartners();
        }
	}
	else {
		alert("Error fetching data: HTTP status " + jsonRequest.status);
	}
}

function partnersLoaded(jsonRequest)
{
	if (jsonRequest.status == 200) {
		// Parse and interpret results
        var results = eval('var partnerData = '+jsonRequest.responseText);
        if(partnerData.partners && partnerData.partners.length > 0)
        {
            var temp;
            // index all the partner entries by ID
            for(var k=0; k< partnerData.partners.length; k++) {
                partners[ partnerData.partners[k].id ] = partnerData.partners[k];
            }
        }
	}
	else {
		alert("Error fetching data: HTTP status " + jsonRequest.status);
	}
}

function statsLoaded(jsonRequest) 
{
	if (jsonRequest.status == 200) {
		// Parse and interpret results
        var results = eval('var cowData = '+ jsonRequest.responseText);
        liveStats = [];
        if(cowData.count > 0 && cowData.value && cowData.value.items)
        {
            for(i in cowData.value.items) {
                var item = cowData.value.items[i];
                switch(item.title) {
                    case 'Loans Yesterday':
                        liveStats.push({title:'New Loans',value:item.description});
                        break;
                    case 'Users Added Yesterday':
                        liveStats.push({title:'New Users',value:item.description});
                        break;
                    case 'Total Loans':
                        if(item.description.charAt(0) === '$') {
                        liveStats.push({title:item.title,value:item.description}); }
                        break;
                    case 'Total Users':
                        liveStats.push({title:item.title,value:item.description});
                        break;
                }
            }
            liveStats.sort(function(a,b){return a.title.localeCompare(b.title);});
            updateStats();
        }
	}
	else {
		alert("Error fetching data: HTTP status " + jsonRequest.status);
	}
}

var statIndex = 0;
function updateStats() {
    if(!liveStats.length) return;
        
    document.getElementById('headlineText').innerText = liveStats[statIndex].title;
    document.getElementById('statText').innerText = liveStats[statIndex].value;
    setTimeout(updateStats, 5000);

    statIndex += 1;
    if(statIndex >= liveStats.length) { statIndex = 0; }    
}