/*
	Mechanize.js
	BSD license
*/
var Mechanize;
(function(){

function foreach(array,callback){
	for(var i=0;i<array.length;i++){
		callback(array[i],i,array)
	}
}

Mechanize = function(){
	if(typeof WScript != "undefined")
		this.IE = WScript.CreateObject("InternetExplorer.Application")
	else
		this.IE = new ActiveXObject("InternetExplorer.Application");
};
Mechanize.prototype = {
	show : function(){
		this.IE.Visible = true;
	},
	hide : function(){
		this.IE.Visible = false;
	},
	get : function(url){
		this.IE.Navigate(url);
		this._wait();
	},
	get_document : function(){
		return this.IE.Document
	},
	title : function(){
		return this.get_document().title
	},
	links : function(){
		return this.get_document().links
	},
	submit_form : function(param){
		var doc = this.get_document();
		var frm = doc[param.form_name];
		var f = param.fields;
		for(var i in f){
			if(!frm[i]) continue;
			if(frm[i].length && !frm[i].type){
				// radio button
				// alert(frm[i].type);
				foreach(frm[i],function(elm){
					elm.value == f[i] && (elm.checked = true);
				})
			} else if(frm[i].type == "checkbox"){
				frm[i].checked = true;
			} else {
				frm[i].value = f[i]
			}
		}
		if(param.button){
			var elms = frm.elements;
			for(var i=0;i<elms.length;i++){
				var e = elms[i];
				if(e.name == param.button){
					e.click();
					break;
				}
			}
		}else{
			frm.submit();
		}
		this._wait();
	},
	_wait : function(){
		while(this.IE.busy) ;
		while(this.IE.Document.readyState != "complete");
	}
}
})();
