//////////////////////////////////////////////////////////////////////////////////////////
//// GLOBAL VARIABLES ////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////
var new_pins = {html: "", number: 0, old_title: ""};
var followers_json = null;
var cache = {}, lastXhr;
var media_url = "http://assets.pinterest.com/";



//////////////////////////////////////////////////////////////////////////////////////////
//// CSRF & COOKIES //////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////

// Setting custom header for ajax post request to avoid csrf attacks
$('html').ajaxSend(function(event, xhr, settings) {
    function getCookie(name) {
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
    if (!(/^http:.*/.test(settings.url) || /^https:.*/.test(settings.url))) {
        // Only send the token to relative URLs i.e. locally.
        xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
    }
});

function setCookie(name,value,days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime()+(days*24*60*60*1000));
        var expires = "; expires="+date.toGMTString();
    }
    else var expires = "";
    document.cookie = name+"="+value+expires+"; path=/";
}

function getCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
}

function deleteCookie(name) {
    setCookie(name,"",-1);
}

// Grab variable from get parameters
$.extend({
    getUrlVars: function() {
        var vars = [], hash;
        var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
        for(var i = 0; i < hashes.length; i++) {
            hash = hashes[i].split('=');
            vars.push(hash[0]);
            vars[hash[0]] = hash[1];
        }
        return vars;
    },
    getUrlVar: function(name) {
        return $.getUrlVars()[name];
    }
});



//////////////////////////////////////////////////////////////////////////////////////////
//// GLOBAL FUNCTIONS ////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////

// JQuery plugin for giving an input a default value on blur/focus
(function($) {
    $.fn.extend({
        defaultValue: function(value, className) {
            $(this).focus(function() {
                if ($(this).val() == value)
                    $(this).val("");
            }).blur(function() {
                if ($(this).val() == "") {
                    $(this).val(value);
                    if (className)
                        $(this).addClass(className);
                }
            });
        }
    });
})(jQuery);

// Fixing .indexOf for IE
if(!Array.indexOf){
    Array.prototype.indexOf = function(obj){
        for(var i=0; i<this.length; i++){
            if(this[i]==obj){
                return i;
            }
        }
        return -1;
    }
};

// Check for YouTube video thumbnail
function is_video(url) {
    var re = /^http:\/\/img\.youtube\.com\/vi\/[a-zA-Z0-9\-_]+\/0\.jpg$/;
    return re.test(url);
}

// Given an element, get it's innerHTML and outerHTML
function getHTML(element) {
    var html = $(element).wrap("<div />").parent().html();
    $(element).unwrap();
    return html;
}


//////////////////////////////////////////////////////////////////////////////////////////
//// SCROLL TO TOP ///////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////

var ScrollToTop = ScrollToTop || {
    id: 'ScrollToTop',
    control: $('#' + this.id),
    setup: function() {

        var ui =
            "<a id='" + ScrollToTop.id + "' href='#' class='Button WhiteButton Offscreen Indicator'>" +
                "<strong>Scroll to Top</strong>" +
                "<span></span>" +
            "</a>";

        // Add ScrollToTop
        $('body').append(ui);

        // Get height of window on load, so we know when to show ScrollToTop
        var windowHeight = ($(window).height() / 2);

        // Watch window position, so we know when to show ScrollToTop
        $(window).scroll(function() {
            var scrollPosition = window.innerWidth ? window.pageYOffset : document.documentElement.scrollTop; // If IE, use document.Element
            if (scrollPosition >= windowHeight) {
                $('#ScrollToTop').removeClass('Offscreen');
            } else {
                $('#ScrollToTop').addClass('Offscreen');
            }
        });

        $('#ScrollToTop').click(function (event) {
            $("html, body").animate({ scrollTop: "0px" }, 400);
            return false;
        });

    }
}



//////////////////////////////////////////////////////////////////////////////////////////
//// MODAL ///////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////

