
SK.Comments = {
  View: {
    hideForms: function() {
      $('#reply-comment').hide().appendTo($('#invisible_section'));
    },

    showForm: function(id) {
      SK.Comments.View.hideError();
      if (id == "comment-0") {
      }
      else {
        $('#reply-comment').show().appendTo($('#'+id+' > .comment_form_target'));
        if ($('#reply-comment').attr('action') == "") {
          action = $('#reply-comment').attr('rel')
        } else {
          action = $('#reply-comment').attr('action')
        }
          
        $('#reply-comment').attr('action', action.replace(/\/\//, '/'+id.split("-")[1]+'/'))
        $('#reply-comment').removeAttr('rel')
      }
    },

    showSpinner: function(id) {
      SK.Comments.spinner.prependTo($('#'+id)).show();
    },

    hideSpinner: function() {
      SK.Comments.spinner.appendTo($('#invisible_section')).hide();
    },

    displayError: function(id, html) {
      $('#'+id+' > .comment_form_target .error').html(html).show();
    },

    hideError: function() {
      $('.comment_form_target .error').hide();
    },

    addChild: function(id, html) {
      if ($('#'+id+' > ol.comments').length == 0) {
        $('#'+id).append('<ol class="comments"></ol>');
      }
      $('#'+id+' > ol.comments').prepend(html);
      $('#'+id+' > ol.comments > .comment:first > .footer .reply_comment_link').click(stopAnd(SK.Comments.Controller.handleReplyClick));
    },

    getElements: function() {
      SK.Comments.spinner = $('#comment_spinner');
      SK.Comments.newCommentForm = $('#new-comment');
      SK.Comments.newCommentLink = $('#new-comment_link');
    },

    form: function(id) {
      if (id == "comment-0") {
        return $('#new-comment');
      }
      else {
        return $('#reply-comment');
      }
    }
  },

  Controller: {
    handleReplyClick: function(e) {
      e.preventDefault();
      
      var id = $(e.target).parents('.comment').attr('id');
      SK.Comments.View.showForm(id);
      $('#reply_comment_content').val("")
    },

    handleSuccessFor: function(id) {
      return function(json_resp) {
        if (json_resp["status"] == "ok") {
          SK.Comments.View.addChild(id, json_resp["body"]);
          SK.Comments.View.hideSpinner();
          SK.Comments.View.hideError();
        }
        else {
          SK.Comments.View.displayError(id, json_resp["message"]);
          SK.Comments.View.hideSpinner();
        }
      };
    },

    handleErrorFor: function(id) {
      return function(req) {
        SK.Comments.View.displayError(id, "Sorry, there was an unknown error.");
        SK.Comments.View.hideSpinner();
      };
    },

    handleSubmitForm: function(e) {
      var id;
      if (e.target.id == "new-comment") {
        id = "comment-0";
      } else {
        id = e.target.parentNode.parentNode.id;
      }
      SK.Comments.Controller.submitForm(id);

      if (id = "comment-0") {
        $('#new_comment_content').val("")
        $('#rating').val("")
      	if (SK.rating != undefined) {
          SK.rating.setRating(null);
      	}
      }
    },

    submitForm: function(id) {
      SK.Comments.View.hideForms();
      SK.Comments.View.showSpinner(id);
      var form = SK.Comments.View.form(id);
      
      $.ajax({
        type:     'POST',
        url:      form.attr("action") + "?format=js",
        data:     form.serialize(),
        success:  (SK.Comments.Controller.handleSuccessFor(id)),
        error:    (SK.Comments.Controller.handleErrorFor(id)),
        dataType: "json"
      });
    }
  },

  init:function() {
    $(document).ready(function() {
      SK.Comments.View.hideForms();
      SK.Comments.View.getElements();

      $('.reply_comment_link').click(SK.Comments.Controller.handleReplyClick);
      $('#cancel_reply_comment_link').click(stopAnd(SK.Comments.View.hideForms));

      $('#new-comment').submit(stopAnd(SK.Comments.Controller.handleSubmitForm));
      $('#reply-comment').submit(stopAnd(SK.Comments.Controller.handleSubmitForm));
    });
  }
};

SK.Comments.init();


//# Google Maps
SK.GMapAdaptor = {
  mapContainerSelector: '#google-map',

  load_google_map: function(lat, lng) {
    if (GBrowserIsCompatible()) {
      var map = new GMap2($(this.mapContainerSelector)[0]);
      map.addControl(new GSmallMapControl());
      map.setCenter(new GLatLng(lat, lng), 13);
      map.addOverlay(new GMarker(new GLatLng(lat, lng)));
    }
  },

  load_google_map_for_city: function(locations) {
    var marker;
    var map;
    if (GBrowserIsCompatible()) {
      map = new GMap2($(this.mapContainerSelector)[0]);
      map.addControl(new GSmallMapControl());
      map.setCenter(new GLatLng(locations[0][0], locations[0][1]), 13);
      for(var idx in locations) {
	      marker = new GMarker(new GLatLng(locations[idx][0], locations[idx][1]));
	      GEvent.addListener(marker, "click", function(mk, val){
	        return function() {
            mk.openInfoWindowHtml("<p style=\"color:#000\">" + val + "</p>");
	        }
	      }(marker, locations[idx][2]));
	      map.addOverlay(marker);
      }
    }
  }
}

SK.rating = {
  ratingSelector: "#rating",
  ratingController: false,
  currentRatingHandle: false,
  ratingLabel: false,
  currentSelectionLabel: false,
  
  setRatingLabel: function(labelText) {
    if (labelText) {
      cancelButton = $(document.createElement("a"))
      cancelButton.attr('href','')
      cancelButton.text("(cancel)")
      cancelButton.click(function(){
        SK.rating.setRating(null);
        return false;
      });
      this.ratingLabel.text(labelText+' ')
      this.ratingLabel.append(cancelButton)
    } else {
      $(this.ratingLabel).html('&nbsp;');
    }
  },

  setRating:function(ratingValue) {
    this.currentSelectionLabel = $(this.ratingController).children('.star'+ratingValue).attr('title');
    
    //Reflect selection in display
    $(this.currentRatingHandle).show().css('width', ratingValue * $(this.ratingController).children('.star1').width());
    this.setRatingLabel(this.currentSelectionLabel)
    
    //Set options in origional selector
    $(this.ratingSelector).children().attr('selected', false)
    $(this.ratingSelector).children('[value='+ratingValue+']').attr('selected', true)
  },

  createRatingController:function() {
    //Create new rating controller widget
    this.ratingController = $(document.createElement("ol"));
    this.ratingController.attr('class','max-rating');

    $(this.ratingSelector).after(this.ratingController)
    
    //Add a change-able holding-element for the current selected rating
    this.currentRatingHandle = $(document.createElement("li"));
    this.currentRatingHandle.attr('class','rating current-rating');
    this.ratingController.append(this.currentRatingHandle);
    
    //Add rating values for each of the specified options in the select we're replacing
    $.each($(SK.rating.ratingSelector).children('[value]'), function(){
      var ratingValue = $(this).val();
      ratingOption = $(document.createElement("li"));
      ratingOption.attr('class','rating star'+ratingValue);
      ratingOption.attr('title','Rate '+ratingValue+' stars');
      ratingOption.hover(
        function(){
          $(this).addClass('active')
          SK.rating.ratingLabel.text($(this).attr('title'))
          SK.rating.currentRatingHandle.hide()
        },
        function(){
          $(this).removeClass('active')
          SK.rating.setRatingLabel(SK.rating.currentSelectionLabel)
          SK.rating.currentRatingHandle.show()
        });
      ratingOption.click(function(){
          SK.rating.setRating(ratingValue);
      });
      SK.rating.ratingController.append(ratingOption);
    });
    
    this.ratingLabel = $(document.createElement("span"));
    this.ratingLabel.attr('class','ratingLabel').html('&nbsp;')
    this.ratingLabel.insertAfter(this.ratingController)
  },

  init:function() {
    if ($("body").hasClass("not-logged-in") == false) {
      SK.rating.createRatingController();
      $(SK.rating.ratingSelector).hide();
      SK.rating.setRating($(SK.rating.ratingSelector + " option:selected").val());      
    } 
  }
}

$(document).ready(function(){
  SK.rating.init()  
})

