$(function() {

var CommunityModerator = Spine.Model.setup("CommunityModerator", ["email"]);
CommunityModerator.extend(Spine.Model.Ajax);
CommunityModerator.extend({
  url: "/api/1.0/community/" + _communityId + "/moderators"
});

CommunityModerator.bind("ajaxError", function(record, xhr, settings, error){ 
  alert("There was an error performing the requested action.");
});




var Community = Spine.Controller.create({

  events: {
    "click .add-moderator": "addModerator",
    "click .current-moderators .remove": "deleteModerator",
    "click .delete-image": "deleteImage",
    "click .becomealocal a": "becomeALocal",
    "click .unjoin a": "unjoin",
//    "click .videos a": "playVideo",
    "click #browse-community-members": "browseCommunityMembers",
    "click .edit-moderators": "browseCommunityModerators",

  },

  browseCommunityMembers: function(e) {
    $.fancybox({
      'type' : 'ajax',
      'ajax' : {
        'type' : 'GET',
        'url' : '/modal/community/' + _communityId + '/members',
        'modal' : false,
        'overlayOpacity' : 1
      }
    });
    mpq.track('browse-community-members', {'communityName' : _communityName, 'userid' : _userId });
  },

  browseCommunityModerators: function(e) {
    $.fancybox({
      'type' : 'ajax',
      'ajax' : {
        'type' : 'GET',
        'url' : '/modal/community/' + _communityId + '/moderators',
        'modal' : false,
        'overlayOpacity' : 1
      }
    });
  },

  playVideo: function(e) {
    var videoId = $(e.currentTarget).attr("videoid");

    $.fancybox({
      'type' : 'ajax',
      'ajax' : {
        'type' : 'GET',
        'url' : '/modal/video',
        'data' : 'videoid=' + videoId,
        'transitionIn' : 'none',
        'transitionOut' : 'none'
      }
    });
  },

  unjoin: function(e) {

    _communityId = e.currentTarget.id;

    $.ajax({
      url: "/api/1.0/community/" + _communityId + "/members/" + _userId,
      type: 'DELETE',
      success: function() {

        $("#inline").fancybox().trigger('click');
        x = document.getElementById(_communityId + "Div");  
        x.parentNode.removeChild(x);

     },
   });
   

  },

  becomeALocal: function(e) {

    if( !_userAuthenticated ) {
      $.fancybox({
        'type' : 'ajax',
        'ajax' : {
          'type' : 'GET',
          'url' : '/modal/login',
          'data' : 'next=/community/' + _communityId
        }
      });
    }
    else {
      $.ajax({
        url: "/api/1.0/community/" + _communityId + "/members/" + _userId,
        type: 'PUT',
        success: function() {
          $(".becomealocal").fadeOut();
          $(".community-members").prepend( $(".user-icon") );
          $(".user-icon").show();
        },
      });
      mpq.track('become-a-local', {'communityName' : _communityName, 'userid' : _userId });

    } // End _userAuthenticated
    
  },

  deleteImage: function(e) {
    var imageid = $(e.currentTarget).attr("imageid");

    $.ajax({
      url: "/api/1.0/community/" + _communityId + "/photos/" + imageid,
      type: 'DELETE',
      success: function() {
        alert('Image has been deleted.');
      },
    });

  },

  addModerator: function(e){
    var email = $("#email").val();

    // If the e-mail is not already in the list
    if( !CommunityModerator.findByAttribute('email',email)) {

      // Check to see if the e-mail is a valid user. If the user is valid add
      // to the moderators list.
      $.ajax({
        url: "/api/1.0/user",
        data: {'email':email},
        type: 'GET',
        success: function() {
          CommunityModerator.create({'email':email});
        },
      });
    }
  },

  deleteModerator: function(e) {
    var userid = $(e.currentTarget).attr("userid");
    var moderator = CommunityModerator.find(parseInt(userid));

    if( moderator ) {
      moderator.destroy();
      alert("Removed moderator from community.");
    }
    else {
      alert("Error removing moderator.");
    }
  },

  addCommunityModerator: function(user) {
  },

  init: function(){

    // $('.editable-content').editable('http://www.example.com/save.php');

    CommunityModerator.bind("create",  this.addCommunityModerator);
    CommunityModerator.bind("refresh change", this.proxy(this.render));
    CommunityModerator.fetch();
    


    $("a[rel='community-photos']").fancybox({
      'transitionIn' : 'none',
      'transitionOut' : 'none',
      'titlePosition' : 'over',
      'titleFormat' : function(title, currentArray, currentIndex, currentOpts) {
        var context = {
          'index' : currentIndex + 1,
          'totalImages' : currentArray.length,
          'title' : title,
          'imageid' : $("img[imagenumber='" + currentIndex + "']").attr('imageid'),
        };

        return $("#photo-caption-template" ).tmpl( context );
      }
    });


	$("#uploader").plupload({
		// General settings
		runtimes : 'flash,html5,browserplus,silverlight,gears,html4',
		url : '/api/1.0/community/' + _communityId + '/photos',
		max_file_size : '1000mb',
		max_file_count: 30, // user can add no more then 20 files at a time
//		chunk_size : '1mb',
		unique_names : true,
		multiple_queues : true,

		// Resize images on clientside if we can
		resize : {width : 1024, height : 768, quality : 95},
		
		// Rename files by clicking on their titles
		rename: true,
		
		// Sort files
		sortable: true,

		// Specify what files to browse for
		filters : [
			{title : "Image files", extensions : "jpg,gif,png"},
			{title : "Zip files", extensions : "zip,avi"}
		],

		// Flash settings
		flash_swf_url : '/site_media/plupload/js/plupload.flash.swf',

		// Silverlight settings
		silverlight_xap_url : 'site_media/plupload/js/plupload.silverlight.xap'
	});











  },

  render: function(){
    mpq.track('view-community', {'communityName' : _communityName });
  },

});


var community = Community.init({
  el: $(document)
});


});

