/* XsltParser - a jQuery plugin
 *
 * Making use of XSLT templates
 *
 * version 1.0
 * Author: Björn Wikström, bjorn.wikstrom@gmail.com
 * License: GNU LGPL <http://www.gnu.org/licenses/lgpl.html>
 * Copyright (c) 2010, Björn Wikström <bjorn.wikstrom@gmail.com>
 */

(function($) {
	
	$.fn.xsltParser = function(opts) {
		if (!opts || !opts['xml'] || !opts['xslt'])
			throw('Missing required options');
		
		this.options = {
			xml:        false,
			xslt:       false,
			onSend:     function() {},
			onStart:    function() {},
			onComplete: function() {}
		};
		for (prop in this.options) {
			if (opts[prop])
				this.options[prop] = opts[prop];
		}
		
		var _me            = this;
		this._container    = $(this);
		this._xmlDocument  = false;
		this._xsltDocument = false;
		
		this.fetch = function(url) {
			return $.ajax({
				async: false,
				url:   url,
				dataType: 'application/xhtml+xml',
				beforeSend: _me.options['onSend'](url)
			}).responseXML;
		};
		
		this.run   = function(xml, xslt) {
			if (window.ActiveXObject) {
				return xml.transformNode(xslt);
			} else if (document.implementation){
				var p = new XSLTProcessor();
				p.importStylesheet(xslt);
				return p.transformToFragment(xml, document);
			} else {
				throw('Browser does not support XSLT transformation');
			}
		};
		
		this.init  = function(xmlPath, xsltPath) {
			_me._xmlDocument =  _me.fetch(xmlPath);
			_me._xsltDocument = _me.fetch(xsltPath);
		};
		
		this.start   = function() {
			_me.options['onStart']();
			_me.init(_me.options['xml'], _me.options['xslt']);
			
			var content = _me.run(_me._xmlDocument, _me._xsltDocument);
			_me.html(content);
				
			_me.options['onComplete']();
		}
		
		this.start();
	}
	
})(jQuery);
