jQuery(document).ready(function () {
    if (jQuery('#tipsOfTheDayWrapper').length) hasEmilesTips();
    if (jQuery('#webBWrapper').length) hasWebB();
    if (jQuery('#activityWrapper').length) hasMemberActivities();
    if (jQuery('#mcountertitleWrapper').length) hasPointsCounter();
});

function hasEmilesTips() {
    jQuery.getJSON(document.location.protocol + '//twitter.com/statuses/user_timeline.json?screen_name=emiles_tips&count=6&trim_user=true&callback=?', function(data) {
        if (data != null) {
            if (data.length > 0)
                jQuery("#tipsOfTheDayWrapper").css("display", "block");

            for (i=0; i<data.length; i++) {
                var text = linkify(data[i].text);
                jQuery('#tipsOfTheDay').append(
                    '<div class="sidebarBoxItem">'+text+'</div>'
                );
            }
        }
    });
}

function hasWebB() {
    jQuery(".webBShortDescription").each(function() {
        if (jQuery(this).text().length > 25) {
            jQuery(this).text(jQuery(this).text().substr(0, 25));
            jQuery(this).append("...");
        }
        jQuery(this).css("display", "block");
    });

    jQuery("#webBTextExpand").click(function(){
        if (!webBExpanded) {
            webBExpand();
        } else {
            webBUnexpand();
        }
        return false;
    });

    jQuery("#webBExpand").click(function(){
        if (!webBExpanded) {
            webBExpand();
        } else {
            webBUnexpand();
        }
        return false;
    });

    jQuery("#webBWrapper").mouseleave(function(){
        if (webBExpanded) {
            webBUnexpand();
        }
    });
}

function hasMemberActivities() {
    showActivity();
}

function hasPointsCounter() {
    showTotalMiles(1);
}

function linkify(string) {  
    string = string.replace(  
        /((https?\:\/\/)|(www\.))(\S+)(\w{2,4})(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/gi,  
        function(url){  
            var full_url = url;  
            if (!full_url.match('^https?:\/\/')) {  
                full_url = 'http://' + full_url;  
            }  
            return '<a href="' + full_url + '" target="_blank">' + url + '</a>';  
        }  
    );  

    return string;  
}  

function getApiUrl() {
    if (document.location.protocol == 'https:') {
        return 'https://api.e-miles.com';
    } 

    return 'http://api.e-miles.com';
}

function showTotalMiles(firstTime) {
   jQuery.getJSON(getApiUrl() + '/v1/activity/points?callback=?', function(data) {
       if (data != null) {
           var niceNumber = "";
           if ((data.point != undefined) && !isNaN(data.point)) {
               niceNumber = data.point.toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1,");
           }

           if (firstTime == 1) {
               jQuery("#mcountertitleWrapper").css("display", "block");
               jQuery('#totalMilesContent').html(niceNumber);
           } else {
               jQuery('#totalMilesWrapper').slideUp('fast', function() { 
                   jQuery('#totalMilesContent').html(niceNumber); 
               });
               jQuery('#totalMilesWrapper').slideDown('slow');
           }

           setTimeout("showTotalMiles(0)", 30000);
       }
    });
}

function showActivity() {
    jQuery.getJSON(getApiUrl() + '/v1/activity?callback=?', function(data) {
        if (data != null) {
            jQuery('#activityContent').html("");
            if (data.length > 0)
                jQuery("#activityWrapper").css("display", "block");

            for (i=0; i<data.length; i++) {
                if (data[i].activity == 'redeem') {
                    jQuery('#activityContent').append(
                        '<div class="sidebarBoxItem" style="display: none;"><b>'+data[i].firstName+' '+data[i].lastName+'</b> deposited <b>'+
                        data[i].point+' miles</b> '+data[i].timeMessage+' ago.</div>'
                        );
                } else if (data[i].activity == 'enroll') {
                    jQuery('#activityContent').append(
                        '<div class="sidebarBoxItem" style="display: none;"><b>'+data[i].firstName+' '+data[i].lastName+'</b> enrolled '+
                        data[i].timeMessage+' ago. Welcome, <b>'+data[i].firstName+' '+data[i].lastName+'</b>!</div>'
                        );
                } else if (data[i].activity == 'donate') {
                    jQuery('#activityContent').append(
                        '<div class="sidebarBoxItem" style="display: none;"><b>'+data[i].firstName+' '+data[i].lastName+
                        '</b> just made a donation '+ data[i].timeMessage+' ago.</div>'
                        );
                }
            }

            for (i=0; i<3; i++) {
                jQuery("#activityContent>div:hidden:last").slideDown("fast");
            }
            showActivityItem()
        }
    });
}

function showActivityItem(item) {
    if (jQuery("#activityContent>div:hidden:last").is(":hidden")) {
        jQuery("#activityContent>div:hidden:last").slideDown("slow");
        setTimeout("showActivityItem()", 4500);
    } else {
        if(jQuery('#activityContent > div').size() > 6) {
            showActivity();
        } else {
            setTimeout("showActivity()", 15000);
        }
    }
}

var webBExpanded = false;

function webBExpand() {
    jQuery("#webBWrapper").animate({ width: "530" }, { queue: true, duration: 250 })
    jQuery(".webBShortDescription").css("display", "none");
    jQuery("#expandIcon").attr("class", "ui-icon ui-icon-circle-arrow-w");
    jQuery("#mainContentRight").fadeTo('fast', .2);
    webBExpanded = true
}

function webBUnexpand() {
    jQuery("#webBWrapper").animate({ width: "188" }, { queue: true, duration: 200 })
    jQuery(".webBShortDescription").css("display", "block");
    jQuery("#expandIcon").attr("class", "ui-icon ui-icon-circle-arrow-e");
    jQuery("#mainContentRight").fadeTo('fast', 1);
    webBExpanded = false;
}

