//Date.format = 'yyyy-mm-dd';
jQuery.fn.autoscroll = function() {
    $('html,body').animate({scrollTop: this.offset().top}, 500);
};
function toggle_comment_form(id){
    var cform = $('#comment_form_' + id);
    if(cform.hasClass('hidden')) {
        cform.prev().text("Stop Replying to This Post");
        cform.slideDown();
    }
    else {
        cform.prev().text("Reply to This Post");
        cform.slideUp();
    }
    cform.toggleClass('hidden');
}
var current_inline_div;
/*
 * works by name convention of markup around an editable field
 * eg. the 'city' field in the sidebar/is_me.html
 <li>City:
   <span class="inline_field" id="city_edit_div">
     <span id="city_edit_span" alt="which city?">{{ profile.city }}</span>
     <a href="#" id="city_edit" class="inline_edit" alt="change city">(+)</a>
   </span>
 </li>
 * the <a class="inline_edit"> marks this as an editable field
 * the id="city_edit" is used to find the containing city_edit_div and 
 * city_edit_span for sending the value of the span and hiding the 
 * containing city_edit_div when the input field is displayed
 * field_name parameter is set from the id before the first underscore ie. 'city'
 * 
*/
function add_inline_editor(link_id, field_id, div_id) {
  /* 
  link_id is the <a> that displays the inline edit form
  field_id is the id that gets updated with the 'content' of the response
  div_id is the div that is hidden while the inline form is displayed
  */
  //console.log('adding inline editor for: ' + link_id);
  $('#'+link_id).bind('click', function() {
    $('.inline_field').show(); // need to show all in case of clicking 'edit' links without cancelling
    // hide the display value of the field being edited
    $('#'+div_id).hide();
    // store a reference to the element that's been hidden so we can show it again
    current_inline_div = $('#'+div_id);
    // insert form into dom at the parent of the div_id
    $('#'+div_id).after($('#inline_editor_id'));
    $('#inline_editor_id').show();
    // set field_name on generic form to current link
    field_name = link_id.split('_', 1);
    //$('#field_input_id').attr('value', $('#'+field_id).text()).focus().select();
    // choose an intial value for the input field and select all
    // if there's already text in the field span, prepare it for editing
    // use the 'alt' attribute of the field span if it is not empty
    var initial_value = ('' == $('#'+field_id).text()) ? ($('#'+field_id).attr('alt')) : ($('#'+field_id).text());
    $('#field_input_id').attr('value', initial_value).focus().select();
    // handle 'escape' key to cancel the inline editor
    $('#field_input_id').bind('keydown', function(event) {
      if (event.keyCode == 27) {
        $('#inline_editor_id').hide();
        current_inline_div.show();
      }
    });
    $('#field_name_id').attr('value', field_name); // set for form submission
    return false;
  });
}

$(function() {
  /* cancel on generic form */
  $('#inline_editor_cancel').bind('click', function() {
    $('#inline_editor_id').hide();
    current_inline_div.show();
    return false;
  });
  /* add inline_editor for each element with class="inline_edit" */
  $('.inline_edit').each(function(index, obj) {
    var id = this.id;
    if (id != '') {
      add_inline_editor(id, id+'_span', id+'_div');
    }
  });
  /* setup generic inline editor form */
  $('#inline_form_id').bind('submit', function() {
    $('#inline_editor_id').hide();
    current_inline_div.show();
    $(this).ajaxSubmit({
      dataType: 'json',
      success: function(data) {
        // set the nominated element with the specified content
        if (data['status'] == 'ok') {
          $('#' + data['id']).empty().append(data['content']);
          $('#errors').empty();
        } else {
          // display error text
          $('#errors').empty().append('<li>' + data['message'] + '</li>');
        }
      },
      error: function(request, status, error) {
        //console.log(status);
      }
    });
    return false;
  });
  /* handle inline editing of profile.sphere select */
  //$('#main_sphere_input_id').bind('change', function() {
  $('#main_sphere_input_form_id').bind('submit', function() {
    $('#sphere_input_div').hide();
    $('#sphere_display_div').show();
    $('#main_sphere_input_form_id').ajaxSubmit({
      dataType: 'json',
      success: function(data) {
        // set the nominated element with the specified content
        if (data['status'] == 'ok') {
          //var sphere_name = $('#main_sphere_input_id :selected').text();
          // get the display text from the json response.
          $('#' + data['id']).empty().append(data['sphere']);
          $('#errors').empty();
        } else {
          // display error text
          $('#errors').empty().append('<li>' + data['message'] + '</li>');
        }
      },
      error: function(request, status, error) {
        //console.log(status);
      }
    });
    return false;
  });
  /*
    var profile_avatar = $('#profile_avatar');
    if(profile_avatar) {
        profile_avatar.bind('mouseenter', function() {
            $('#avatar_replace').css('display', 'block');
        }).bind('mouseleave', function() {
            $('#avatar_replace').css('display', 'none');
        });
    }*/
    /*
    var ymap = document.getElementById('ymap');
    if(ymap) {
        var map = new YMap(ymap);
        // Add map type control  
        map.addTypeControl();  
        // Add map zoom (long) control  
        map.addZoomLong();  
        // Add the Pan Control  
        map.addPanControl();
        for(var i = 0; i < _geo.length; ++i) {
            var g = _geo[i];
            var yPoint = new YGeoPoint(g[0], g[1]);
            // Display the map centered on a geocoded location
            map.drawZoomAndCenter(yPoint, 12);
            // Create a new marker for an address
            var myMarker = new YMarker(yPoint);
            // Create some content to go inside the SmartWindow
            var myMarkerContent = g[2];
            // When the marker is clicked, show the SmartWindow
            YEvent.Capture(myMarker, EventsList.MouseClick, function() {
                myMarker.openSmartWindow(myMarkerContent); 
            });
            // Put the marker on the map
            map.addOverlay(myMarker);
            var pageLink = document.getElementById('loc_' + i);
            if(pageLink) {
                pageLink.onclick = function() {
                    var geoIndex = parseInt(this.id.replace('loc_', ''), 10);
                    var g = _geo[geoIndex];
                    var yPoint = new YGeoPoint(g[0], g[1]);
                    map.drawZoomAndCenter(yPoint, 12);
                };
            }
        }
    }*/
    var gmap = document.getElementById('gmap');
    if(gmap && GBrowserIsCompatible()) {
      var map = new GMap2(gmap);
      map.addControl(new GLargeMapControl());
      map.addControl(new GMapTypeControl());
      var mm = new GMarkerManager(map);
      var last_point;
      for(var i = 0; i < _geo.length; i++) {
        var g = _geo[i];
        var point = new GLatLng(g[0], g[1]);
        last_point = point;
        var marker = new GMarker(point);
        marker.myContent = g[2];
        mm.addMarker(marker, 0, 17);
        GEvent.addListener(map, "click", function(overlay, latlng, overlaylatlng) {
          if (overlay && overlay.myContent) {
            overlay.openInfoWindowHtml(overlay.myContent);
          }
        });
        var pageLink = document.getElementById('loc_' + i);
        if(pageLink) {
          pageLink.onclick = function() {
            var geoIndex = parseInt(this.id.replace('loc_', ''), 10);
            var g = _geo[geoIndex];
            var point = new GLatLng(g[0], g[1]);
            map.setCenter(point, 12);
          };
        }
      }
      map.setCenter(point, 12);
    }
  });
