/*
**
**	jquery.ORjson.js - jQuery Plugin for manipulating ORHC Data
**	Author: 		Adrian Fowler
**	
*/

(function( $ ){
	$.fn.ORjsonHTML = function(options) {

		// default values
		var defaults = {
			'url'					:	undefined,		// url or array or urls of remote JSON data to get
			'src'					:	undefined,		// directly input JSON data object
			'type'				:	'table',			// type of table to draw
			'theme'				:	'fitTabGreen',	// css theme for table
			'header'				:	true, 			// enable thead row
			'arrayToHide'		:	['hidden'],		// array of column names to hide
			'over'				:	true,				// add a css change as mouse travels over row
			'striping'			:	true,				// stype alternate rows
			'numbered'			:	false,			// add column with row numbers
			'append'				:	false,			// append table rather than replace
			'suffix'				:	undefined,		// string of html to add at end
			'stringifyArray'	:	undefined,		// trigger to manipulate JSON array into a string based
															//  on this header value

			'linkHrefUrl'		:	undefined,		// link url to prepend
			'linkHrefField'	:	undefined,		// link ref to suffix to url
			'popUpWidth'		:	400,				// link popup width
			'popUpHeight'		:	300,				// link popup height
			'noHighslide'		:	false,			// create new windows rather than highslide popup

			'pageId'				:	'pager',			// default id for paging function
			'rowsPerPage'		:	10					// no of rows per page
		};

		var opts = $.extend(defaults, options);
		
		/*
		**	MAIN PLUGIN CODE
		*/
 		return this.each(function() {

 			//Show the 'loading' image
 			var loading = '<div id="loading"><img src="images/loading.gif" alt="" border="0"></div>';
			if (opts.append) {
	 			$(this).append(loading);
			} else {
	 			$(this).html(loading);
			}
 			
 			// Check if data supplied directly or needs to be received remotely
			var remote = [];
 			if(opts.url) {
 				if ((typeof opts.url == 'object') && (opts.url.length)) {	// this denotes an array
					for (var i in opts.url) {
						$.extend(true, remote, getJSONData(opts.url[i], opts.stringifyArray[i]));
					}
				} else {
					remote = getJSONData(opts.url, opts.stringifyArray);
				}
			} else {
				remote = typeof opts.src != 'object' ? $.parseJSON(opts.src) : opts.src;
			}
			
			var output = '';
			if (remote != []) {
				// Render JSON to required HTML format
				switch(opts.type) {
					case 'table':
						output = DrawTableList(remote);
						break;
					case 'detail':
						output = DrawDetailView(remote);
						break;
					case 'newslist':
						output = DrawNewsList(remote);
						break;
					case 'newsitem':
						output = DrawNewsItem(remote);
						break;
					case 'slideshow':
						output = DrawSlideShow(remote);
						break;
				}
				// add any suffix string
				if (opts.suffix) {
					output += opts.suffix;
				}
			} else {
				output = 'No data retrieved.';
			}
			
			// Write to page
			if (opts.append) {
				$('#loading').hide();
				$(this).append(output);
			} else {
				$(this).html(output);
			}
			// add pagination
			if (!(opts.pageId == 'pager' || output == 'No data retrieved.' || output == [])) {
				$('#' + opts.pageId).addTablePager({results : opts.rowsPerPage, id : opts.pageId});
			}
			
			// Set table zebra striping and mose hover, if required
			if (opts.striping) {
				$('.' + opts.theme + ' tr:nth-child(even)').addClass("alt");
			}
			if (opts.over) {
				$('.' + opts.theme + ' tr').mouseover(function(){$(this).addClass("over");}).mouseout(function(){$(this).removeClass("over");});
			}
		});


		/*
		**	JSON Rendering Functions
		*/
		
		// creates a standard table with column/rows
		function DrawTableList(array) {
			var str = '';
			if (array != null) {
				str = '<table id="' + opts.pageId + '" class="' + opts.theme + '">';
				if (opts.header == true) {
					str += '<thead><tr>';
					if (opts.numbered) {
					 str += '<th scope="col">#</th>';
					}
					for (var index in array[0]) {
						if (grepArray(opts.arrayToHide, index) == false){
							str += '<th scope="col">' + index.replace(/_/g, '&nbsp;') + '</th>';
						}
					}
					str += '</tr></thead>';
				}

				str += '<tbody>';
				for (var row = 0; row < array.length; row++) {
					if (!(opts.linkHrefField == null) && !(opts.linkHrefUrl == null) && !(array[row][opts.linkHrefField] == null)) {
						if (opts.noHighslide == false) {
							 str += '<tr class="pointer" onclick="OpenHighSlide(\'' + opts.linkHrefUrl + array[row][opts.linkHrefField] + '\',' + opts.popUpWidth + ','  + opts.popUpHeight + ',undefined);">';
						} else {
							 str += '<tr class="pointer" onclick="window.location.href=\'' + opts.linkHrefUrl + array[row][opts.linkHrefField] + '\';">';
						}
					} else {
						str += '<tr>';
					}
					if (opts.numbered) {
					 str += '<td align="right">' + (row + 1) + '</td>';
					}
					for (var index in array[row]) {
						if (grepArray(opts.arrayToHide, index) == false){
							if (array[row][index] == null) {
							 str += '<td></td>';
							} else {
								if (index.toLowerCase() == 'email') {
									if (array[row][index].lastIndexOf("@") == array[row][index].length - 1) {
										str += '<td><a href="mailto:' + array[row][index] + EmailValidDomain + '">' + array[row][index] + EmailValidDomain + '</a></td>';
									} else {
										str += '<td><a href="mailto:' + array[row][index] + '">' + array[row][index] + '</a></td>';
									}
								} else if (index.toLowerCase() == 'time') {
									str += '<td align="right">' + array[row][index].split(':', 2).join(':') + '</td>';
								} else if (index == '%') {
									str += '<td align="right">' + array[row][index].toFixed(2) * 100 + '</td>';
								} else {
									if (isNaN(array[row][index]) == true) {
										str += '<td>' + array[row][index].replace(/\r\n\r\n/g, '<br /><br />') + '</td>';
									} else {
										str += '<td align="right">' + array[row][index] + '</td>';
									}
								}
							}
						}
					}
					str += '</tr>';
				}
				str += '</tbody>'
				str += '</table>';
				return str;
			
			} else {
				return 'No data retrieved.';
			}
		}
		
		// creates a details view table with column 1 as the header and column 2 as the details
		function DrawDetailView(array) {
			var str = '<table id="' + opts.pageId + '" class="' + opts.theme + '">';
			str += '<tbody>';
			for (var row = 0; row < array.length; row++) {
				for (var index in array[row]) {
					if (grepArray(opts.arrayToHide, index) == false){
						str += '<tr>';
						if (opts.header) {
							str += '<th scope="row">' + index.replace(/_/g, '&nbsp;') + '</th>';
						}
						if (array[row][index] == null) {
							str += '<td></td>';
						} else {
							if (index.toLowerCase() == 'time') {
								str += '<td>' + array[row][index].split(':', 2).join(':') + '</td>';
//							} else if (index.toLowerCase() == 'date') {
//								str += '<td>' + formatORdate(array[row][index]) + '</td>';
							} else {
								if (isNaN(array[row][index]) == true) {
									str += '<td>' + array[row][index].replace(/\r\n\r\n/g, '<br /><br />') + '</td>';
								} else {
									str += '<td align="right">' + array[row][index] + '</td>';
								}
							}
						}
						str += '</tr>';
					}
				}
			}
			str += '</tbody>'
			str += '</table>';
			return str;
		}
		
		// creates an informal table of news with highslide popups
		function DrawNewsList(array) {
			var str = '<table id="' + opts.pageId + '" class="' + opts.theme + '">';
				str += '<tbody>';
			for (var row = 0; row < array.length; row++) {
//				var title = formatORdate(array[row].Date) + ' - ' + array[row].Title;
				var title = array[row].Date + ' - ' + array[row].Title;
				str += '<tr><td>';
				if (array[row].Detail == null) {
					array[row].Detail = '';
				}
				if ((array[row].FileSize == null) || (array[row].FileSize == 0)) {
					str += '<h4 class="ui-corner-all">' + title + '</h4>';
				} else {
//					str += '<div class="i80-20l"><h4 class="ui-corner-all">' + title + '</h4></div><div class="i80-20r"><h4 align="right" class="ui-corner-all">' + formatBytes(array[row].FileSize) + '</h4></div>'
					str += '<h4 class="ui-corner-all">' + title + '&nbsp;&nbsp;[' + formatBytes(array[row].FileSize) + ']</h4>'
				}

				str += '<div>';
				if (array[row].FileType == true) {
					if (!(array[row].FileName == null)) {
						str += (row % 2 == 0) ? '<div class="i20-80l"><a class="highslide" id="thumb' + row + '" href="' + LocationImageFull + array[row].FileName + '" onclick="return hs.expand(this)"><img  title="Click to enlarge" src="' + LocationImageThumbs + array[row].FileName + '"></a><div class="highslide-caption"><b>' + title + '</b><br />' + array[row].Detail.replace(/\r\n\r\n/g, '<br /><br />') + '</div></div><div class="i20-80r">' + array[row].Detail.substring(0,200) + '</div>'
														: '<div class="i80-20l ' + opts.theme + '">' + array[row].Detail.substring(0,200) + '</div><div class="i80-20r"><a class="highslide" id="thumb' + row + '" href="' + LocationImageFull + array[row].FileName + '" onclick="return hs.expand(this)"><img  title="Click to enlarge" src="' + LocationImageThumbs + array[row].FileName + '"></a><div class="highslide-caption"><b>' + title + '</b><br />' + array[row].Detail.replace(/\r\n\r\n/g, '<br /><br />') + '</div></div>';
					} else {
						str += (row % 2 == 0) ? '<div class="i20-80l"><img src="' + LocationImageThumbs + array[row].FileName + '"></div><div class="i20-80r">' + array[row].Detail.substring(0,200) + '</div>'
														: '<div class="i80-20l">' + array[row].Detail.substring(0,200) + '</div><div class="i90-10r"><img src="' + LocationImageThumbs + array[row].FileName + '"></div>';
					}
				} else {
					if (!(opts.linkHrefField == undefined) && !(opts.linkHrefUrl == undefined) && !(array[row][opts.linkHrefField] == null)) {
						str += '<div class="pointer" onclick="OpenHighSlide(\'' + opts.linkHrefUrl + array[row][opts.linkHrefField] + '\',' + opts.popUpWidth + ','  + opts.popUpHeight + ',undefined);">' + array[row].Detail.substring(0,200) + '</div>';
					} else {
						str += '<div>' + array[row].Detail.substring(0,200) + '</div>';
					}
				}
				str += '</div>';
				str += '</td></tr>';
			}
			str += '</table>';
			return str;


		}

		// creates an informal table of news with highslide popups
		function DrawNewsItem(array) {
			var str = '';
			for (var i = 0; i < array.length; i++) {
				if (array[i].Detail == null) {
					array[i].Detail = '&nbsp;';
				}
//				str += '<h4 class="ui-corner-all">' + formatORdate(array[i].Date) + ' - ' + array[i].Title + '</h4>';
				str += '<h4 class="ui-corner-all">' + array[i].Date + ' - ' + array[i].Title + '</h4>';
				if (array[i].FileType == true) {
					str += '<p><img src="./' + LocationImageFull + array[i].FileName + '">' + array[i].Detail.replace(/\r\n\r\n/g, '<br /><br />') + '</p>';
				} else {
					str += '<p>' + array[i].Detail.replace(/\r\n\r\n/g, '<br /><br />') + '</p>';
				}

				if (array[i].FileSize > 0) {
					var location;
					if (array[i].NewsType == 1) {
						location = LocationDownloads
					} else if (array[i].NewsType == 3) {
						location = LocationNewsletter
					} else if (array[i].NewsType == 4) {
						location = LocationClubDocs
					} else if (array[i].NewsType == 5) {
						location = LocationCommittee
					}
					str += '<h4 align="right" class="ui-corner-all"><a href="' + location + array[i].FileName + '" target="_blank"> View Attachment (' + formatBytes(array[i].FileSize) + ')</a></h4>';
				}

				if (array[i].Posted_by != null && array[i].Posted != null) {
//					str += '<p class="tag">Posted:&nbsp;&nbsp;' + array[i].Posted_by + ' (' + formatORdate(array[i].Posted, true) + ')</p>';
					str += '<p class="tag">Posted:&nbsp;&nbsp;' + array[i].Posted_by + ' (' + array[i].Posted + ')</p>';
				}
				if (array[i].Updated_by != null && array[i].Updated != null) {
//					str += '<p class="tag">Updated:&nbsp;' + array[i].Updated_by + ' (' + formatORdate(array[i].Updated, true) + ')</p>';
					str += '<p class="tag">Updated:&nbsp;' + array[i].Updated_by + ' (' + array[i].Updated + ')</p>';
				}

			}
			return str;
		}

		// creates a image slideshow
		function DrawSlideShow(array) {
			var size = new Array(400, 260); //default size width, height

			var str = '<ul class="slideshow">';
			for (var i = 0; i < array.length; i++) {
				if (array[i].Detail == null) {
					array[i].Detail = '';
				}
				str += (i == 0) ? '<li class="show">' : '<li>';
				str += ' <a href="' + opts.linkHrefUrl + '">';
//				str += ' <img src="./' + LocationImageFull + array[i].FileName +'" title="' + formatORdate(array[i].Date) + ' - ' + array[i].Title + '" alt="' + array[i].Detail.substring(0,200) + '"/>';
				str += ' <img src="./' + LocationImageFull + array[i].FileName +'" title="' + array[i].Date + ' - ' + array[i].Title + '" alt="' + array[i].Detail.substring(0,200) + '"/>';
				str += ' </a>';
				str += '</li>';
			}
			str += '</ul>';
			return str;
		}
	}
	
})( jQuery );


