/**
 * @author Giovanni Buffa
 * Copyright 2009 - simply@amp-gioppy.com
 * 
 * Under CC-License
 * 
 * Plugin for jQuery to navigate the tree of the XML file and return the value of a node randomly.
 */

(function($){
	$.fn.xmlTree = function(options){
		var defaults = {
			//the url of the XML
			XMLurl: '',
			//the ID of the section
			section: '',
			//the ID of the div content
			IMGcontent: '',
			//OPTINALS
			//the color of the background
			//BGcolor: '',
			//root directory
			//DIRroot: ''
		}
			
			var options = $.extend(defaults, options);
			
			return this.each(function(){
				function parseXml(xml) {   
					if (jQuery.browser.msie) {   
						var xmlDoc = new ActiveXObject("Microsoft.XMLDOM");   
						xmlDoc.loadXML(xml);   
						xml = xmlDoc;   
					}
					return xml;   
				}
				$.ajax({
					type: "GET",
					url: options.XMLurl,
					dataType: ($.browser.msie) ? "text" : "xml",
					success: function(xml){
					var newXML = parseXml(xml);
						$(newXML).find("sezione").each(function(){
							imgArray = new Array();
							var id = $(this).attr('id');
							var title = $(this).attr('title');
							
							if(id == options.section){
								$(this).find('immagine').each(function(){
									var img = $(this).attr('src');
									imgArray.push(img);
								});
								var total = imgArray.length;
								//$(options.IMGcontent).css("background", "url("+options.DIRroot+imgArray[Math.floor(total * Math.random())]+") no-repeat"+options.BGcolor);
								$(options.IMGcontent).html('<img src="'+imgArray[Math.floor(total * Math.random())]+'" alt="" />');
							}
						});
					}
				});
			});
	}
})(jQuery);
