var Prototype = {
  Version: '1.5.0',
  BrowserFeatures: {
    XPath: !!document.evaluate
  },

  ScriptFragment: '(?:<script.*?>)((\n|\r|.)*?)(?:<\/script>)',
  emptyFunction: function() {},
  K: function(x) { return x; }
};

var Class = {
  create: function() {
    return function() {
      this.initialize.apply(this, arguments);
    };
  }
};

Object.extend = function(destination, source) {
  for (var property in source) {
    destination[property] = source[property];
  }
  return destination;
};

var Try = {
  these: function() {
    var returnValue;
    for (var i = 0, length = arguments.length; i < length; i++) {
      var lambda = arguments[i];
      try {
        returnValue = lambda();
        break;
      } catch (e) {}
    }
    return returnValue;
  }
};

function $(element) {
  if (arguments.length > 1) {
    for (var i = 0, elements = [], length = arguments.length; i < length; i++)
      elements.push($(arguments[i]));
    return elements;
  }
  if (typeof element == 'string')
    element = document.getElementById(element);
  return element;
}

var $A = function(iterable) {
  if (!iterable) return [];
  if (iterable.toArray) {
    return iterable.toArray();
  } else {
    var results = [];
    for (var i = 0, length = iterable.length; i < length; i++)
      results.push(iterable[i]);
    return results;
  }
};

Function.prototype.bind = function() {
  var __method = this, args = $A(arguments), object = args.shift();
  return function() {
    return __method.apply(object, args.concat($A(arguments)));
  }
};

Function.prototype.bindAsEventListener = function(object) {
  var __method = this, args = $A(arguments), object = args.shift();
  return function(event) {
    return __method.apply(object, [( event || window.event)].concat(args).concat($A(arguments)));
  }
};

String.interpret = function(value){
  return value == null ? '' : String(value);
}