/* Common routines */
// get JSON data remotely
function getJSONData(url, stringifyval) {
	var result = '';
	$.ajax({
		type: "POST",
		url: url,
		async: false,
		contentType: "application/json; charset=utf-8",
		dataType: "json",
		success: function(data) {
			result = typeof data != 'object' ? $.parseJSON(data) : data;
			if (stringifyval != undefined) {
				result = stringArray(result, stringifyval)
			}
		},
		error: function(xhr, err) {
			result = {"error" : xhr.status + ' - ' + err};
		}
	});
	return result;
}

// return a reformated JSON object of a list of array items in one entry
function stringArray(input, val){
	var array = typeof input != 'object' ? $.parseJSON(input) : input;
	var str = '';
	for (i=0; i < array.length; i++){
		str += (i == 0) ? array[i][val] :  '; ' + array[i][val];
	}
	return [$.parseJSON('{"' + val + '":"' + str + '"}')];
}

//identify if item appears in an array.
// used to decide which columns not to show
function grepArray(array, val){
   for(i=0;i<array.length;i++){
      if(array[i] == val){
         return true;
      }
   }
   return false;
}

//open a highslide IFRAME window
function OpenHighSlide(url, w, h, title) {
   return hs.htmlExpand(null, {
      objectType: 'iframe',
      src: url,
		width: w,
		height: h,
		headingText: title
   });
}

