// JSONのデータを取得
var _json_request_auth_lock = false;
function JsonRequest(url, params, on_succ, on_error) {
    if(_json_request_auth_lock) {
	setTimeout(function(){ JsonRequest(url, params, on_succ, on_error); }, 500);
	return;
    }
    try {
	_json_request_auth_lock = false;
	new Ajax.Request(url, $H(params).merge({
		    onSuccess: function(req) {
			on_succ(req, req.responseText.strip()=='' ? undefined : eval("("+req.responseText+")"));
		    },
		    onFailure: (on_error || function(r){}),
			onException: function(req, e) { if(__debug) console.log(e); if(on_error) on_error(req,e); },
		    on403: function(req) {
			if(_json_request_auth_lock) {
			    setTimeout(function(){ JsonRequest(url, params, on_succ, on_error); }, 500);
			    return;
			}
		        _json_request_auth_lock = true;
		        dialog.show('login_box', undefined, function(form) {
				var p = $H();
				p['login'] = form.login.value;
				p['password'] = form.password.value;
				p['property'] = 'sticka-ajax';
				new Ajax.Request('/session/create.json', {method: 'post', parameters: p.toObject(), onSuccess: function(req) {
					    var values =  req.responseText.strip().blank() ? undefined : eval("("+req.responseText+")");
					    if(values.errors.size()==0) {
						my.update(values.attributes);
						dialog.hide();
						_json_request_auth_lock = false;
						return JsonRequest(url, params, on_succ, on_error);
					    }
					    else {
						errors_to_html(values.errors);
						dialog.hide();
						resized();
					    }
					}});
			    });
		    }
		}).toObject());
    }
    catch(e) {
	on_error(undefined, e);
    }
}

var Template15 = Class.create();
Template15.Pattern = /(^|.|\r|\n)(([#%]{1})\{(.*?)\})/;
Template15.prototype = {
  initialize: function(template, pattern) {
    this.template = template.toString();
    this.pattern  = pattern || Template15.Pattern;
  },

  evaluate: function(object) {
    return this.template.gsub(this.pattern, function(match) {
      var before = match[1];
      if (before == '\\') return match[2];
      return before + String.interpret(eval((match[3]=="#"?"object.":'')+match[4]));
    });
  }
}

// テンプレート
var _templates = $H();
var $T = function(temp_id, params) {
    var temp = _templates[temp_id];
    if(temp == undefined) temp = _templates[temp] = new Template15($(temp_id+'_template').innerHTML.gsub('id="_', 'id="'));
    if(params == undefined) return temp;
    return temp.evaluate(params);
}

// ダイアログ
var Dialog = Class.create();
Dialog.prototype = {
    _callback : undefined,

    initialize : function() {
        var self = this;
        Event.observe('dialog-form', 'submit', function(e) { if(self._callback!=undefined) self._callback(e.target); Event.stop(e); }, false);
    },

    show : function(template, params, _callback) {
	var duration = 0.3;
        this._callback = _callback;
	Element.setStyle('dialog', {visibility: 'hidden'});
        Element.update('dialog-body', $T(template, (params || {})));
        Element.show('dialog');
        this.resized();
        Event.observe(window, "resize", this.resized);
        Element.show('dialog-overlay');
	$('dialog-overlay').setOpacity(0.0);
	$('dialog-body').setOpacity(0.0);
	Element.setStyle('dialog', {visibility: 'visible'});
	new Effect.Opacity('dialog-overlay', { duration: duration, from: 0.0, to: 0.75 });
	new Effect.Opacity('dialog-body', { duration: duration, from: 0.0, to: 1.0 });
    },

    hide : function() {
	var duration = 0.3;
        this._callback = undefined;
        Event.stopObserving(window, "resize", this.resized, false);
	new Effect.Opacity('dialog-overlay', { duration: duration, from: 0.75, to: 0.0 });
	new Effect.Opacity('dialog-body', { duration: duration, from: 1.0, to: 0.0 });
	setTimeout( function() {
	        Element.hide('dialog');
	    }, duration * 1000);
    },

    resized : function() {
        if(Prototype.Browser.IE) {
            Element.setStyle('dialog-overlay', {width: document.body.clientWidth, height:document.body.clientHeight});
        }
        Element.setStyle('dialog-body', {left: (document.body.clientWidth-Element.getWidth('dialog-body'))/2+"px", top:(document.body.clientHeight-Element.getHeight('dialog-body'))/3+"px"});
    }
};

// 意見箱ダイアログ
function dialog_comment() {
    dialog.show('comment_form', undefined, function(form) {
            JsonRequest('/comment/create.json', {method: 'post', parameters: {body: form.body.value}}, function(req, value) {
                    dialog.hide();
                },
                function(req) { });
        });
}

// ヘルプ表示
function dialog_help() {
    dialog.show('help_box');
}

var dialog;
Event.observe(window, "load", function() { dialog = new Dialog(); });

// 空白か？
function is_blank(str) {
    return((typeof str)=="undefined" || str==null || str=="");
}

// checkvox生成
function checkbox_option(val) {
    return([1,'1','t','true'].include(val) ? ' checked="checked" ' : '');
}

// エラーメッセージ表示
function errorMessage(str) {
    Element.update('error_message_body', str);
    Element.show('error_message');
}


function getAreaRange(obj) {
    var pos = new Object();
    if (Prototype.Browser.IE) {
	obj.focus();
	var range = document.selection.createRange();
	var clone = range.duplicate();
 
	clone.moveToElementText(obj);
	clone.setEndPoint( 'EndToEnd', range );
 
	pos.start = clone.text.length - range.text.length;
	pos.end = clone.text.length - range.text.length + range.text.length;
    }
 
    else if(window.getSelection()) {
	pos.start = obj.selectionStart;
	pos.end = obj.selectionEnd;
    }
 
    return pos;
}

function insertAtCaret( obj, text ) {


    var target =$(obj);
    var pos = getAreaRange(target);
 
    var val = target.value;
    var range = val.slice(pos.start, pos.end);
    var beforeNode = val.slice(0, pos.start);
    var afterNode = val.slice(pos.end);
    var insertNode;
 
    if (range || pos.start != pos.end) {
	target.value = beforeNode + text + range + afterNode;
    }
 
    else if (pos.start == pos.end) {
	target.value = beforeNode + text + afterNode;
    }
}
