//Add This Config
var addthis_config = {
    ui_click: true,
    ui_offset_top: -15,
    ui_offset_left: 0
}
jQuery.fn.addEvent = jQuery.fn.bind;

function ExternalLinks(){
	$("a[rel*='external']").each(function(i){
		$(this).attr("target", '_blank');
	});
}

function SmoothScroll() {
    $('.scroll').click(function() {
        if (location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '')
                && location.hostname == this.hostname) {
            var $target = $(this.hash);
            $target = $target.length && $target
                    || $('[name=' + this.hash.slice(1) + ']');
            if ($target.length) {
                var targetOffset = $target.offset().top;
                $('html,body')
                        .animate({scrollTop: targetOffset}, 1000);
                return false;
            }
        }
    });
}

//Main nav drop down
function DropDownMenu() {

    $("li.has-subnav").hover(function () {
        $("li.has-subnav").removeClass('subnav-active');
        $(this).addClass('subnav-active');
        Cufon.refresh();
    },
                            function () {
                                $(this).removeClass('subnav-active');
                                Cufon.refresh();
                            });
}

function SocialToolTip() {

    var label
    $('#social li').each(function(i) {
        label = $(this).children('a').attr('title');
        $(this).append('<span style="display:none;">' + label + '</span>');
        $(this).children('a').removeAttr('title');
    });

    Cufon.refresh();

    $('#social li a').hover(function() {
        $(this).siblings('span').fadeIn();
    },
                           function () {
                               $(this).siblings('span').fadeOut();
                           });
}

function EventToolTip() {

    var label
    $('.calendarDates a').each(function(i) {
        label = $(this).attr('title');
        $(this).append('<span style="display:none;">' + label + '</span>');
        $(this).removeAttr('title');
    });

    $('.calendarDates a').hover(function() {
        $(this).children('span').fadeIn();
        },
       function () {
           $(this).children('span').fadeOut();
       });
}

function HomepageCarousel() {

    //Text for each slide for the navigation
    var titleArray = [];
    $('#banners li').each(function(index) {
        titleArray.push($(this).find('img').attr('alt'));
    });
    $('#banners').after('<ul id="bannerNav"></ul>');

    var slideCounter = $('#banners li').size(); // For counter in navigation (hidden from view)
    $("#banners li:not(:first) a").attr("tabIndex", "-1"); //Stop user tabbing through each slide - only the current

    $("#banners").carouFredSel({
        width: 610,
        height: 300,
        items: {
            visible: 1,
            minimum: 1,
            width: 610,
            height: 300
        },
        scroll: {
            pauseOnHover: true,
            duration: 800,
            easing: "easeInOutExpo",
            onBefore: function(oldItems, newItems) {
                oldItems.children('a').attr("tabIndex", "-1");
                newItems.children('a').removeAttr("tabIndex");
            }
        },
        pagination: {
            container: "#bannerNav",
            anchorBuilder: function(nr) {
                var str = '<li>';
                str += '<a href="#">';
                str += titleArray[nr - 1];
                str += ' <span>';
                str += '(Slide' + ' ' + nr + ' ' + 'of' + ' ' + slideCounter + ')';
                str += '</span>';
                str += '</a>';
                str += '</li>';
                return str;
            }
        }
    });
}

function relTime(time_value) {
    time_value = time_value.replace(/(\+[0-9]{4}\s)/ig, "");
    var parsed_date = Date.parse(time_value);
    var relative_to = (arguments.length > 1) ? arguments[1] : new Date();
    var timeago = parseInt((relative_to.getTime() - parsed_date) / 1000);
    if (timeago < 60) return 'less than a minute ago';
    else if (timeago < 120) return 'about a minute ago';
    else if (timeago < (45 * 60)) return (parseInt(timeago / 60)).toString() + ' minutes ago';
    else if (timeago < (90 * 60)) return 'about an hour ago';
    else if (timeago < (24 * 60 * 60)) {
        var hours = (parseInt(timeago / 3600));
        var plural = '';
        if (hours > 1) {
            plural = 's';
        }
        return 'about ' + hours.toString() + ' hour' + plural + ' ago';
    }
    else if (timeago < (48 * 60 * 60)) return '1 day ago';
    else return (parseInt(timeago / 86400)).toString() + ' days ago';
}

function urlToLink(text) {
    var exp = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;
    return text.replace(exp, "<a href='$1'>$1</a>");
}

function PopulateTwitterFeed() {
    $.getJSON("http://twitter.com/statuses/user_timeline.json?screen_name=climategroup&count=20&callback=?",
             function(tweetdata) {
                 var index = 0;
                 var tweetlist = $("#twitter_update_list");
                 tweetlist.empty();
                 $.each(tweetdata,
                       function(i, tweet) {
                           var content = "";
                           if (index < 4) {

                               content = content + ('<li>');
                               content = content + ('<span>' + urlToLink(tweet.text) + '</span>');
                               content = content + ('<a style="font-size: 85%" href="http://twitter.com/ClimateGroup/statuses/' + tweet.id_str + '">' + relTime(tweet.created_at) + '</a>')
                               content = content + ('</li>');

                               tweetlist.append(content);
                           }

                           index++;
                       }
                         )
             }
            );
}

function MembersSlideshow() {

    $(".memberShowcase ul").carouFredSel({
        width: 284,
        height: 200,
        items: {
            visible: 1,
            width: 284,
            height: 200
        },
        scroll: {
            easing: "easeInOutExpo",
            duration: 600,
            pauseOnHover: true
        }
    });
}

