function Luckit(serviceUrl, defaultMode) {
	var defaults = {
		SERVICE_URL:     'luckit_proxy.php?service=search',
		DEFAULT_MODE:    'javascript',
		MODE_JAVASCRIPT: 'javascript',
		MODE_JSON:       'json'
	};
	
	for (i in defaults)
		this[i] = defaults[i];

	if (arguments.length==1 && typeof arguments[0]=='object') {
		for (prop in arguments[0])
			this[prop] = arguments[0][prop];
	} else {
		if (serviceUrl) this.SERVICE_URL = serviceUrl;
		if (defaultMode) this.DEFAULT_MODE = defaultMode;
	}
}

Luckit.prototype.newQuery = function(terms, success, failure, mode) {
	return new LuckitQuery(this, terms, success, failure, mode);
}

function LuckitQuery(controller, terms, success, failure, mode) {
	this.controller = controller;

	this.success = success;
	this.callback = { success:this.handleSuccess, failure:failure||this.handleFailure, scope:this };
	this.mode = mode||this.controller.DEFAULT_MODE;
	this.terms = terms;
}

LuckitQuery.prototype.search = function(opts) {
	if (!opts) opts = {};
	
	var params = {};
	
	if (typeof(opts.limit)  != 'undefined') params.limit  = opts.limit;
	if (typeof(opts.offset) != 'undefined') params.offset = opts.offset;
	
	var url = this.controller.SERVICE_URL+'&mode='+this.mode;
	
	for (var i in params)
		url += '&' + i + '=' + escape(params[i]);
	
	YAHOO.util.Connect.initHeader('Content-Type','text/xml;charset=utf-8');

	var ro = YAHOO.util.Connect.asyncRequest(
		"POST", 
		url,
		this.callback,
		this.generatePayload()
	);
	
	if (typeof(opts.returnRequestObject) != 'undefined' && opts.returnRequestObject)
		return ro;
	else
		return false; // for easy form onsubmit handling
}

LuckitQuery.prototype.handleFailure = function(r) {
	alert('There was an error: '+r.status+' '+r.statusText);
}

LuckitQuery.prototype.handleSuccess = function(o) {
	var r = eval(o.responseText);
	this.success(r);
}

LuckitQuery.prototype.generatePayload = function() {	
	if (!this.payload)
		this.payload = '<query>' + this.makeXmlFromArray(this.terms) + '</query>';

	return this.payload;
}

LuckitQuery.prototype.makeXmlFromArray = function(terms) {	
	var xml = '';
	
	for (var i=0; i < terms.length; i++) {
		var term = terms[i];

		xml += '<' + term._type;
		
		for (var j in term)
			if (j.charAt(0) != '_')
				xml += ' ' + j + '="' + escapeXML(term[j]) + '"';
				
		if (term._terms)
			xml += '>' + this.makeXmlFromArray(term._terms) + '</' + term._type + '>';
		else
			xml += '/>';
	}
	
	return xml;
	
	// copied from kitsite-cms/kit/core.js, 2006-07-11
	function escapeXML(txt, sq) { 
		if (txt==undefined||txt==null||txt=='') return '';
		if (txt.replace) { // ie. it is a string, and not, say, a number
			txt = txt.replace(/&nbsp;/g, String.fromCharCode(160));
			txt = txt.replace(/&shy;/g, String.fromCharCode(173));
			txt = txt.replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/\n/g,'&#xA;');
			if (!sq) txt = txt.replace(/"/g,'&quot;');
		}
		return txt;
	}
}

function LuckitResults(total, offset, pagesize, results) {
	this.total = total;
	this.offset = offset;
	this.pagesize = pagesize;
	this.results = results;
}

function LuckitDocument(id, fields) {
	this.id = id;
	this.fields = fields||[];
}

LuckitDocument.prototype.getField = function(name, all) {
	if (!all) {
		for (var i=0; i < this.fields.length; i++)
			if (this.fields[i].name==name)
				return this.fields[i].value;
		return '';
	} else {
		var values = [];

		for (var i=0; i < this.fields.length; i++)
			if (this.fields[i].name==name)
				values.push(this.fields[i].value);

		return values;
	}
}

function LuckitField(name,value) {
	this.name = name;
	this.value = value;
}

function LuckitTotal(count,fields) {
	this.count = count;
	this.fields = fields;
}

// TODO: pagination