var Modal = Modal || {
    setup: function() {
        // Hide modals when the escape-key is pressed
        $(document).keydown(function(e) {
            if (e.keyCode == 27) {
                var id = $('.ModalContainer:visible').attr('id');
                if (id) {
                    Modal.close(id);
                } else if ($("#zoomScroll").length) {
                    window.History.back();
                }
                e.preventDefault();
            }
        });
    },
    show: function(id) {

        var m = $('#' + id);                // .ModalContainer
        var modal = $('.modal:first', m);   // .modal

        // Turn off site scrolling
        $('body').addClass('noscroll');

        // Unhide modal, even though it's off the screen, so we can get its height
        m.show();
        var modalHeight = modal.outerHeight();

        // Prepare to position modal vertically in screen center
        modal.css('margin-bottom','-' + (modalHeight / 2) + 'px');

        // Show modal (animate up)
        setTimeout(function() {
            m.addClass('visible');
            // Removing translate, to avoid CSS bugs
            m.css('-webkit-transform','none');
        }, 1);

        return false;

    },
    close: function(id) {

        var m = $('#' + id);    // .ModalContainer

        // If we aren't zoomed, turn on site scrolling
        if ($('#zoomScroll').length === 0)
            $('body').removeClass('noscroll');

        // Hide modal (animate down)
        m.removeClass('visible');
        setTimeout(function() {
            m.hide();
            // Reapplying translate
            m.css('-webkit-transform','translateZ(0)');
        }, 251);

        return false;

    }
}



//////////////////////////////////////////////////////////////////////////////////////////
//// GLOBAL EVENT LISTENERS //////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////

$(document).ready(function(){

    // Show "Scroll to Top"
    ScrollToTop.setup();

    // Setup the listeners for modals
    Modal.setup();

    // Tooltips
    $('.tipsyHover').tipsy({ gravity:'n', delayIn: 0.1, delayOut: 0.1, opacity: 0.7, live: true, html: true });

    // Header Search
    $("#query").focus( function() {
        if (cache) $(this).catcomplete("search", $(this).val())
    });

    // Search typeahead
    $.widget( "custom.catcomplete", $.ui.autocomplete, {
        _renderMenu: function( ul, items ) {
            var self = this,
            currentCategory = "";
            $.each( items, function( index, item ) {
                if ( item.category != currentCategory ) {
                    ul.append( "<li class='ui-autocomplete-category'>" + item.category + "</li>" );
                    currentCategory = item.category;
                }
                self._renderItem( ul, item );
            });
            /* Breaks IE8. What does this do? */
            var item;
            item = {link: "/search/?q="+this.term}
            $( "<li></li>" )
              .data( "item.autocomplete", item )
              .append("<a href='/search/?q="+this.term+"' class='ui-corner-all' tabindex='-1' style='font-weight:bold; min-height:0 !important;'>Search for "+this.term+"</a>")
              .appendTo( ul );
        }
    });

    var cc = $("#query").catcomplete({
        source: function(request, response) {
            Tagging.getFriends(request, function(friends) {
                var options = friends;
                if (myboards) {
                    var filtered = tagmate.filter_options(myboards, request.term);
                    options = friends.concat(filtered);
                }
                // Show label in the text input
                for (var i = 0; i < options.length; i++)
                    options[i].value = options[i].label;
                response(options);
            });
        },
        minLength: 1,
        delay: 0,
        appendTo: "#SearchAutocompleteHolder",
        select: function(event, ui) {
            document.location.href = ui.item.link;
        }
    });

    if (typeof(cc.data("catcomplete")) != 'undefined') {
        cc.data("catcomplete")._renderItem = function(ul, item) {
            var link = "<a href='" + item.link + "'>" +
                "<img src='" + item.image + "' class='AutocompletePhoto' alt='Photo of " + item.label + "' width='38px' height='38px'/>" +
                "<span class='AutocompleteName'>" + item.label + "</span></a>";

            return $("<li></li>")
                .data("item.autocomplete", item)
                .append(link)
                .appendTo(ul);
        };
    }

    $("#query").defaultValue("Search", "default_value");
    $("#Search #query_button").click(function() {
        $("#Search form").submit();
        return false;
    });
});