function attachPublicationSortBy() {
    $('#sortbytitle').click(function(e) {
        e.preventDefault();
        updatePublicationList("title");
    });

    $('#sortbydate').click(function(e) {
        e.preventDefault();
        updatePublicationList("date");
    });
}
function updatePublicationList(sortBy) {

    $.ajax({
        url: "/publication/sort-by/",
        data: "sortby=" + sortBy,
        type: "GET",
        success: function(data) {
            loadPublicationList(data);
        }
    });
}

function loadPublicationList(data) {
    $('#ajaxpublicationList').replaceWith(data);
    attachPublicationSortBy();
}

$(document).ready(function() {

    ExternalLinks();
    SmoothScroll();
    DropDownMenu();
    if ($('#banners').length > 0) {
        HomepageCarousel();
    }
    ;
    if ($('#social').length > 0) {
        SocialToolTip();
    }
    ;
    if ($('.memberShowcase ul').length > 0) {
        MembersSlideshow();
    }
    ;
//    if ($('#calendarContainer').length > 0) {
//        //EventToolTip();
//    }
    ;

    //Print
    $(".print a, a.print").click(function() {
        window.print();
    });

    $("#tabs").tabs();
    $(".accordion").accordion({
        active: false,
        autoHeight: false,
        collapsible: true
    });

    var volatile = $(".search input[type=text]")
    volatile.focus(function(event) {
        if ($(this).val() == $(this).attr("title")) {
            $(this).val("");
        }
    }, volatile.blur(function(event) {
        if ($(this).val() == "") {
            $(this).val($(this).attr("title"));
        }
    }
            ));

    //Selectmemu
    $('.hd select, .searchHeader select').selectmenu();

    //Twitter Pod
    if ($('#twitter_div').length > 0) {
        PopulateTwitterFeed();
    }
    /*
     if ($('#twitter_div').length > 0) {
     var script = document.createElement('script');
     script.src = 'http://twitter.com/javascripts/blogger.js';
     script.type = 'text/javascript';

     var script2 = document.createElement('script');
     script2.src = 'http://twitter.com/statuses/user_timeline/climategroup.json?callback=twitterCallback2&count=3';
     script2.type = 'text/javascript';

     document.getElementsByTagName('head')[0].appendChild(script);
     document.getElementsByTagName('head')[0].appendChild(script2);
     }
     */


    // publications sorting
    attachPublicationSortBy();

    //Iframe
    $('.iframe').click(function(e) {
        e.preventDefault();
        var $this = $(this);

        //Define Dialog Width/Height if custom
        if ($this.attr('rel')) {
            var dialogDimensions = $this.attr('rel').split("x");
            var dialogWidth = dialogDimensions[0]
            var dialogHeight = dialogDimensions[1]
        }
        else {
            var dialogWidth = 653
            var dialogHeight = 500
        }

        //Fix for STAF as the title uses the "title" attr and the tooltip removes this on load.
        if ($this.parent().hasClass('staf')) {
            var dialogTitle = 'Send to a friend'
        }
        else {
            var dialogTitle = 'External Site'
        }

        $('<div><iframe class="externalSite" width="100%" height="100%" frameborder="0" src="' + this.href + '" /></div>').dialog({
            title: ($this.attr('title')) ? $this.attr('title') : dialogTitle,
            width: dialogWidth + "px",
            height: dialogHeight,
            close: function(event, ui) {
                $(this).dialog("destroy");
                $(".externalSite").remove();
                $(".ui-widget-overlay").remove();
            }
        });

        $(".ui-dialog").has('iframe').before("<div class='ui-widget-overlay'></div>");

        function dialogOverlayResize() {
            $(".ui-widget-overlay").css("height", $(document.body).height() + "px").css("width", $(document.body).width() + "px").css("z-index", "1001");
        }

        $(window).resize(function() {
            dialogOverlayResize();
        });
        dialogOverlayResize();

    });

    //Event Calendar
    var eventDate = new Date();
    var eventDateNext = new Date();
    eventDateNext.setMonth(eventDate.getMonth() + 1);

    if ($("#calendarContainer")) {
        $("#lastMonth").click(function(e) {
            eventDate.setMonth(eventDate.getMonth() - 1);
            updateCalendar(eventDate, "Prev");

            eventDateNext.setMonth(eventDateNext.getMonth() - 1);
            updateCalendar(eventDateNext, "Next");
        });

        $("#nextMonth").click(function(e) {
            eventDate.setMonth(eventDate.getMonth() + 1);
            updateCalendar(eventDate, "Prev");

            eventDateNext.setMonth(eventDateNext.getMonth() + 1);
            updateCalendar(eventDateNext, "Next");
        });

        updateCalendar(eventDateNext, "Next");
    }

    function updateCalendar(d, tableEx) {

        var monthNames = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
        $.ajax({
            url: "/event/calendar-pod/",
            data: "month=" + d.getMonth() + "&year=" + d.getFullYear() + "&ajax=true",
            type: "GET",
            success: function(data) {
                $("#calendarTable" + tableEx).html(data);
                $("#currentMonth" + tableEx).html(monthNames[d.getMonth()] + " " + d.getFullYear());
                if (tableEx == 'Next') {
                    EventToolTip();
                }
            }
        });
    }
});

