(function($){
	var template = '<div class="phWidget">' +
			'<h3>Widget Title</h3>' +
			'<select></select>' +
			'<div class="info"></div>' +
		'</div>';	
	
	// default options
	var defaults = {
		title: 'widget title',
		// time at which pharmacy changes to next
		changeAt: '8',
		xmlPath : 'farmacias.xml'
	};
	
	$.phWidget = function(parent, options){
			// farmacias-servico element that will contain our widget
		var parent = $(parent),
			// content of the xml file containing details/schedule about pharmacies
			scheduleXml = '',
			// use default options in not set some fields
			options = $.extend({}, defaults, options),					
			// will contain widget
			widgetEl = $(template)
				.addClass('loading')
				.appendTo(parent);

		// Create a title
		widgetEl.find('h3').text(options.title);		

		$.ajax({
			type: "GET",
			url: options.xmlPath,
			dataType: "xml",
			success: onLoad
		});
		
		/**
		 * When xml is loaded
		 */
		function onLoad(responseXml){
			widgetEl.removeClass('loading');
			// save response
			scheduleXml = responseXml;
			
			// create dropdown
			var select = widgetEl.find('select').change(function(){
				showInfo($(this).val())
			});
					
			$(scheduleXml).find('city').each(function(){
				var name = $(this).attr('name');
				$('<option></option>').attr({
					value: name
				}).text(name).appendTo(select);
			});
			
			showInfo(select.val());			
		}
		
		/**
		 * When another option of dropdown/select is selected 
		 * @param selectedCity name of the city information about we need
		 */
		function showInfo(selectedCity){
			// drugstore xml node
			var d = getDrugstore(selectedCity);

			var html = '<p class="nome">' + d.attr('name') + '</p>' +
				'<p>' + d.attr('address') + '<br />' +
				(d.attr('phone') ? '' + d.attr('phone') + '<br />' : '') +
				(d.attr('info') ? '' + d.attr('info') + '</p>' : '');		
			
			widgetEl.find('.info').html(html);
		}	
		
		/**
		 * Gets drugstore that is opened tonight in the provided city
		 */
		function getDrugstore(cityName){
			// get all info about all drugstores
			var drugstores = $(scheduleXml).find('city[name="'+cityName + '"] drugstores');
			
			var now = new Date();
			
			// get a date at which first drugstore start working
			var startDate = new Date(drugstores.attr('startdate'));		
			
			var secondsInDay = 1000 * 60 * 60 * 24 ;
			// options.changeAt = at which hour drugstores change
			var changeTimeOffset = options.changeAt * 1000 * 60 * 60;
			
			var diff = Math.floor((now.getTime() - (startDate.getTime() + changeTimeOffset) ) / secondsInDay);			
			
			// number of drugstores in a city
			var count = drugstores.find('drugstore').length;
			// days each drugstore is working in a row
			var days = drugstores.attr('days');			
			// get the index of drugstore that is open now
			var index = Math.floor(diff / days) % count;
			
			return drugstores.find('drugstore').eq(index);			
		}				
	};
})(jQuery);
