﻿// helper functions
var setupStats = function() {

    var myGraph = new mooBarGraph({
        container: $('statChart'),
        data: new Array([0, '', '', '', '']),
        colors: ['#3a87d0', '#1d75c9', '#0063c1', '#1d75c9'],
        color: '#1A2944',
        width: 198,
        height: 50,
        barSpace: 0

    });

    myGraph.draw('/feeds/stats_json.aspx');

}


var gotoPage = function(page) {
    $('CurrentPage').setProperty('text', page);
    $('deals').setProperty('text', '');
    $('Pager').setProperty('text', 'Loading...');
    startPage();
    $('imgLoader').style.visibility = "Visible";
    scroll(0, 0);

}

var renderLinkPager = function() {

    var currentPage = $('CurrentPage').getProperty('text');

    var startPage = '<a href=\"/\">Previous Page</a>';
    var prevPage = '<a href=\"/?p=' + (parseInt(currentPage, 10) - 1) + '\">Previous Page</a>';
    var nextPage = '<a href=\"/?p=' + (parseInt(currentPage, 10) + 1) + '\">Next Page</a>';

    if (currentPage == 1) {
        $('Pager').setProperty('html', nextPage);
    }
    else if (currentPage == 2) {
    $('Pager').setProperty('html', startPage + ' - ' + nextPage);
    }
    else {
        $('Pager').setProperty('html', prevPage + ' - ' + nextPage);
    }
}

var renderPager = function() {

    var currentPage = $('CurrentPage').getProperty('text');

    var prevPage = '<a href=\"#\" id=\"pPage\">Previous Page</a>';
    var nextPage = '<a href=\"#\" id=\"nPage\">Next Page</a>';

    if (currentPage == 1) {
        $('Pager').setProperty('html', nextPage);
        $('nPage').addEvent('click', function(e) {
        e = new Event(e).stop();
            gotoPage(2);
        });
    }
    else {
        $('Pager').setProperty('html', prevPage + ' - ' + nextPage);
        $('nPage').addEvent('click', function(e) {
            e = new Event(e).stop();
            gotoPage((parseInt(currentPage, 10) + 1));
        });
        $('pPage').addEvent('click', function(e) {
            e = new Event(e).stop();
            gotoPage((parseInt(currentPage, 10) - 1));
        });
    }

}

var updateDates = function() {
    var table = $('deals');
    // logic to determine where to add
    var currentRows = table.getElements('tr');

    if (currentRows.length != 0) {        
        for (x = 0; x < currentRows.length; x++) {
            var origTime = currentRows[x].getElementsByTagName('td')[0].getProperty('id');
            currentRows[x].getElementsByTagName('td')[0].setProperty('text', processDate(origTime));         
        }
    }
}

var processDate = function(dateUtc) {
    var diff = 0;
    var postDate = new Date(parseInt(dateUtc, 10));
    var currentDate = new Date();
    var yearToday = currentDate.getUTCFullYear();
    var monthToday = currentDate.getUTCMonth();
    var dayToday = currentDate.getUTCDate();
    var hourToday = currentDate.getUTCHours();
    var minToday = currentDate.getUTCMinutes();
    var secToday = currentDate.getUTCSeconds();
    var msToday = currentDate.getUTCMilliseconds();
    var utcDate = Date.UTC(yearToday, monthToday, dayToday, hourToday, minToday, secToday, msToday);

    diff = utcDate - postDate;

    var daysPast = Math.floor((diff / 86400000));
    var hoursPast = Math.floor((diff % 86400000) / 3600000);
    var minutesPast = Math.floor(((diff % 86400000) % 3600000)/60000);    

    return minTwoDigits(daysPast) + ':' + minTwoDigits(hoursPast) + ':' + minTwoDigits(minutesPast);
}

var minTwoDigits = function(n) {
    if (n > 9) return n;
    if (n == 0) return '00';
    if (n < 0) return '00';
    return '0' + n;
}

//main ajax content
var insertRow = function(row) {
    var table = $('deals');
    var currentRows = table.getElements('tr');

    if (currentRows.length == 0) {
        row.injectInside(table);
    }
    else {
        var firstRow = table.getFirst('tr');
        row.injectBefore(firstRow);
    }

    //remove the last element if list is too big
    if (currentRows.length > 50) table.getLast('tr').destroy();
}

var processDeal = function(deals) {
        var lastid;
        deals.each(function(deal) {
            var row = new Element('tr');
            var dateposted = new Element('td', { 'id': deal.datefound, 'class': 'DealDate' }).set('html', processDate(deal.datefound)).injectInside(row);
            var link = new Element('td', { 'id': deal.id, 'class': 'DealTitle' }).set('html', deal.link).injectInside(row);
            insertRow(row);
            lastid = deal.id;
        });

        // window.product_paginator.update_pages();
        if (lastid != null) $('LastUpdateID').set('text', lastid);

        $('imgLoader').style.visibility = "hidden";
        renderPager();
}

var getUpdates = function() {
    $('imgLoader').style.visibility = "visible";
    var lastid = $('LastUpdateID').get('text');
    getFeed('/feeds/deals_json.aspx?l=' + lastid);

    updateDates();
}  
    
var getFeed = function(furl) {
    var request = new Request.JSON({
        url: furl,
        onComplete: function(jsonObj) {
            if (jsonObj != null) {
                processDeal(jsonObj);
            }
        }
    }).send();
}

var startPage = function() {
    $clear(window.Updates);
    var currentPage = $('CurrentPage').getProperty('text');

    if (currentPage == 1) {
        getFeed('/feeds/deals_json.aspx');

        //check for updates
        window.Updates = getUpdates.periodical(60000);
    }
    else {
        getFeed('/feeds/deals_json.aspx?p=' + currentPage);
        window.Updates = updateDates.periodical(60000);
    }

    if (currentPage > 1) {
        $('HeaderDetail').setProperty('text', ' - Page ' + currentPage);
    }
    else {
        $('HeaderDetail').setProperty('text', '');
    }

    
}

//Finally start everything up
window.addEvent('domready', function() {
    startPage();
    ConfigureSearch();
    setupStats();
});