document.documentElement.className += 'js_active'; 
function str_replace (search, replace, subject, count) {
    // http://kevin.vanzonneveld.net
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Gabriel Paderni
    // +   improved by: Philip Peterson
    // +   improved by: Simon Willison (http://simonwillison.net)
    // +    revised by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
    // +   bugfixed by: Anton Ongson
    // +      input by: Onno Marsman
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +    tweaked by: Onno Marsman
    // +      input by: Brett Zamir (http://brett-zamir.me)
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   input by: Oleg Eremeev
    // +   improved by: Brett Zamir (http://brett-zamir.me)
    // +   bugfixed by: Oleg Eremeev
    // %          note 1: The count parameter must be passed as a string in order
    // %          note 1:  to find a global variable in which the result will be given
    // *     example 1: str_replace(' ', '.', 'Kevin van Zonneveld');
    // *     returns 1: 'Kevin.van.Zonneveld'
    // *     example 2: str_replace(['{name}', 'l'], ['hello', 'm'], '{name}, lars');
    // *     returns 2: 'hemmo, mars'

    var i = 0, j = 0, temp = '', repl = '', sl = 0, fl = 0,
    f = [].concat(search),
    r = [].concat(replace),
    s = subject,
    ra = r instanceof Array, sa = s instanceof Array;
    s = [].concat(s);
    if (count) {
        this.window[count] = 0;
    }

    for (i=0, sl=s.length; i < sl; i++) {
        if (s[i] === '') {
            continue;
        }
        for (j=0, fl=f.length; j < fl; j++) {
            temp = s[i]+'';
            repl = ra ? (r[j] !== undefined ? r[j] : '') : r[0];
            s[i] = (temp).split(f[j]).join(repl);
            if (count && s[i] !== temp) {
                this.window[count] += (temp.length-s[i].length)/f[j].length;
            }
        }
    }
    return sa ? s : s[0];
}
get_relative_timestamp = function(timestamp) {
    var c = new Date();
    var t = iso2date(timestamp);

    var d = c.getTime() - t.getTime();
    var dY = Math.floor(d / (365 * 30 * 24 * 60 * 60 * 1000));
    var dM = Math.floor(d / (30 * 24 * 60 * 60 * 1000));
    var dD = Math.floor(d / (24 * 60 * 60 * 1000));
    var dH = Math.floor(d / (60 * 60 * 1000));
    var dN = Math.floor(d / (60 * 1000));

    if (dY > 0)   {
        return dY === 1? "1 year ago"   : dY + " years ago";
    }
    if (dM > 0)   {
        return dM === 1? "1 month ago"  : dM + " months ago";
    }
    if (dD > 0)   {
        return dD === 1? "1 day ago"    : dD + " days ago";
    }
    if (dH > 0)   {
        return dH === 1? "1 hour ago"   : dH + " hours ago";
    }
    if (dN > 0)   {
        return dN === 1? "1 minute ago" : dN + " minutes ago";
    }
    return "less than a minute ago";
};

// from http://delete.me.uk/2005/03/iso8601.html
iso2date = 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();
    var time = (Number(date) + (offset * 60 * 1000));
    var result = new Date();
    result.setTime(Number(time));
    return result;
}

// If jQuery is included in the page, adds a jQuery plugin to handle it as well
if ( typeof jQuery != "undefined" )
    jQuery.fn.prettyDate = function(){
        return this.each(function(){
            var date = get_relative_timestamp($(this).attr('title'));
            if ( date )
                $(this).text( date );
        });
    };

