﻿// for LIve Feed in "Follow Us section of Preserve the Parks"

// declare global arrays
var combinedArray = [];
var newString = "";

// pushes object onto array
function pusher(array, elm) {
    array.push(elm);
}

// pop last object off array
function popArray(array) {
    array.pop();
}

// object to store data, this will get pushed into the arrays
function feedObj(service, type, value, link, name, date, origDate) {
    this.service = service; // facebook or twitter
    this.type = type; 	// status or link
    this.value = value; // the text/message
    this.link = link; 	// fb link
    this.name = name; 	// fb link name
    this.date = date; 	// date/time it was created
    this.origDate = origDate;
}

// fixes the date/time stamp provided by facebook
function formatFBTime(fbDate) {
    var arrDateTime = fbDate.split("T");  //separator to chop up the date.  makes it an array
    var strTimeCode = arrDateTime[1].substring(0, arrDateTime[1].indexOf("+"));  //pulls out time as a string

    var valid_date = new Date(arrDateTime[0].replace(/-/g, '/'))  // 0 = first spot
    var arrTimeCode = strTimeCode.split(":");  //splitter to turn data into array 
    valid_date.setHours(arrTimeCode[0]);  //  Hours dictates which array position to pull data
    valid_date.setMinutes(arrTimeCode[1])  //minutes
    valid_date.setSeconds(arrTimeCode[2])  //seconds

    if (arrTimeCode[0] > 12) {
        var hours = parseInt(valid_date.getHours()) - 12;
    }
    else {
        var hours = valid_date.getHours();
    }

    var month = valid_date.getMonth();
    var minutes = valid_date.getMinutes();
    if (minutes == 0)
        minutes = "00";
    var day = valid_date.getDate();
    var time = valid_date.setHours + ":" + valid_date.setMinutes;

    var montharray = new Array("Jan", "Feb", "Mar", "Apr", "May", "June",
                            "July", "Aug", "Sep", "Oct", "Nov", "Dec")

    newString = hours + ":" + minutes + " " + montharray[month] + " " + day;


    return valid_date;  //this returns a valid date object in same format as Twitter  
}

$(function() {
    var token;

    $.ajax({
        type: 'POST',
        url: 'FBToken.asmx/GetAccessToken',
        date: "{}",
        contentType: "application/json; charset=utf-8",
        dataType: 'json',
        success: function(response) {
            token = response.d;
            beginFeed(token);
        }
    });



});

function beginFeed(resp) {

    // get facebook
    $.getJSON("https://graph.facebook.com/naturevalley/posts?limit=15&access_token=" + resp + "&callback=?", function(json) {

        $.each(json.data, function(i) {
            var basic_date = formatFBTime(this.created_time);
            var date = new Date(Date.parse(basic_date));
            var service = "Facebook"; 		// service identifier
            var link = this.link;
            var name = this.from.name;

            var message = this.message; //actual text of the message

            if (message != undefined) {  //detects if there is any text that should be a hyperlink
                if (message.indexOf("http://") >= 0) {
                    var startPos = message.indexOf("http://");

                    for (p = startPos; p <= message.length; p++) {
                        if (message.charAt(p) == "" || message.charAt(p) == ".") {
                            var endPos = p;
                        }
                    }

                    var finalMessage = message.substring(startPos, endPos);  //adds <a tag to make hyperlink

                    var ahref = "<a href='" + finalMessage + "'>" + finalMessage + "</a>";
                    //var lastPos = message.sbstr(message, startPos,
                    message = message.replace(finalMessage, ahref);  //replaces old message with link update

                }

                var myObj = new feedObj(service, this.type, message, link, name, date, newString);  //holds object data.  brings in variables
                pusher(combinedArray, myObj);  //refer to line 68.  injects my Obj into combined aray

            }

        });

        // get twitter
        $.getJSON("http://search.twitter.com/search.json?from=nature_valley&rpp=50&callback=?", function(json) {
            $(json.results).each(function() {
                var tTime = new Date(Date.parse(this.created_at));
                var origDate = new Date(Date.parse(this.created_at));
                if (parseInt(tTime.getHours()) > 12) {
                    var hours = parseInt(tTime.getHours()) - 12;
                }
                else {
                    var hours = tTime.getHours();
                }

                var month = tTime.getMonth();
                var minutes = tTime.getMinutes();
                if (minutes == 0)
                    minutes = "00";

                var day = tTime.getDate();

                var montharray = new Array("Jan", "Feb", "Mar", "Apr", "May", "June",
                                        "July", "Aug", "Sep", "Oct", "Nov", "Dec")

                var twDate = hours + ":" + minutes + " " + montharray[month] + " " + day;

                //var twMessage = this.text;

                var twMessage = "<span class='feedFrom'>" + "@Nature_Valley" + " " + "</span>" + this.text;

                if (twMessage != undefined) {  //detects if there is any text that should be a hyperlink
                    if (twMessage.indexOf("http://") >= 0) {
                        var startPos = twMessage.indexOf("http://");

                        for (p = startPos; p <= twMessage.length; p++) {
                            if (twMessage.charAt(p) == "" || twMessage.charAt(p) == ".") {
                                var endPos = p;
                            }
                        }

                        var finalMessage = twMessage.substring(startPos, endPos);  //adds <a tag to make hyperlink

                        var ahref = "<a href='" + finalMessage + "'>" + finalMessage + "</a>";

                        //var lastPos = message.sbstr(message, startPos,
                        twMessage = twMessage.replace(finalMessage, ahref);  //replaces old message with link update

                    }

                    var twType = "status";
                    var twService = "Twitter";

                    // twitter does not have link or name  
                    var twLink = " ";
                    var twName = " ";

                    var fdObj = new feedObj(twService, twType, twMessage, twLink, twName, origDate, twDate);  //feed Object
                    pusher(combinedArray, fdObj);

                }

            }); //end Twitter

            combinedArray.sort(function(a, b) {
                var dateA = new Date(a.date), dateB = new Date(b.date)
                return dateB - dateA //sort by date descending
            });

            for (var i in combinedArray) {
                if (combinedArray[i].service == "Twitter") {
                    $("#liveText").append("<ul><li class='feedFrom'>" + combinedArray[i].name + " " + "<span class='feedMessage'>" + combinedArray[i].value + "</span>&nbsp;<span class='feedTime'>" + combinedArray[i].origDate + " &nbsp;via " + combinedArray[i].service + "</span></li></ul>");
                    break;
                }
            }

            for (var i in combinedArray) {
                $("#liveMessages").append("<ul><li class='feedFrom'>" + combinedArray[i].name + " " + "<span class='feedMessage'>" + combinedArray[i].value + "</span></li><li class='feedTime'>" + combinedArray[i].origDate + " via " + combinedArray[i].service + "</li></ul>");

            }
        });

    }); // end facebook        
}


