/*
 * @namespace NTFU public namespace for NTFU widget
 */
var NTFU = window.NTFU || {};

/*
 * General function to do JSONP requests
 * @param {string} url
 */ 
NTFU.doRequest = function(url) {
	var head = document.getElementsByTagName('head')[0];
	
	var script = document.createElement('script');
	script.type = 'text/javascript';
	script.src = url;
	
	head.insertBefore(script, head.firstChild);

	return script;
};

/*
 * General function to add a stylesheet
 * @param {string} url
 */ 
NTFU.loadStylesheet = function (url) {
   var link = document.createElement("link");
   link.rel = "stylesheet";
   link.type = "text/css";
   link.href = url;
   
   document.getElementsByTagName("head")[0].appendChild(link);
};

/*
 * General function to get an element by his id
 * @param {string} url
 */ 
NTFU.byID = function (id) {
	return document.getElementById(id);
};

/*
 * General function to get (an) element(s) by classname
 * @param {element} element
 * @param {string} className
 * @param {bool} optAll
 */
NTFU.byClass = function (element, tag, className, optAll) {
	var collection = [];
    var elements = element.getElementsByTagName(tag);

	for (var i in elements) {
		if(elements[i].className == className) {
			collection[collection.length] = elements[i];
		}
	}

	return (optAll) ? collection : collection[0];
};

/*
 * Add a classname to a given element
 * @param {element} element
 * @param {string} className
 */
NTFU.addClass = function (element, className) {
	element.className += ' ' + className;
};