jQuery.fn.extend({
    highlight: function(search, insensitive, hls_class){
        var regex = new RegExp("(<[^>]*>)|(\\b"+ search.replace(/([-.*+?^${}()|[\]\/\\])/g,"\\$1") +")", insensitive ? "ig" : "g");
        return this.html(this.html().replace(regex, function(a, b, c){
            return (a.charAt(0) == "<") ? a : "<strong class=\""+ hls_class +"\">" + c + "</strong>";
        }));
    }
});
$(document).ready(function(){
     $('#content').addClass($('.filter:checked').val());
    $('.filter').click(function(){
        $cont = $('#content');
        $cont.removeClass();
        $cont.addClass($(this).val());
    })
    var SEARCH_URL = "http://graph.facebook.com/search?callback=?";
    var TEMPLATE = '<div class="search-post parent-{GENDER}" id="{ID}">\
                    <div class="profile-image  rounded" style="float:left">\
                        <a href="http://www.facebook.com/profile.php?id={FROM.ID}" title="{FROM.NAME}">\
                            <img class="rounded" src="http://graph.facebook.com/{FROM.ID}/picture?type=normal" alt="{FROM.NAME}"/>\
                        </a><div class="shine"></div>\
                    </div>\
                    <div class="user-content ">\
                        <h2><a href="http://www.facebook.com/profile.php?id={FROM.ID}" title="{FROM.NAME}" class="gender-{GENDER}">{FROM.NAME}</a></h2>\
                        <p><span class="message">{MESSAGE}</span>\
                        <small title="{CREATED_TIME}"></small>\
                        </p>\
                     </div>\
                    <div class="clear"></div>\
                </div>';
    var LOADMORETEMPLATE = '<div id="more-box">\
                    <a href="#more" id="more-box-a" title="Load More">Load More</a>\
                </div>';
    $('#search').click(function(){
        query = $('#q').val();
        if(query==''){
            return false;
        }else{
            getData();
             $('#content').html('');
        $('#search').attr({
            value:'Loading'
        });
        $('#load-more-wrap').html('');
        }
        return false;
    });
    getData = function(){
       
        $.ajax({
            url: SEARCH_URL,
            dataType: 'json',
            data: ({
                q:query,
                type:'post'
            }),
            success: getDataCallback
        });

    }
    getDataCallback = function(items){
        
        if(items.data!=''){
            scrollId = items.data[0].id;
            var userids = $.map(items.data,function(user){
                if(user.from!=null)
                {
                    return user.from.id;
                }
            });
            var uURL = 'http://graph.facebook.com/?callback=?';
            $.ajax({
                
            data:{ids:userids.join(','),type:'post'},
            url: uURL,
            dataType: 'json',
            success: function(users){
                $.each(items.data, function(i, item){
                if(item.message!=undefined&&item.from!=null){

                    templateIs = str_replace(['{FROM.ID}','{FROM.NAME}','{MESSAGE}','{CREATED_TIME}','{ID}','{GENDER}'],
                        [item.from.id, item.from.name, item.message, item.created_time, item.id, users[item.from.id].gender], TEMPLATE);
                    $('#content').append(templateIs).find('.search-post:last');



                    $('.user-content p:last').highlight(query, 1, 'hls rounded');
                    $('.user-content p:last span.message').expander( {
  slicePoint:       200,      // the number of characters at which the contents will be sliced into two parts.
                              // Note: any tag names in the HTML that appear inside the sliced element before
                              // the slicePoint will be counted along with the text characters.
  widow:            4,        // a threshold of sorts for whether to initially hide/collapse part of the element's contents.
                              // If after slicing the contents in two there are fewer words in the second part than
                              // the value set by widow, we won't bother hiding/collapsing anything.
  expandText:       '[read more...]',   // text displayed in a link instead of the hidden part of the element.
                              // clicking this will expand/show the hidden/collapsed text
  expandPrefix:     '… ', // text to come before the expand link
  collapseTimer:    0,        // number of milliseconds after text has been expanded at which to collapse the text again
  expandEffect:     'fadeIn',
  expandSpeed:      '',       // speed in milliseconds of the animation effect for expanding the text
  userCollapse:     true,     // allow the user to re-collapse the expanded text.
  userCollapseText: '[read less...]',  // text to use for the link to re-collapse the text
  userCollapsePrefix: ' '
});

                    $('small:last').prettyDate();

                }

});
$.scrollTo($('#'+scrollId),1000);
            $('#search').attr({
                value:'Search'
            });

            if(items.paging.next!=undefined){
                createLoadMore(items.paging.next);
            }else{
                $('#load-more-wrap').html('')
            }
            }
        });

 /*  
            */
          
            
        }
        else{
             $('#search').attr({
                value:'Search'
            });
            //$('#content').html('Please enter something common!');
        }
    
    }
    getMoreData = function(sUrl){

        $.ajax({
            url: sUrl,
            dataType: 'json',
            success: getDataCallback
        });

    }

    createLoadMore = function(paging){
        nextPageUrl = paging+"&callback=?";
        $('#load-more-wrap').html(LOADMORETEMPLATE);
        $('#more-box-a').click(function(){
            getMoreData(nextPageUrl);
            $(this).parent().html('<a href="#loading">Loading..</a>');
            $(this).remove();
            return false;
        }).html('Load More');
    }
});