Object.extend(String.prototype, {
  gsub: function(pattern, replacement) {
    var result = '', source = this, match;
    replacement = arguments.callee.prepareReplacement(replacement);

    while (source.length > 0) {
      if (match = source.match(pattern)) {
        result += source.slice(0, match.index);
        result += String.interpret(replacement(match));
        source  = source.slice(match.index + match[0].length);
      } else {
        result += source, source = '';
      }
    }
    return result;
  },

  sub: function(pattern, replacement, count) {
    replacement = this.gsub.prepareReplacement(replacement);
    count = count === undefined ? 1 : count;

    return this.gsub(pattern, function(match) {
      if (--count < 0) return match[0];
      return replacement(match);
    });
  },

  scan: function(pattern, iterator) {
    this.gsub(pattern, iterator);
    return this;
  },

  truncate: function(length, truncation) {
    length = length || 30;
    truncation = truncation === undefined ? '...' : truncation;
    return this.length > length ?
      this.slice(0, length - truncation.length) + truncation : this;
  },

  strip: function() {
    return this.replace(/^\s+/, '').replace(/\s+$/, '');
  },

  stripTags: function() {
    return this.replace(/<\/?[^>]+>/gi, '');
  },

  stripScripts: function() {
    return this.replace(new RegExp(Prototype.ScriptFragment, 'img'), '');
  },

  extractScripts: function() {
    var matchAll = new RegExp(Prototype.ScriptFragment, 'img');
    var matchOne = new RegExp(Prototype.ScriptFragment, 'im');
    return (this.match(matchAll) || []).map(function(scriptTag) {
      return (scriptTag.match(matchOne) || ['', ''])[1];
    });
  },

  evalScripts: function() {
    return this.extractScripts().map(function(script) { return eval(script) });
  },

  escapeHTML: function() {
    var div = document.createElement('div');
    var text = document.createTextNode(this);
    div.appendChild(text);
    return div.innerHTML;
  },

  unescapeHTML: function() {
    var div = document.createElement('div');
    div.innerHTML = this.stripTags();
    return div.childNodes[0] ? (div.childNodes.length > 1 ?
      $A(div.childNodes).inject('',function(memo,node){ return memo+node.nodeValue }) :
      div.childNodes[0].nodeValue) : '';
  },

  toQueryParams: function(separator) {
    var match = this.strip().match(/([^?#]*)(#.*)?$/);
    if (!match) return {};

    return match[1].split(separator || '&').inject({}, function(hash, pair) {
      if ((pair = pair.split('='))[0]) {
        var name = decodeURIComponent(pair[0]);
        var value = pair[1] ? decodeURIComponent(pair[1]) : undefined;

        if (hash[name] !== undefined) {
          if (hash[name].constructor != Array)
            hash[name] = [hash[name]];
          if (value) hash[name].push(value);
        }
        else hash[name] = value;
      }
      return hash;
    });
  },

  toArray: function() {
    return this.split('');
  },

  succ: function() {
    return this.slice(0, this.length - 1) +
      String.fromCharCode(this.charCodeAt(this.length - 1) + 1);
  },

  camelize: function() {
    var parts = this.split('-'), len = parts.length;
    if (len == 1) return parts[0];

    var camelized = this.charAt(0) == '-'
      ? parts[0].charAt(0).toUpperCase() + parts[0].substring(1)
      : parts[0];

    for (var i = 1; i < len; i++)
      camelized += parts[i].charAt(0).toUpperCase() + parts[i].substring(1);

    return camelized;
  },

  capitalize: function(){
    return this.charAt(0).toUpperCase() + this.substring(1).toLowerCase();
  },

  underscore: function() {
    return this.gsub(/::/, '/').gsub(/([A-Z]+)([A-Z][a-z])/,'#{1}_#{2}').gsub(/([a-z\d])([A-Z])/,'#{1}_#{2}').gsub(/-/,'_').toLowerCase();
  },

  dasherize: function() {
    return this.gsub(/_/,'-');
  },

  inspect: function(useDoubleQuotes) {
    var escapedString = this.replace(/\\/g, '\\\\');
    if (useDoubleQuotes)
      return '"' + escapedString.replace(/"/g, '\\"') + '"';
    else
      return "'" + escapedString.replace(/'/g, '\\\'') + "'";
  }
});
if (!window.Element)
  var Element = new Object();

Element.remove = function(element) {
  element = $(element);
  element.parentNode.removeChild(element);
  return element;
};

var PeriodicalExecuter = Class.create();
PeriodicalExecuter.prototype = {
  initialize: function(callback, frequency) {
    this.callback = callback;
    this.frequency = frequency;
    this.currentlyExecuting = false;

    this.registerCallback();
  },

  registerCallback: function() {
    this.timer = setInterval(this.onTimerEvent.bind(this), this.frequency * 1000);
  },

  stop: function() {
    if (!this.timer) return;
    clearInterval(this.timer);
    this.timer = null;
  },

  onTimerEvent: function() {
    if (!this.currentlyExecuting) {
      try {
        this.currentlyExecuting = true;
        this.callback(this);
      } finally {
        this.currentlyExecuting = false;
      }
    }
  }
}

var Abstract = new Object();

Abstract.Insertion = function(adjacency) {
  this.adjacency = adjacency;
}

Abstract.Insertion.prototype = {
  initialize: function(element, content) {
    this.element = $(element);
    this.content = content.stripScripts();

    if (this.adjacency && this.element.insertAdjacentHTML) {
      try {
        this.element.insertAdjacentHTML(this.adjacency, this.content);
      } catch (e) {
        var tagName = this.element.tagName.toUpperCase();
        if (['TBODY', 'TR'].include(tagName)) {
          this.insertContent(this.contentFromAnonymousTable());
        } else {
          throw e;
        }
      }
    } else {
      this.range = this.element.ownerDocument.createRange();
      if (this.initializeRange) this.initializeRange();
      this.insertContent([this.range.createContextualFragment(this.content)]);
    }
    //setTimeout(function() {content.evalScripts()}, 10);
  },

  contentFromAnonymousTable: function() {
    var div = document.createElement('div');
    div.innerHTML = '<table><tbody>' + this.content + '</tbody></table>';
    return $A(div.childNodes[0].childNodes[0].childNodes);
  }
}

var Insertion = new Object();

Insertion.Top = Class.create();
Insertion.Top.prototype = Object.extend(new Abstract.Insertion('afterBegin'), {
  initializeRange: function() {
    this.range.selectNodeContents(this.element);
    this.range.collapse(true);
  },

  insertContent: function(fragments) {
    fragments.reverse(false).each((function(fragment) {
      this.element.insertBefore(fragment, this.element.firstChild);
    }).bind(this));
  }
});


if (typeof HTMLElement != 'undefined') {
	HTMLElement.prototype.insertAdjacentElement = function(where, parsedNode) {
    switch (where.toLowerCase()) {
			case "beforebegin":
		    this.parentNode.insertBefore(parsedNode,this);
		    break;
			case "afterbegin":
				this.insertBefore(parsedNode,this.firstChild);
				break;
			case "beforeend":
				this.appendChild(parsedNode);
				break;
			case "afterend":
				if(this.nextSibling) {
				    this.parentNode.insertBefore(parsedNode,this.nextSibling);
				} else {
				    this.parentNode.appendChild(parsedNode);
				}
				break;
		}
	};
}

var DM72 = {
	DEBUG: true,
	
	debugAlert: function(info) {
		if (this.DEBUG) {
			alert('错误调试信息:' + info);
		}
	}
};

//工具类
var Util = {
	//得到url的绝对路径
	getFullUrl: function(url) {
		if (!url) {
			return null;
		}
		var image	=	new	Image();
		image.src = url;   
  	return image.src;   
  },
  
  //图片预载入
  preloadImage: function(imageList, onComplete) {
		var image = new Image();
	  var loadImage = function() {
	  	if (imageList.length > 0) { 
		  	var imageSrc = imageList.shift();
	  		image.onload = function() {
	  			window.setTimeout(function(){loadImage();}, 1);
	  		};
 	      image.onerror = function(){ 
         	window.setTimeout(function(){loadImage();}, 1);
        };
      	image.src = imageSrc;
	  	} else {
	  		if (onComplete) {
	  			window.setTimeout(function(){onComplete();}, 1);
	  		}
	  	}
  	};
  	loadImage();
    window.setTimeout(function() {
    	if (imageList.length > 0) {
    		loadImage();
    	}
   	}, 10000);
  },
  
  //调整图片大小，将图片限制在一定范围内
 	ajustImage: function(imageId, xLimit, yLimit) {
 		if (!$(imageId)) {
 			DM72.debugAlert('不存在image:' + imageId);
 			return false;
 		}
 		var image	=	new	Image();
 		image.src = $(imageId).src;
 		if ((xLimit > 0) && (yLimit > 0) &&
 				(image.width > xLimit) && (image.height > yLimit)) {
 			$(imageId).width = (xLimit < image.width * (yLimit / image.height)) ?
 					xLimit : (image.width * (yLimit / image.height));
 			$(imageId).height = (yLimit < image.height * (xLimit / image.width)) ?
 					yLimit : (image.height * (xLimit / image.width));
 		}
		else if ((xLimit > 0) && (image.width > xLimit)) {
			$(imageId).width = xLimit;
			$(imageId).height = image.height * (xLimit / image.width);
		}
		else if ((yLimit > 0) && (image.height > yLimit)) {
			$(imageId).height = yLimit;
			$(imageId).width = image.width * (yLimit / image.height);
		}
		else {
			if (xLimit !== 'undefined') {
				$(imageId).width = image.width;
			}
			if (yLimit !== 'undefined') {
				$(imageId).height = image.height;
			}
		}
 	},
 	
 	//firefox中url里[]显示的是%5B,%5D 这里要替换掉
 	srcFilter: function(html) {
 		return html.replace(/%5B/g, '[').replace(/%5D/g, ']');
 	},
 	
 	parseJson: function(json, obj) {
 		try {
			return eval('eval("(" + json.strip() + ")").' + (obj || 'dm72'));
		} catch (e) {
			DM72.debugAlert('数据格式错误！\n' + ((json.strip() === '') ? '数据为空' : json));
			return null;
		}
 	},
 	
 	getCurrentTime: function() {
 		var date = new Date();
 		var hours = date.getHours();
 		hours = (hours > 9) ? hours : '0' + hours;
 		var minutes = date.getMinutes();
 		minutes = (minutes > 9) ? minutes : '0' + minutes;
 		var seconds = date.getSeconds();
 		seconds = (seconds > 9) ? seconds : '0' + seconds;
 		return hours + ':' + minutes + ':' + seconds;
 	},
 	
 	notNull: function(value) {
 		if ((typeof value == 'undefined') || (value === null)) {
 			return '';
 		}
 		return value;
 	},
 	
 	toBoolean: function(value) {
 		if ((value === true) || (value == 'true')) {
 			return true;
 		} else {
 			return false;
 		}
 	},
 	
 	radioValue: function(element, form) {
 		form = form ? form : document.forms[0];
 		var radioList = Form.getInputs(form, 'radio', element);
 		for (var i = 0; i < radioList.length; i++) {
 			var radio = radioList[i];
 			if (radio.checked) {
 				return radio.value;
 			}
 		}
 		return null;
 	}
};

var ScreenLocker = {
	id: 'screen_locker',
	
	zIndex: 1000000,
	
	lock: function() {
		if (!$(this.id)) {
			var lockDiv = document.createElement('span');
			lockDiv.id = this.id;
			lockDiv.style.position = 'absolute';
			lockDiv.style.filter = 'alpha(opacity: 50)';
			lockDiv.style.opacity = 0.5;
			lockDiv.style.zIndex = this.zIndex;
			lockDiv.style.backgroundColor = 'rgb(238, 238, 238)';
			lockDiv.style.left = 0;
			lockDiv.style.top = 0;
			lockDiv.style.width = document.body.scrollWidth > document.body.clientWidth ?
							document.body.scrollWidth : document.body.clientWidth;
			lockDiv.style.height = document.body.scrollHeight > document.body.clientHeight ?
							document.body.scrollHeight : document.body.clientHeight;
			(new Insertion.Top(document.body, lockDiv.outerHTML)); 
		}
	},
	
	unlock: function() {
		if ($(this.id)) {
			Element.remove(this.id);
		}
	}
};
//对话框类
var Dialog = Class.create();

Object.extend(Dialog, {
	
	instance: [],

	getInstance: function(id) {
		if (!this.instance[id]) {
			DM72.debugAlert('调用Dialog.getInstance(id)出错，对象' + id + '未初始化!');
			return Dialog.prototype;
		}
		return this.instance[id];
	}
});

Object.extend(Dialog.prototype, {
	initialize: function(id, title) {
		this.id = id;
		this.title = title;
		this.options = Object.extend({
			url: null,
			width: 500,
			height: 400, 
      modal: false,
      zIndex: ScreenLocker.zIndex + 2,
      draggable: false,
      revert: false,
      windowName: window.name,
      dialogClass: 'dlg',
      titlebarClass: 'dlg_titlebar',
      titleClass: 'dlg_title',
      closeClass: 'dlg_close'
    }, arguments[2] || {});

		//使其能够在顶层窗口运行
		if (top.location.href != window.location.href) {
			this.options.url = Util.getFullUrl(this.options.url);
			if ((!this.options.url) && (!top.document.getElementById(id))) {
				top.document.body.insertAdjacentElement("BeforeEnd", $(id)); 
			}
		  top.eval(''.concat('new Dialog("', this.id, '","', this.title, '",',
		  		Object.toJSON(this.options),');')); 
			return;
		}
    if ((!$(id)) && (!this.options.url)) {
    	DM72.debugAlert('页面缺少' + id + '对象!');
    	return false;
    }
    Dialog.instance[id] = this;
    this.open();
	},
	
	open: function() {
		if (Dialog.getInstance(this.id).isOpen()) {
			return false;
		}
		this.openState = true;
		if (!this.options.modal) {
			ScreenLocker.lock();
		}

		var dialogDiv = $(this.id) ? $(this.id) : document.createElement('span');
		if (!$(this.id)) {
			document.body.insertAdjacentElement("AfterBegin", dialogDiv);   
		}
		dialogDiv.insertAdjacentElement("AfterBegin", this._createTitleBar());
		dialogDiv.id = this.id;
		dialogDiv.className = this.options.dialogClass;
		dialogDiv.style.position = 'absolute';
		dialogDiv.style.zIndex = this.options.zIndex;
		dialogDiv.style.width = this.options.width || dialogDiv.style.width;
		dialogDiv.style.height = this.options.height || dialogDiv.style.height;
		dialogDiv.style.left = (document.body.clientWidth - dialogDiv.offsetWidth) / 2 + document.body.scrollLeft;
		dialogDiv.style.top = (document.body.clientHeight - dialogDiv.offsetHeight) / 2 + document.body.scrollTop;
		dialogDiv.style.top = (dialogDiv.offsetTop > 10) ? dialogDiv.offsetTop : 10;
		if (this.options.url) {
			var iframeName = this.id + '_iframe';
			var iframe = Try.these(
				function() {return document.createElement('<iframe name="' + iframeName + '" >');},
				function() {return document.createElement('iframe');}
			);
			iframe.id = iframe.name = iframeName;
			iframe.width = '100%';
			iframe.height = dialogDiv.offsetHeight - 22;
			iframe.scrolling = 'no';
			iframe.frameBorder = 0;
			iframe.border = 0;
			dialogDiv.insertAdjacentElement("BeforeEnd", iframe);
			iframe.src = this.options.url;
		}
	},
	
	isOpen: function() {
		return this.openState;
	},
	
	close: function() {
		ScreenLocker.unlock();
		//解决在iframe中调用时ie文本框失去焦点问题
		if ($(this.id + '_iframe')) {
		 $(this.id + '_iframe').src = '';
		}
		Element.remove(this.id);
		this.openState = false;
	},
	
	getWindowName: function() {
		return this.options.windowName;
	},

	_createTitleBar: function() {
		var titleBarId = this.id + '_titlebar';
		var titleId = this.id + '_title';
		var closeId = this.id + '_close';
		var style = '';
		if (this.options.draggable) {
			style += 'cursor:move;';
		}
		var span = document.createElement('span');
		span.innerHTML = ''.concat(
			'<table id="', titleBarId, '" class="', this.options.titlebarClass, 
					'" style="', style, '" width="100%" border="0" cellspacing="0" cellpadding="0">',
			  '<tr>',
			  	'<td>',
						'<div id="', titleId, '" class="', this.options.titleClass, '">', 
							this.title,
						'</div>',
			  	'</td>',
				  '<td align="right">',
						'<div id="', closeId, '" class="', this.options.closeClass ,'">',
							'<a href="#" onclick="Dialog.getInstance(\'', this.id, '\').close();return false;">',
								'<input type="button" value="×"/>', 
							'</a>',
						'</div>',
					'</td>',
				'</tr>',
			'</table>');
		if (this.options.draggable) {
			html = html.concat(
			'<script>',
				'new Draggable("', this.id, '", {handle: "', this.options.titlebarClass ,'", revert:', this.options.revert, ', starteffect:null, endeffect:null} );',
			'</script>');
		}
		return span;
	}
});

//提示信息对话框
var MessageDialog = Class.create();

Object.extend(MessageDialog, {
	instance: null,

	getInstance: function() {
		return this.instance;
	}
});

Object.extend(MessageDialog.prototype, {
	initialize: function(title, content) {
		this.title = title;
		this.content = content;
		this.options = Object.extend({
			id: 'messge_dialog',
			modal: true,
			width: 400,
			height: 200,
			zIndex: ScreenLocker.zIndex + 3,
			autoClose: true,
			closeTime: 500,
			msgClass: 'msg_dlg',
			onClose: function() {}
		}, arguments[2] || {});
		
		MessageDialog.instance = this;
		this.open();
	},
	
	open: function() {
		var msgSpan = document.createElement('span');
		document.body.insertAdjacentElement("BeforeEnd", msgSpan);
		msgSpan.id = this.options.id;
		msgSpan.zIndex = this.options.zIndex;
		var innerHtml = ''.concat(
			'<table class="', this.options.msgClass ,'" width="100%" height="100%" border="0" cellspacing="0" cellpadding="0">',
				'<tr><td>', this.content || '', '</td></tr>',
			'</table>');
		msgSpan.innerHTML = innerHtml;
		(new Dialog(this.options.id, this.title || '提示信息', this.options));
		if (this.options.autoClose) {
			window.setTimeout((function () {
				MessageDialog.getInstance().close();
			}).bind(this), this.options.closeTime);
		}
	},
	
	isOpen: function() {
		return top.Dialog.getInstance(this.options.id).isOpen();
	},
	
	close: function() {
		top.Dialog.getInstance(this.options.id).close();
		this.options.onClose();
	}
});

//确认对话框
var ConfirmDialog = Class.create();

Object.extend(ConfirmDialog, {
	instance: [],

	getInstance: function(id) {
		if (!this.instance[id]) {
			DM72.debugAlert('调用ConfirmDialog.getInstance(id)出错，对象' + id + '未初始化!');
			return ConfirmDialog.prototype;
		}
		return this.instance[id];
	}
});

Object.extend(ConfirmDialog.prototype, {
	initialize: function(title, content) {
		this.title = title;
		this.content = content;
		this.options = Object.extend({
			id: 'confirm_dialog',
			modal: false,
			zIndex: ScreenLocker.zIndex + 4,
			width: 400,
			height: 150,
			onConfirm: function(){},
			confirmClass: 'confirm_dlg'
		}, arguments[2] || {});

		this.handle = (top.location.href != window.location.href) ? 
				('document.getElementById(\'' + window.name + '\').contentWindow.') : '';
		ConfirmDialog.instance[this.options.id] = this;
		this.open();
	},
	
	open: function() {
		var confirmSpan = document.createElement('span');
		confirmSpan.id = this.options.id;
		confirmSpan.zIndex = this.options.zIndex;
		var innerHtml = ''.concat(
			'<table class="', this.options.confirmClass ,'" width="100%" height="130" border="0" cellspacing="0" cellpadding="0">',
				'<tr><td align="center">', this.content, '</td></tr>',
				'<tr><td align="center">',
					'<input type="button" value="确  定" onclick="' + this.handle + 'ConfirmDialog.getInstance(\'', this.options.id, '\').confirm();"/>&nbsp;&nbsp;',
					'<input type="button" value="取  消" onclick="' + this.handle + 'ConfirmDialog.getInstance(\'', this.options.id, '\').close();"/>&nbsp;&nbsp;',
				'</td></tr>',
			'</table>');
		confirmSpan.innerHTML = innerHtml;
		top.document.body.insertAdjacentElement("BeforeEnd", confirmSpan);
		(new Dialog(this.options.id, this.title, this.options));
	},
	
	close: function() {
		top.Dialog.getInstance(this.options.id).close();
	},
	
	confirm: function() {
		this.options.onConfirm();
		this.close();
	}
});

//图片播放器
var PhotoPlayer = Class.create();
Object.extend(PhotoPlayer.prototype, {
	initialize: function(id, xLimit, yLimit) {
		this.id = id;
		this.xLimit = xLimit;
		this.yLimit = yLimit;
		this.photoList = [];
		this.playing = 0;
		this.playState = true;
	},
	
	add: function(photoUrl, browseUrl) {
		var photo = [];
		photo.photoUrl = photoUrl;
		photo.browseUrl = browseUrl;
		this.photoList[this.photoList.length] = photo;
	},
	
	show: function() {
		var html = [];
		for (var i = 0; i < this.photoList.length; i++) {
			var photo = this.photoList[i];
			html[i] = ''.concat(
				'<div id="picdiv', i, '" style="display:none;height:200px;width:auto;">',
					'<table width="100%" height="100%" border="0" cellspacing="0" cellpadding="0">',
						'<tr><td align="center" valign="middle">',
							'<a id="pica', i, '" href="', photo.browseUrl, '">',
								'<img border="0" id="pic', i, '" src="', photo.photoUrl, '"/>',
							'</a>',
						'</td></tr>',
					'</table>',
				'</div>');
		}
		$(this.id).innerHTML = html.join('');
		this.play(0);
	},
	
	play: function(index) {
		for (var i = 0; i < this.photoList.length; i++) {
			if (index == i) {
				Util.ajustImage('pic' + i, this.xLimit, this.yLimit);
				$('picdiv' + index).style.display = '';
			} else {
				$('picdiv' + i).style.display ='none';
			}
		}
		this.playing = index;
	},
	
	autoPlay: function(interval) {
		this.executer = (new PeriodicalExecuter((function(executer){
			this.next();
		}).bind(this), interval || 5));
		this.playState = true;
	},
	
	pause: function() {
		this.executer.stop();
		this.playState = false;
	},
	
	isPlaying: function() {
		return this.playState;
	},
	
	getPlaying: function() {
		return this.playing;
	},
	
	prev: function() {
		this.playing--;
		if (this.playing < 0) {
			this.playing = this.photoList.length - 1;
		}
		this.play(this.playing);
	},
	
	next: function() {
		this.playing++;
		if (this.playing == this.photoList.length) {
			this.playing = 0;
		}
		this.play(this.playing);
	}
});

//简化后的Submit类
var SimpleSubmit = Class.create();

Object.extend(SimpleSubmit, {
	
	showMessage: function(message, options) {
		(new MessageDialog('提示信息', message,
			Object.extend(options, {
				onClose: function() {
					if (!options.redirect) {
						return false;
					}
					if (options.dialogId) {
						var windowName = top.Dialog.getInstance(options.dialogId).getWindowName();
						(top.document.frames[windowName] || window).location.href = options.redirect;
					} else {
						if (Util.getFullUrl(options.redirect) == window.location.href){
							window.history.go(0);
						} else {
							window.location.replace(options.redirect);
						}
					}
				}
			})
		));
	}
});

Object.extend(SimpleSubmit.prototype, {
	initialize: function(formName, url) {
		this.formName = formName;
		this.form = $(formName) ? $(formName) : document.forms[formName];
		this.url = url;
		//this.url = Util.getFullUrl(url);
		this.options = Object.extend({
			redirect: null,
			lock: true,        //是否锁定屏幕
			processing: true, //是否显示“正在提交”提示
			dialogId: null,    //如果当前窗口在dialog中，则需传入dialog的Id
			message: true,     //是否显示返回信息
			msgClass: 'msg_dlg', //返回信息框的样式
			autoClose: true,   //返回信息是否自动关闭
			closeTime: 800,    //返回信息多久关闭
			onComplete: function(){}  //提交完成后执行的操作
    }, arguments[2] || {});

		//this.options.redirect = Util.getFullUrl(this.options.redirect);
    if (!this.form) {
    	DM72.debugAlert('页面缺少form:' + formName + '!');
    	return false;
    }
		if (MessageDialog.getInstance() &&
				MessageDialog.getInstance().isOpen()) {
			return false;
		}
    this._execute();
	},
	
	_execute: function() {
		if (this.options.lock) {
			ScreenLocker.lock();
		}
		if (this.options.processing) {
			this._processing(this.formName);
		}
		this._submit();
	},
	
	_processing: function() {
		var processSpan = document.createElement('span');
		this.processId = processSpan.id = this.formName + '_process';
		processSpan.style.position = 'absolute';
		processSpan.style.zIndex = ScreenLocker.zIndex + 1;
		processSpan.style.left = document.body.scrollWidth - 150;
		processSpan.style.top = document.body.scrollTop + 5;
		processSpan.innerHTML = '<div style="border-color:#550000;background-color:#6F6FFB;color:#ffffff;font-size:12px;">正在提交数据，请稍候...</div>';
		document.body.insertAdjacentElement('BeforeEnd', processSpan);
	},
	
	_submit: function() {
		var iframeName = this.formName  + '_iframe';
		var iframe = $(iframeName) ? $(iframeName) : this._createIframe(iframeName);
		this._checkResponse(iframe);
		this.form.action = this.url;
		this.form.target = iframeName;
		this.form.submit();
	},
	
	_createIframe: function(iframeName) {
		var iframe = Try.these(
			function() {return document.createElement('<iframe name="' + iframeName + '" >');},
			function() {return document.createElement('iframe');}
		);
		iframe.id = iframe.name = iframeName;
		iframe.style.display = 'none';
		document.body.insertAdjacentElement('BeforeEnd', iframe);
		return iframe;
	},
	
	_checkResponse: function(iframe) {
		(new PeriodicalExecuter((function(executer){
			var iframeHtml =  Try.these(
				function() {return document.frames[iframe.name].document.body.innerHTML;},
				function() {return $(iframe.id).contentDocument.body.innerHTML;}
			) || '';
			if (iframeHtml !== '') {
				iframeHtml = iframeHtml.unescapeHTML();
				this._response(iframeHtml);
				Try.these(
					function() {document.frames[iframe.name].document.body.innerHTML = '';},
					function() {$(iframe.id).contentDocument.body.innerHTML = '';}
				);
				executer.stop();
			}
		}).bind(this), 0.02));
	},
	
	_response: function(html) {
		ScreenLocker.unlock();
		if ($(this.processId)) {
			Element.remove(this.processId);
		}
		if (this.options.message) {
			(this.options.dialogId ? top : window). 
					SimpleSubmit.showMessage(html, this.options);
		}
		if (this.options.dialogId) {
			top.Dialog.getInstance(this.options.dialogId).close();
		}
		this.options.onComplete();
	}
});
