//google.load("maps", "2");


function showMap(map_id, lat, lng) {
    if (GBrowserIsCompatible()) {
        var map = new GMap2(document.getElementById(map_id));
        var center = new GLatLng(lat, lng)
        var marker = new GMarker(center, {
            draggable: false
        });

        map.setCenter(center, 16);
        map.addOverlay(marker);

        var customUI = map.getDefaultUI();
        customUI.maptypes.normal = true;
        customUI.controls.smallzoomcontrol3d = true;
        customUI.controls.maptypecontrol = false;
        customUI.controls.menumaptypecontrol = false;

        map.setUI(customUI);

    }
}

function showMessage(type, message, timeout, id) {
    /*
       fields marked with * are required
       TODO: add css option and 0 timeout time to keep the message
     
     * type     (str) alert, warning, info or success
     * message  (str) the message to be displayed, with html formatting
       timeout  (int) how long the message should be displayed (ms)
       id       (str) which element in the DOM will receive the message
     */
     
     if (timeout == undefined) { timeout = 5000; }
     if (id == undefined) { id = "#message"; }
     
     $(id).hide().removeClass().addClass(type).slideDown().html(message);
     
     setTimeout(
       function() { $(id).slideUp(); },
       timeout
       );
}

function hideMessage(id) {
     if (id == undefined) { id = "#message"; }
     $(id).slideUp();
}