(function () { 
	if (NTFU && NTFU.Widget) {
		return;
	}
	
	/*
     * Constructor for new instances of the NTFU widget
     * @param {object} opts the configuration options for the widget
     */
	NTFU.Widget = function (opts) {
		this.init(opts);
	};
	
	/*
	 * Widget counter
	 */
	NTFU.Widget.counter = 0;

	NTFU.Widget.prototype = function () {
		// the url to base the image and css path on
		var baseUrl = 'http://www.ntfu.nl/portals/0/formulieren/widget/';
		
		return {
			init: function (opts) {
				var that = this;
				
				opts = opts || {};
				
				this._baseUrl = baseUrl;
				this._widgetNumber = ++NTFU.Widget.counter;
				this._cssClass = 'ntfu-wg';
				
				// make an unique callback function
				NTFU.Widget['receiveCallback_' + this._widgetNumber] = function (response) {
					that._display.call(that, response);
				};
				
				// each widget has his own callback function
				this._callback = 'NTFU.Widget.receiveCallback_' + this._widgetNumber;
				
				this.id = opts.id || 'ntfu-wg-' + this._widgetNumber;
				this.tourtype = opts.tourtype || false;
				this.zipcode = opts.zipcode || 0;
				this.radius = opts.radius || 0;
				this.size = opts.size || 300;
				
				// check if zipcode and radius set, else show all tours
				this._allTours = false;
				if(this.zipcode == 0 || this.radius == 0)
					this._allTours = true;
				
				// set size of widget
				this.setSize(this.size);
				
				document.write('<div class="' + this._cssClass + '" id="' + this.id + '" style="width: ' + this.size + 'px;"></div>');
				
				// put html element in variable
				this._widget = NTFU.byID(this.id);
				
				// set the correct urls from the base url
				this._setUrls();
				
				return this;
			},

			// function to render the widget
			render: function () {   
				NTFU.loadStylesheet(this._cssUrl);
				
				this._widget.innerHTML = this._getWidgetHTML();
								
				return this;
			},
	
			// function to start the widget
			start: function () {
				NTFU.doRequest(this._requestUrl);
          		
				return this;
			},
			
			// private function to display callback data 
			_display: function (response) {				
				var tourtype = response['tourtype'];
				var radius = response['radius'];
				var zipcode = response['zipcode'];
				var feed = response['feed'];
				var items = response['items'];
				var totals = response['totals'];
				
				this.setRss(feed['title'], feed['url']);
				
				this.setPreferences(tourtype, radius, zipcode)
				
				this.setItems(items);
				
				this.setFooter(totals['count'], totals['url']);
			},
			
			// function to set an rss item in the widget
			setRss: function (title, url) {
    			if(this.size < 200 && title.length > 20) {
					title = title.substring(0, 20);
					title += '...';
    			}
    			else if(this.size >= 200 && this.size < 250 && title.length > 30) {
    				title = title.substring(0, 30);
					title += '...';
    			}
    			else if(this.size >= 250 && this.size < 300 && title.length > 40) {
    				title = title.substring(0, 40);
					title += '...';
    			}
        		else if(this.size >= 300 && title.length > 50) {
    				title = title.substring(0, 50);
					title += '...';
    			}
        		
        		var a = document.createElement('a');
        		a.appendChild(document.createTextNode(title));
        		a.target = '_blank';
        		a.href = url;
        		a.title = title;

        		NTFU.byClass(this._widget, 'div', 'ntfu-rss', false).appendChild(a);
        	},
			
			// function to set the user set preferences
			setPreferences: function (tourtype, radius, zipcode) {
				var ul = document.createElement('ul');
				
				var li = document.createElement('li');
				li.appendChild(document.createTextNode(tourtype));
				ul.appendChild(li);	
				
				if(!this._allTours) {
					var li = document.createElement('li');
					
					if(this._fullSize) {
						li.appendChild(document.createTextNode('In een straal van ' + radius + ' km rond postcode ' + zipcode));
					}
					else {
						li.appendChild(document.createTextNode('Straal van ' + radius + ' km'));
					}
						
					ul.appendChild(li);	
				}
				
				NTFU.byClass(this._widget, 'div', 'ntfu-set', false).appendChild(ul);
				
				if(!this._allTours) {
					var span = document.createElement('span');
					span.appendChild(document.createTextNode(zipcode));
					
					var div = document.createElement('div');
					div.appendChild(span);
					
					NTFU.byClass(this._widget, 'div', 'ntfu-set', false).appendChild(div);
				}
			},
			
			// function to set the received item to the widget
			setItems: function (items) {
				var itemCount = items.length;
				
				var ul = document.createElement('ul');
				
				if(itemCount > 0) {			
					for(var i = 0; i < itemCount; i++) {
						var item = items[i];

						if(item == undefined)
							continue;
						
						var li = document.createElement('li');
						
						if(document.compatMode == 'BackCompat')
							li.style.width = (this.size - 10) + 'px';
						else
							li.style.width = (this.size - 29) + 'px';
						
						var span = document.createElement('span');
						span.className = 'ntfu-tr-date';

						var day = document.createElement('span');
						day.appendChild(document.createTextNode(item['day']));
						day.className = 'ntfu-tr-day';
						span.appendChild(day);
						
						var month = document.createElement('span');
						month.appendChild(document.createTextNode(item['month']));
						month.className = 'ntfu-tr-month';
						span.appendChild(month);
	
						li.appendChild(span);
						
						if(this._fullSize) {
							var a = document.createElement('a');
							a.className = 'ntfu-tr-name';
							
							if(document.compatMode == 'BackCompat')
								a.style.width = (this.size - 132) + 'px';
							else
								a.style.width = (this.size - 151) + 'px';
							
							a.target = '_blank';
							a.href = item['url'];
							a.appendChild(document.createTextNode(item['name']));
		        			a.title = item['name'];
		        			
		        			li.appendChild(a);
		        			
		        			var a = document.createElement('a');
		        			a.className = 'ntfu-tr-city';
							a.style.width = '100px';
		        			a.target = '_blank';
							a.href = item['url'];
							a.appendChild(document.createTextNode(item['city']));
		        			a.title = item['city'];
		        			
		        			li.appendChild(a);
						}
						else {
							var a = document.createElement('a');
							a.className = 'ntfu-tr-name-city';
							a.target = '_blank';
							a.href = item['url'];
							a.appendChild(document.createTextNode(item['name'] + ', ' + item['city']));
		        			a.title = item['name'] + ', ' + item['city'];
		        			
		        			li.appendChild(a);
						}

						ul.appendChild(li);	
					}
				}
				else {
					var span = document.createElement('span');
					span.appendChild(document.createTextNode('Geen toertochten gevonden.'));
					
					var li = document.createElement('li');
					li.appendChild(span);
					
					ul.appendChild(li);	
				}
				
				NTFU.byClass(this._widget, 'div', 'ntfu-trs', false).appendChild(ul);
			},

			// function to set the footer of the widget
        	setFooter: function (count, url) {
        		if(this._allTours)
        			return;
        			
        		var title = '';
        		
        		if(this._fullSize)
        			title = 'Bekijk meer toertochten in de regio';
        		else
        			title = 'Meer in de regio';
        		
        		title += ' (' + count + ')';	
        			
        		var a = document.createElement('a');
        		a.appendChild(document.createTextNode(title));
        		a.href = url;
        		a.target = '_blank';
        		a.title = title;

        		NTFU.byClass(this._widget, 'div', 'ntfu-ftr-fill', false).appendChild(a);
        	},
			
			// function to set the size of the widget
			setSize: function (size) {
				if(size < 160)
					this.size = 160;
				else if(size > 300)
					this.size = 300;
				else
					this.size = size;

				this._fullSize = (this.size == 300);
				
				if(this._fullSize)
					this._cssClass += ' ntfu-wg-full';
			},
			
			// private function to get the widget html
			_getWidgetHTML: function () {
				var className = (this._fullSize) ? 'ntfu-doc-full' : 'ntfu-doc';
				var allToursTitle = (this._fullSize) ? 'Bekijk alle tochten in Nederland' : 'Alle tochten in Nederland';
				
				var html = '\
					<div class="' + className + '">\
				 		<div class="ntfu-top">\
				 			<div class="ntfu-top-left">\
				 			<div class="ntfu-top-right">\
				 			<div class="ntfu-top-fill">\
				 				<a href="http://www.ntfu.nl" title="NTFU" target="_blank">\
				 					<img src="' + this._imageUrl + 'logo.png" width="90" height="60" style="border: 0px none;" />\
				 				</a>\
				 			</div></div></div>\
				 		</div>\
				 		<div class="ntfu-bdy">\
				 			<div class="ntfu-bdy-left">\
				 			<div class="ntfu-bdy-right">\
				 			<div class="ntfu-bdy-fill">\
						 		<div class="ntfu-rss">\
						 			<img src="' + this._imageUrl + 'rss.png" width="27" height="18" style="margin:0px; padding:0px; border: 0px none; float: left;" />\
						 		</div>\
						 		<div class="ntfu-set"></div>\
						 		<div class="ntfu-trs"></div>\
						 		<div class="ntfu-all">\
						 			<a href="' + this._allToursUrl + '" title="' + allToursTitle + '" target="_blank">' + allToursTitle + '</a>\
						 		</div>\
						 	</div></div></div>\
					 	</div>\
				 		<div class="ntfu-ftr">\
				 			<div class="ntfu-ftr-left">\
				 			<div class="ntfu-ftr-right">\
				 			<div class="ntfu-ftr-fill">\
				 			</div></div></div>\
				 		</div>\
				 		<div class="ntfu-get">\
				 			<a href="' + this._getWidgetUrl + '" title="NTFU widget ook op uw website?" target="_blank">NTFU widget ook op uw website?</a>\
				 		</div>\
					 </div>\
				';

				return html;
			},
			
			// private function to set the correct urls
			_setUrls: function () {
				this._requestUrl  = this._baseUrl + 'widget.asp';
				this._requestUrl += '?callback=' + this._callback;
				this._requestUrl += '&tourtype=' + this.tourtype;
				this._requestUrl += '&zipcode=' + this.zipcode;
				this._requestUrl += '&radius=' + this.radius;
				this._requestUrl += '&' + (+new Date); // prevent caching
				
				this._cssUrl = this._baseUrl + 'widget.css';
				
				this._imageUrl = this._baseUrl + '';
				
				this._allToursUrl = 'http://www.ntfu.nl/Kalender/Kalender.aspx';
				
				this._getWidgetUrl = 'http://www.ntfu.nl/Kalender/Kalenderwidget.aspx';
				
				return this;
			}
		};
	}();
})();
