/*
	ajaxPro plugin for jQuery
	
	expects options in the following format
	
	var opts = {
		className : 'className',
		classLibrary : 'classLibrary',
		method : 'methodName',
		data : { json data },
		success : handler
	}	
*/

jQuery.ajaxPro = function(opts) {

	var dataString = '{}';
	
	if (!opts.classLibrary)
		opts.classLibrary = 'MatchClassLibraries';
		
	if (opts.data)
		dataString = JSON.stringify(opts.data)
	
	$jq.ajax({
        type: "POST",
        url: "/ajaxpro/" + opts.className + "," + opts.classLibrary + ".ashx",
        data: dataString,
        dataType: "json",
        beforeSend: function(xmlhttp) {
			xmlhttp.setRequestHeader("Ajax-method", opts.method);
        },
        success: opts.success
    });
}

/* jQuery selectbox related plugins */

jQuery.fn.containsOption = function(query) {
	var found = false;
	
	this.each(
		function() {
			if (this.nodeName.toLowerCase() == 'select') {
				for (var i = 0; i < this.options.length; i++) {
					if (query.value) {
						found = (query.value.constructor == RegExp) ? 
							this.options[i].value.match(query.value) : 
							this.options[i].value == query.value;
					} else if (query.text) {
						found = (query.text.constructor == RegExp) ? 
							this.options[i].text.match(query.text) : 
							this.options[i].text == query.text;
					}
					
					if (found)
						break;
				}
			} else return this;
		}
	);
	
	return found;
};

jQuery.fn.addOption = function(o) {
	var opt = o;
	
	this.each(
		function()
		{
			if (this.nodeName.toLowerCase() == 'select') {
				var option = document.createElement('OPTION');
				option.value = opt.value;
				option.text = opt.text;
				
				if (opt.selected)
					option.selected = opt.selected;
		
				this.options[this.options.length] = option;
			}
			else return this;
		}
	);
	
	return this;
};

jQuery.fn.clearOptions = function() {
	this.each(
		function () {
			if (this.nodeName.toLowerCase() == 'select') {
				this.options.length = 0;
			}
		}
	);
};

jQuery.fn.removeOption = function(val) {
	this.each(
		function() {
			if (this.nodeName.toLowerCase() == 'select') {
				for (var i = 0; i < this.options.length; i++) {
					if (this.options[i].value == val) {
						this.options[i] = null;
					}
				}
			} else return this;
		}
	);
	
	return this;
};

jQuery.fn.selectOptionByValue = function(val) {
	this.each(
		function() {
			if (this.nodeName.toLowerCase() == 'select') {
				for (var i = 0; i < this.options.length; i++) {
					if (this.options[i].value == val) {
						this.options[i].selected = true;
					}
					else {
						this.options[i].selected = false;
					}
				}
			} else return this;
		}
	);
	
	return this;
};