function hoverEffect(id, leftPx, topPx, divPadding) {
    /*
      id        (str) name of the css #id to which the effect should be applied
      leftPx    (int) distance in pixels from the left side of the id'd element
      topPx     (int) distance in pixels from the top side of the id'd element
    */

    $(id).append("<div class=\"hoverEffect\"><p></p></div>");

    $(id).hover(function () {

        $("div.hoverEffect").css({
            "left": leftPx + "px"
        });
        $(this).find("div.hoverEffect").css({
            "left": leftPx + "px"
        }).animate({
            opacity: "show",
            top: topPx + "px"
        }, "slow");
        var hoverText = $(this).attr("title");

        if (divPadding) {
            $(this).find("div.hoverEffect").css({
                "padding": divPadding
            });
        }
        $(this).find("div.hoverEffect p").text(hoverText);
    },

    function () {
        bottomPx = topPx + 10;
        $(this).find("div.hoverEffect").animate({
            opacity: "hide",
            top: bottomPx + "px"
        }, "fast");
    });
}
// function resizeProfileActivity(current, next, options) {
//   var index = options.currentSlide;
//   // alert(current.value);
// }
$(document).ready(function () {
    $(".slideshow").cycle({ /* more options in http://jquery.malsup.com/cycle/ */
        delay: 2000,
        timeout: 4000,
        speed: 500,
        pause: 0
    });
    $("#parcerias #slideshow").cycle({
        delay: 2000,
        timeout: 4000,
        speed: 1000,
        pause: 1
    });
    $("#profileslider").cycle({
        delay: 0,
        timeout: 8000,
        prev: ".previous_profile",
        next: ".next_profile",
        speed: 350,
        pause: 1//,
        // after: resizeProfileActivity
    });
    $("input.jQuery_form").click(function () {
        if (this.value == this.defaultValue) {
            this.value = "";
        }
    });
    $("input.jQuery_form").blur(function () {
        if ($.trim(this.value) == "") {
            this.value = this.defaultValue;
        }
    });

    /* profile slidkers */

    $(".accordion").accordion({
        autoHeight: false,
        animated: 'animated'
    });
    $("#accordionResizer").resizable({
        resize: function () {
            $("#accordion").accordion("resize");
        },
        minHeight: 400
    });
   
    $(".ajax-loader").live("click", function () {
        // TOOD: create a "be the first to comment." message for entries with no comments.
        showMessage("alert", "<p>Carregando comentários... Aguarde um instante, por favor.</p>")
        $.ajax({
            type: "GET",
            url: "/profiles/activity/" + $(this).attr('id'),
            dataType: 'json',
            success: function(data) {
                         hideMessage();
                         var dataToAppend = '<h2>' + data.question.title + '</h2>';
                         if (data.comments != "") {
                         $.each(data.comments, function(i, comment) {                           
                           dataToAppend += '<div class="comment" id="comment_' + comment.id + '">'
                                         + '<img src="' + comment.user.avatar + '" ' + 'class="avatar_thumb" alt="Avatar" />'
                                         + '<p class="author"><a href="' + comment.user.url + '">' + comment.user.name + '</a> said:</p>'
                                         + '<p class="text"><a href="' + data.question.url + '">' + comment.comment + '</a></p></div>'
                         });
                         }
                         else {
                           dataToAppend += '<div class="comment"><p class="nopad">Ainda sem comentários? <a href="' + data.question.url + '#question">Então dê sua opinião.</a></p></div>' 
                         }
                         $("#commentwrapper").html("").append(dataToAppend);
            }
        });
        return false;
    });
    
    $("#question_list").append('<div class="button enabled" id="load_questions"><span class="5"><a href="#">Ver mais perguntas</a></span></div>');
    $("#load_questions.enabled").click(function(){
      var index = $(this).find("span").attr("class");
      showMessage("alert", "<p>Carregando perguntas... Aguarde um instante, por favor.</p>")
      $(this).attr("class", "button disabled");
        $.ajax({
            type: "GET",
            url: "/profiles/activity/",
            dataType: 'json',
            data: {
              'index': index
            },
            success: function(object) {
              hideMessage(); 
              var newindex = object.index + 5;
              var dataToAppend = "";
                $.each(object.entries, function(i, entry) {
                  dataToAppend += '<li><a href="/profiles/activity/' + entry[0] + '" class="ajax-loader" id="' + entry[0] + '">' + entry[1] + "</a></li>"
                });
              $("#question_list ul").append(dataToAppend);
              $("#load_questions span").attr("class", newindex.toString());
            }
        });
        return false;
    })
    
    /* sign-in dropdown */
    $(".signin").click(function (e) {
        e.preventDefault();
        $("fieldset#signin_menu").toggle();
        $(".signin").toggleClass("menu-open");
    });

    $("fieldset#signin_menu").mouseup(function () {
        return false
    });
    $(document).mouseup(function (e) {
        if ($(e.target).parent("a.signin").length == 0) {
            $(".signin").removeClass("menu-open");
            $("fieldset#signin_menu").hide();
        }
    });
    $('#message').click(function() {
      $(this).slideUp();
    });
    $("#contatoSubmit").click(function () {
        $('#message').hide().removeClass().addClass('alert').slideDown().html("<p>Processando formulário... por favor aguarde.</p>");
        $.ajax({
            type: "POST",
            url: "/contato/",
            dataType: 'json',
            data: $('#contact_form').serialize(),
            success: function(data) {
                var error = data.error;
                var message = data.message;
                if (error == 'true') {
                    $('#message').hide().removeClass().addClass('warning').slideDown().html("<p>" + data.message + "</p>");
                }
                
                else {
                    $('#message').hide().removeClass().addClass('success').slideDown().html("<p>" + data.message + "</p>");
                    setTimeout(function(){
                      $('#message').slideUp();
                    }, 5000);                    
                }
            }
        });
        return false;
    });

    $("#mapbox").dialog({
      autoOpen: false,
      closeOnEscape: true,
      modal: true,
      zIndex: 3999,
      resizable: false,
      
      show: "fade",
      hide: "fade",
      
      open: function(event, ui) {
          var height = $(window).height();
          var width = $(document).width();
        
          $(this).css({
              'left' : width/2 - ($(this).width() / 2) - 20,
              'top' : height/2 - ($(this).height() / 2), 
              'z-index' : 1500
          });        
      }
    });
    
    $("#mapbox").click(function() {
      $("#mapbox").dialog("close");
    });    
    $("#mapbox_opener").click(function() {
      $("#mapbox").dialog("open");
    });
    
});

