/*
 * Simple JavaScript Templating
 * John Resig - http://ejohn.org/ - MIT Licensed
 */
(function(){
  var cache = {};
 
  this.tmpl = function tmpl(str, data){
    // Figure out if we're getting a template, or if we need to
    // load the template - and be sure to cache the result.
    var fn = !/\W/.test(str) ?
      cache[str] = cache[str] ||
        tmpl(document.getElementById(str).innerHTML) :
     
      // Generate a reusable function that will serve as a template
      // generator (and which will be cached).
      new Function("obj",
        "var p=[],print=function(){p.push.apply(p,arguments);};" +
       
        // Introduce the data as local variables using with(){}
        "with(obj){p.push('" +
       
        // Convert the template into pure JavaScript
        str
          .replace(/[\r\t\n]/g, " ")
          .split("<%").join("\t")
          .replace(/((^|%>)[^\t]*)'/g, "$1\r")
          .replace(/\t=(.*?)%>/g, "',$1,'")
          .split("\t").join("');")
          .split("%>").join("p.push('")
          .split("\r").join("\\'")
      + "');}return p.join('');");
   
    // Provide some basic currying to the user
    return data ? fn( data ) : fn;
  };
})();

String.prototype.trim = function() {//全角半角空白を取り除く
	return this.replace(/^[\s　]+|[\s　]+$/g, "");
}

var HTMLUtil = {};
HTMLUtil.escape = function(s){
	s = s.replace(/&/g,"&amp;");
	s = s.replace(/</g,"&lt;");
	s = s.replace(/>/g,"&gt;");
	s = s.replace(/"/g,"&quot;");
	s = s.replace(/'/g,"&#39;");
	return s;
};
HTMLUtil.unescape = function(s){
	s = s.replace(/&amp;/g,"&");
	s = s.replace(/&lt;/g,"<");
	s = s.replace(/&gt;/g,">");
	s = s.replace(/&quot;/g,'"');
	s = s.replace(/&#39;/g,"'");
	return s;
};
HTMLUtil.undisplay = function(s){
	s = s.replace(/\n/ig,"");
	s = HTMLUtil.unescape(s);
	s = URLUtil.unLink(s); // add
	s = s.replace(/<br\s*\/?>/ig,"\n");
	return s;
};
HTMLUtil.display= function(s){
	s = HTMLUtil.escape(s);
	s = URLUtil.urlToLink(s); // add
	s = s.replace(/\n/g,"<br />");
	return s;
};
var HttpUtil = {};
HttpUtil.ajax = function(type, url, data, on_success, on_error) {
  return $.ajax({
    type: type,
    url: url,
    data: data,
    processData: true,
    dataType:"json",
    success: function(data,status) {
      on_success(data);
    },
    error: function(xhr,status,err) {
      var data = {"result":status};
      if (status == 'timeout') {
        data['msg'] = "サーバーと接続できません.";
      } else {
        try {
          data = eval("("+xhr.responseText+")");
        } catch(e) {
          data['msg'] = "サーバー上で動作が不安定になっています。しばらくたってからやり直してみてください";
        }
      }
      on_error(data);
    }
  });
};
HttpUtil.post = function(url, data, on_success, on_error) {
  return HttpUtil.ajax("POST", url, data, on_success, on_error);
};
HttpUtil.get = function(url, data, on_success, on_error) {
  return HttpUtil.ajax("GET", url, data, on_success, on_error);  
};

var URLUtil = {};
URLUtil.URLRegExp = new RegExp('(http(s)?:\/\/[A-Za-z0-9%&=~?+-_/.#]+)',"gi");
URLUtil.urlToLink = function(s){
	return s.replace(URLUtil.URLRegExp,'<a href="$1" rel="nofollow" target="_blank">$1</a>');
};
URLUtil.AnchorRegExp = new RegExp('<a href="[A-Za-z0-9%&=~?+-_/.#]+" target="?_blank"?>([A-Za-z0-9%&=~?+-_/.#]+)</a>','gi');
URLUtil.unLink = function(s){
	return s.replace(URLUtil.AnchorRegExp,'$1');
};
URLUtil.isURL = function(s) {
    if (s.match(URLUtil.URLRegExp)) {
        return true;
    } else {
        return false;
    }
};

var Smipple = {};
Smipple.favorite = function(snippet_id) {
  HttpUtil.post('/favorite/toggle', {"snippet_id": snippet_id},
    function(data) {
      if (data["favorite"]==true) {
        img_url = '/static/img/content_table_star_td2.png';   
      } else {
        img_url = '/static/img/content_table_star_td1.png';
      }
      $('.favorite_link_'+snippet_id+' img').attr('src', img_url);
    },
    function(data) {
      alert(data["msg"]);
    }
  );
};

Smipple.toggleFollow = function(username) {
    $("#follow-button")
        .addClass("loading")
        .attr("disabled", "true");

    HttpUtil.post('/social/follow', $.extend({"username": username},form_security_data),
        function(data) {
            var cnt_dom = $('#follower-count');
            if (data["follow"]==true) {
                $('#follow-button').hide();
                $('#following-msg').show();
                $('#unfollow-link').show();
                cnt_dom.text(parseInt(cnt_dom.text())+1);
            } else {
                $('#follow-button').show();
                $('#following-msg').hide();
                $('#unfollow-link').hide();
                cnt_dom.text(parseInt(cnt_dom.text())-1);
            }
            $("#follow-button")
                .removeClass("loading")
                .attr("disabled", "");
        },
        function(data) {
            alert(data["msg"]);
        }
    );
}

Smipple.deleteSnippet = function(snippet_id) {
  var answer = confirm(gettext("Are you sure you want to delete this snippet? This cannot be undone."));
  if (answer) {
    HttpUtil.post('/snippet/'+snippet_id+'/delete/', form_security_data,
      function(data) {
        window.location="/";
      },
      function(data) {
        alert(data["msg"]);
      }
    );
  }
};

var InlineComments = {};
InlineComments.make_preview = function(text) {
  var preview = text.trim().replace(/\n/g, "");
  if (preview.length > 40) {
    preview = preview.substring(0,37).trim()+"...";
  }
  return preview;
}

InlineComments.toggleComments = function() {
  $('#snippet-code-comments').toggle();
  $('#snippet-code-nocomments').toggle();
  $('#show_comments').toggle();
  $('#hide_comments').toggle();
};

InlineComments.showForm = function() {
  if (comments_disabled) {
    alert(gettext("Posting comments is currently disabled."));
    return;
  }
  //this is the code line clicked on.
  lineno = parseInt($(this).closest("span[id^='code-line-']").attr("id").substring(10));
  InlineComments.showFormForLine(lineno);
};

InlineComments.showFormForLine = function(lineno) {
  if (!logged_in) {
    alert(gettext("Please log in to enter inline comments"));
    return;
  }
  if (!is_ready) {
    // TODO: test in IE
    location.href = "/settings";
    return;
  }
  form = $('#comment-form-'+lineno);
  if (!form.length) {
    form = InlineComments.createForm(lineno)
    $("#inline-comments-"+lineno).append(form).show();
    form.show();
  }
  //Focus on the comment text field.
  form.get(0).comment.focus();
};

InlineComments.createForm = function(lineno) {
  var form_name = "comment-form-"+lineno;
  form = $("#comment-inlineform").clone().attr("name",form_name).attr("id",form_name);
  form.find("input[name='lineno']").val(lineno);
  return form;
};

InlineComments.submitForm = function(form) {
  $(form).find("input").attr("disabled", "disabled");
  $(form).find(".inline-comment-loader").show();
  // alert("Submit!! \nLine: "+
  //     $(form).find("input[name='lineno']").val()+"\n"+
  //     $(form).find("textarea[name='comment']").val());
  
  var comment_data = {};
  var len = form.elements.length;
  for (var i = 0; i < len; i++) {
    var element = form.elements[i];
    if (element.type == "hidden" || element.type == "textarea") {
      comment_data[element.name] = element.value;
    }
  }

  HttpUtil.post(form.action, comment_data,
    function(data) {
      // alert("Success! "+data);
      inline = {
        "author": Smipple.current_user["display_name"],
        "author_url": Smipple.current_user["user_snippets_url"],
        "comment": comment_data['comment'],
        "lineno": comment_data['lineno'],
        "date": gettext("Just now")
      };
      InlineComments.insertComment(inline);
      InlineComments.closeForm(form);
    },
    function(data) {
      alert(interpolate(gettext("Error: %(error_msg)s\n Please report this to the smipple authors."), {"error_msg":data["msg"]}));

      $(form).find("input").removeAttr("disabled");
      $(form).find(".inline-comment-loader").hide();
    }
  );
};

InlineComments.cancelForm = function(form) {
  InlineComments.closeForm(form);
}

InlineComments.closeForm = function(form) {
  //Cancel the form.
  // closest() is jQuery 1.3
  p = $(form).closest(".inline-comments");
  if (p.children().length < 2) {
    p.hide();
  }
  $(form).remove();
};

InlineComments.loadComments = function(inlines) {
  inline_len = inlines.length;
  for (var i=0; i<inline_len; i++) {
    InlineComments.insertComment(inlines[i]);
  }
}

InlineComments.insertComment = function(inline) {
  var inline_comment = $(tmpl("inline_comment_tmpl", {
    "author": inline['author'],
    "date": inline['date'],
    "comment_preview": InlineComments.make_preview(inline['comment']),
    "comment_text": HTMLUtil.display(inline['comment'])
  }));
  inline_comment.find(".inline-comment-reply").click(function() {
    var lineno = parseInt($(this).closest(".inline-comments").attr("id").substring(16));
    InlineComments.showFormForLine(lineno);
  });

  inline_comment.find(".inline-comment-title").click(function() {
    $(this).closest(".inline-comment").find(".extra").toggle();
  });
  $("#inline-comments-"+(inline['lineno'])).show().append(inline_comment);
}

//Preload loader image
var loadImg = new Image();
loadImg.src = "/static/img/pageslide_loader.gif";

$(document).ready(function() {
  $('a.smipple-help').pageSlide({
      width: "300px"
  });
  $('a.smipple-help-long').pageSlide({
      width: "600px"
  });
  $('a.smipple-help-full').pageSlide({
      width: "100%"
  });

  // TODO: Only do this stuff on the snippet page.
  $("span[id^='code-line-']").dblclick(InlineComments.showForm);
  if (typeof inline_comments != "undefined") {
    InlineComments.loadComments(inline_comments);
  }

  $("#search #id_q").focus(function() {
    if ($(this).attr('value') == gettext("Search Smipple")) {
      $(this).data('orig', $(this).attr('value')).attr('value','');
    }
  }).blur(function() {
    if (!$(this).attr('value')) {
      $(this).attr('value', $(this).data('orig'));
    }
  });
});



