// Always send the authenticity_token with ajax
/*
$(document).ajaxSend(function(event, request, settings) {
  if ( settings.type == 'post' ) {
    settings.data = (settings.data ? settings.data + "&" : "")
      + "authenticity_token=" + encodeURIComponent( AUTH_TOKEN );
    request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
  }
});
*/

// When I say html I really mean script for rails
$.ajaxSettings.accepts.html = $.ajaxSettings.accepts.script;


$(function() {

  //new AjaxUpload('#response_image',{
  //  action: '/responses/response_image',
  //  name: 'response_image',
  //  oncomplete: function(file){
  //  }
  //});

  //response to the click on the album photos
  var bind_albumphotos_behaviors= function(scope) {
    $("img.resp_album_photo",scope).click(function() {
      var p_id=this.id;
      var selected_id=$('input#resp_photo_id').val();
      if(!selected_id.match(p_id)){
        var str='';
        var ori_content=$('div#resp_selected_photos')[0].innerHTML;
        str='<img src="' + this.src + '" border=0 style="border: 2px solid #CC0000;" />';
        $('div#resp_selected_photos').html(ori_content+str);
        $('input#resp_photo_id').val(selected_id+','+p_id);
      }
      return false;
    });
  }


  var bind_subresponses_behaviors= function(scope) {
    //handle the subresponse form
    $("div.subresponses form",scope).submit(function() {
      var subresponse_content=$(this).find('textarea[name="subresponse"]').val();
      var subresponse_content_length=subresponse_content.length;
      var error_message="";
      if ( subresponse_content_length < 2 || subresponse_content_length > 2048) {
        if (subresponse_content_length > 2048){
          error_message="Your reply is too long, maximum is 2048 characters";
        }else {
          error_message="Your reply is too short, minimum is 2 characters";
        }
        $(this)
          .parents('div#resp_reply_form')
          .find('div.subresponse_error')
          .html('<font color="red">'+error_message+'</font>');
      } else {
        var form_name=this.name;

        // append the post in the client side
        var template=$('div#subresponse_template').clone();
        //template.find('div.subresponse').removeClass('hidden');
        var content=template[0].innerHTML;
        content=content.replace(/@@RESPONSE_OWNER_NAME@@/g,$(this).find('input[name="parent_user_name"]').val());
        var now=new Date();
        content=content.replace(/@@SUBRESPONSE_TIME@@/,now.format("mmm dd, hh:MMTT"));
        content=content.replace(/@@SUBRESPONSE_BODY@@/,$(this).find('textarea[name="subresponse"]').val());
 
        $(this).parent().before(content);
        $(this).parent().prev().slideDown("slow");

        $.get('/responses/create',$(this).serialize(),function(data) {
          //$('div#subresponses_'+form_name).html(data);
          //bind_subresponses_behaviors($('div#subresponses_'+form_name).parent());
        });
      
        //clear the form
        $(this).reset();

        $(this)
          .parents('div#resp_reply_form')
          .find('div.subresponse_error')
          .html('');

        //update the comment nums
        var comments_num_block=$(this)
                                .parents("div.response")
                                .find("span#comments_num");

        if (comments_num_block.length > 0){
          comments_num_block.text((parseInt(comments_num_block.text())+1)+"");          
        }else{
          $(this)
            .parents("div.response")
            .find("div.comments_num_div")
            .html('<b><span id="comments_num">1</span> comments</b> for this answer');
        }
      }
      return false;
    });
  }


  var bind_behaviors= function(scope) {
    //sort order
    $('select#response_sort',scope).change(function(){
      var response_form=$('div.response_form form');
      $.cookie('response_sort_order',$(this).val(),{expires: 90,path: '/'});
      $.get('/responses/view',{'order':$(this).val(),'kind':response_form.find('input[name="kind"]').val(),'kind_id':response_form.find('input[name="kind_id"]').val(),'size':response_form.find('input[name="size"]').val(),'short_version':response_form.find('input[name="short_version"]').val()},function(data) {
        $('#resp').parent().html(data);
        bind_behaviors($('#resp').parent());
      });
      return false;
    });

    //toggle subresponse form
    $('a.reply_to_this_link',scope).click(function() {
      $('div.no_other_replies').hide();
//      $(this).parents(".response").find("#resp_reply_form").toggleClass('hidden');
      $(this).parents(".response").find("#resp_reply_form").show();
      return false;
    });

    //expand subresponse block
    $('a.expand_subresponses_block_link',scope).click(function() {
      $(this).parents("div.subresponses").find("div.subresponse_expand").toggleClass('hidden');
      return false;
    });

    //delete a response
    $('a.delete_response',scope).click(function() {
      var answer=confirm('Are you sure?');
      if (answer){
        $(this).parents("div.response").fadeOut("slow",function(){
          $(this).remove();
        });
        $.get('/responses/destroy',{'id':this.name},function(data) {
        });
      }
      return false;
    });

    //delete a subresponse
    $('a.delete_subresponse',scope).click(function() {
      var answer=confirm('Are you sure?');
      if (answer){
        $(this).parents("div.subresponse").fadeOut("slow",function(){
          $(this).remove();
        });
        $.get('/responses/destroy',{'id':this.name},function(data) {
        });
      }
      return false;
    });

    //toggle photo caption div
    $("div.response_form form input#photo_image").click(function() {
      $("div#response_caption_field").removeClass("hidden");
    });

    //toggle response from
    $('a#resp_add_comment',scope).click(function() {
      $("div.response_form").toggleClass("hidden");
      return false;
    });

    //validation before submit the response
    $('div.response_form form',scope).submit(function() {
      var response_content=$(this).find('textarea[name="response"]').val();
      var response_content_length=response_content.length;
      var error_message="";
      if (response_content_length < 2 || response_content_length > 8192) {
        if (response_content_length > 8192){
          error_message="Your reply is too long, maximum is 8192 characters";
        }else {
          error_message="Your reply is too short, minimum is 2 characters";
        }
        $(this)
          .parents('div.response_form')
          .find('div.response_error')
          .html('<font color="red">'+error_message+'</font>');
        return false; 
      }
    });

    bind_subresponses_behaviors(scope);
   
    //handle the responses form
    //$("div.response_form form",scope).submit(function() {
    //  $.get('/responses/create',$(this).serialize(),function(data) {
    //    $('#resp').parent().html(data);
    //    bind_behaviors($('#resp').parent());
    //  });
    //  return false;
    //});
 
    //show more replies
    $("div#response_pages a",scope).click(function() {
      var response_form=$('div.response_form form');
      $.get('/responses/view',{'curr_page':this.name,'kind':response_form.find('input[name="kind"]').val(),'kind_id':response_form.find('input[name="kind_id"]').val(),'size':response_form.find('input[name="size"]').val(),'short_version':response_form.find('input[name="short_version"]').val()},function(data) {
        $('#resp').parent().html(data);
        bind_behaviors($('#resp').parent());
      });
      return false;
    });

    //rate it
    $("a.rate_it_link",scope).click(function() {
      var link_name=this.name;
      $.get('/responses/update_rate_directly',{'id':this.name},function(data) {
        $('span#rate_result_span_'+link_name).html(data);
      });
      return false;
    });
   
    //report abuse
    $("a.report_abuse_link",scope).click(function() {
      var link_name=this.name;
      $.get('/responses/update_report_abuse',{'id':this.name},function(data) {
        $('span#report_abuse_'+link_name).html(data);
      });
      return false; 
    });

    //add more photo-upload entries
    $("a#add_photo_upload_entry_link",scope).click(function() {
      var template=$('div#response_photo_upload_entry_template').clone();
      var content=template[0].innerHTML;
      var index=$("div#response_photo_upload_entries p.response_photo_upload_entry").length
      content=content.replace(/@@ENTRY_INDEX@@/g,index+"");

      $(content)
       .insertAfter("div#response_photo_upload_entries p.response_photo_upload_entry:last")
       .slideDown("slow");

      return false;
    });

    //show "add photos from album" block
    $("a#add_photo_from_album_link",scope).click(function() {
      $.get('/responses/photoselects',{},function(data){
        $('div#response_photoselect').html(data);
        bind_albumphotos_behaviors($('div#response_photoselect'));
      });
      return false;
    });

  }

  //initial event binding
  bind_behaviors(this);  
});