// format kBytes to MBytes etc
function formatBytes(size, precision){
	if (precision === undefined) {
		precision = 2
	}
   var base = Math.log(size) / Math.log(1024);
   var suffixes = ['kB', 'MB', 'GB', 'TB' , 'PB' , 'EB'];
   return Math.round(Math.pow(1024, base - Math.floor(base)), precision) + suffixes[Math.floor(base)];
}

// format date field to match syntax
/*
function formatORdate(value, timestamp){
	var d_names = new Array('Sun','Mon','Tue','Wed','Thu','Fri','Sat');
	var m_names = new Array('Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec');
	var d = new Date(value);
	if (timestamp === undefined) {
		return [d_names[d.getDay()], d.getDate() < 10 ? '0' + d.getDate() : d.getDate(),  m_names[d.getMonth()], d.getUTCFullYear()].join(' ');
	} else {
		return d_names[d.getDay()] + ' ' + [d.getDate() < 10 ? '0' + d.getDate() : d.getDate(), d.getMonth() + 1 < 10 ? '0' + (d.getMonth() + 1) : d.getMonth() + 1, d.getUTCFullYear().toString().substring(2,4)].join('/') + ' ' + [d.getHours() < 10 ? '0' + d.getHours() : d.getHours(), d.getMinutes() < 10 ? '0' + d.getMinutes() : d.getMinutes()].join(':');
	}
}
*/
