﻿
AUTO_ID = 100;

String.implement({
	
	len: function(){
		var len = 0;
		for(var i = 0; i < this.length; i++)		len += this.charCodeAt(i) > 255 ? 2 : 1;
		return len;
	}
	
});

Element.implement({
	
	display: function(){
		return this.setStyle('display', '');
	},
	
	hide: function(){
		return this.setStyle('display', 'none');
	},
	
	reflect: function(){
		return $(this.id || (this.id = 'autoId' + AUTO_ID++));
	}
	
});

function observeSubmit(event, form){
	form = $(form);
	if(!form.submitBtn){
		var inputs = form.getElements('input.submit');
		if(inputs.length > 0)	form.submitBtn = inputs[0];
		else return;
	}
	event = event || window.event;
	if(event.keyCode == 13)	form.submitBtn.click();
}

function request(options){
	options.data = JSON.encode(options.params);
	delete options.params;
	options.headers = { 'X-AjaxPro-Method': options.method };
	delete options.method;
	var s = options.onSuccess, f = options.onFailure;
	
	$extend(options, {
		url: ajaxUrl,
		method: 'POST',
		onSuccess: function(text){
			var obj = JSON.decode(text);
			if(obj.value && s)	s(obj.value);
			if(obj.error && f)	f(this.xhr);
		}
	});
	new Request(options).send();
}

function getHTML(url, title, container, onSuccess, onFailure, track, beside){
	if($type(url) == 'element'){
		title = title || url.innerHTML;
		url = url.href;
	}
	
	if(url.indexOf('ajaxrdm=') > -1)  url = url.replace(/([\?&]ajaxrdm=)\d+/, '\$1' + (new Date().getTime()));
	else  url += (url.indexOf('?') != -1 ? '&' : '?') + 'ajaxrdm=' + (new Date().getTime());
	
	var besideDelay = false;
	new Request.HTML({
		url: url,
		headers: {'X-Request': 'AJAX'},
		evalScripts: false,
		onSuccess: function(tree, els, html, js){
			if($(container || 'contentBox')){
				var tmp = document.createElement('div');
				tmp.innerHTML = html;
				$(container || 'contentBox').empty().appendChild(tmp);
				$('loading').hide();
				$exec.delay(100, this, this.response.javascript);
				if(beside && besideDelay)	beside();
				if(onSuccess)	onSuccess(html);
			}
		},
		onFailure: function(){
			document.getElements('#loading img')[0].hide();
			$('loading').setStyle('color', 'red').getElements('span')[0].innerHTML = '发生错误，请稍候重试';
			if(onFailure)	onFailure();
		}  
	}).get();
	document.getElements('#loading img')[0].display();
	$('loading').setStyle('color', '#000').display().getElements('span')[0].innerHTML = '数据加载中,请稍候..';
	
	if(track !== false && !!!historyMgr.stateChanged)  historyMgr.add(title, url);
	try{
		if(beside)	beside();
	}catch(e){ besideDelay = true; }
}

function asyncSubmit(btn, action, container, onSuccess, onFailure){
	btn.form.__EVENTTARGET.value = btn.id;
	var queryString = [];
	$(btn.form).getElements('input, select, textarea', true).each(function(el){
		if (!el.name || el.disabled) return;
		if(el.tagName.toLowerCase() == 'input' && (el.type.toLowerCase() == 'button' || el.type.toLowerCase() == 'submit'))  return;
		var value = (el.tagName.toLowerCase() == 'select') ? Element.getSelected(el).map(function(opt){
			return opt.value;
		}) : ((el.type == 'radio' || el.type == 'checkbox') && !el.checked) ? null : el.value;
		$splat(value).each(function(val){
			if (typeof val != 'undefined') queryString.push(el.name + '=' + encodeURIComponent(val));
		});
	});
	
	action = action || btn.form.action;
	if(action.indexOf('ajaxrdm=') > -1)  action = action.replace(/([\?&]ajaxrdm=)\d+/, '\$1' + (new Date().getTime()));
	else  action += (action.indexOf('?') != -1 ? '&' : '?') + 'ajaxrdm=' + (new Date().getTime());
	new Request.HTML({
		url: action,
		headers: {'X-Request': 'AJAX'},
		evalScripts: false,
		onSuccess: function(tree, els, html, js){
			if($(container || 'contentBox')){
				var tmp = document.createElement('div');
				tmp.innerHTML = html;
				$(container || 'contentBox').empty().appendChild(tmp);
				$('loading').hide();
				$exec.delay(100, this, this.response.javascript);
				if(onSuccess)	onSuccess(html);
			}
		},
		onFailure: function(){
			document.getElements('#loading img')[0].hide();
			$('loading').setStyle('color', 'red').getElements('span')[0].innerHTML = '发生错误，请稍候重试';
			if(onFailure)	onFailure();
		}
	}).send(queryString.join('&'));

	$('loading').display().getElements('span')[0].innerHTML = '正在提交,请稍候..';
}

HistoryManager = new Class({
	Implements: [Events, Options],
	initialize: function(options){
		this.setOptions({
			/*onStateChanged: $empty,*/
			observeDelay: 100
		}, options);
		this.currentState = '';

		this.frame = new Element('iframe', { width: 0, height: 0, id: 'historyFrame', styles: { display: 'none'}}).inject(document.body);
		this.checkTimer = this.checkState.periodical(this.options.observeDelay, this);
	},
	
	add: function(title, state){
		if(this.currentState == state)	return;
		this.currentState = state;
		try {
			var doc = this.frame.contentWindow.document;
			doc.open();
			doc.write('<html><head><title>' + title + '</title></head><body><input id="input1" value="' + state + '" />' + state + '</body></html>');
			doc.close();
		} catch(e) {};
	},
	
	/*add: function(fname, args){
		
		if(this.currentState == state)	return;
		this.currentState = state;
		
		try {
			var doc = this.frame.contentWindow.document;
			doc.open();
			doc.write('<html><head><title>' + title + '</title></head><body><input id="input1" value="' + state + '" />' + state + '</body></html>');
			doc.close();
		} catch(e) {};
	},*/
	
	checkState: function(){
		var title = this.frame.contentWindow.document.title;
		var state = this.frame.contentWindow.document.getElementById('input1') ? this.frame.contentWindow.document.getElementById('input1').value : '';
		//var state = this.frame.contentWindow.document.body.innerHTML;
		if(state != this.currentState){
			this.currentState = state;
			this.stateChanged = true;
			this.fireEvent('stateChanged', [title, state]);
		}
	},
	
	dispose: function(){
		$clear(this.checkTimer);
		this.removeEvents();
		this.frame.dispose();
		delete this.frame;
	}
});


function $exec(text){
	if (!text) return text;
	text = text.replace('<!--', '').replace('// -->', '').replace('//<![CDATA[', '').replace('//]]>', '');
	if (window.execScript){
		window.execScript(text);
	} else {
		var script = document.createElement('script');
		script.setAttribute('type', 'text/javascript');
		script[(Browser.Engine.webkit && Browser.Engine.version < 420) ? 'innerText' : 'text'] = text;
		document.head.appendChild(script);
		document.head.removeChild(script);
	}
	return text;
};