window.qst= { 
	name: "qst",
	loadingImg: '<img src="77.gif" alt="" />'
};
window.qst.gcal = {};
( function( context ){
	context.domain = "qst.wikis.com";
	if( window.location.href.toLowerCase().indexOf(".site") > 0 ) {
		context.domain = "wiki7.qst";
	}
	context.namespace = function ( namespaceString ) {
		var parts = namespaceString.split('.'),
			parent = window,
			currentPart = '';    
		for(var i = 0, length = parts.length; i < length; i++) {
			currentPart = parts[i];
			parent[currentPart] = parent[currentPart] || {};
			parent = parent[currentPart];
		}
		return parent;
	};
	
	context.w = function( options ) {
		var defaults= {
				loadingImg: qst.loadingImg
			};
		$( options ).each( function( i, o ) {
			var get, 
				settings= $.extend( {}, defaults, o ),
				$target= $( settings.destination );
			if( settings.content ) {
				if( settings.destination && settings.loadingImg && $target.children().length === 0 ) {
					$target.html( settings.loadingImg );
				}
				if( settings.localFile ) {
					get= $.get( settings.content );
				} else {
					get= $.ajax({
						url: "/ba-simple-proxy.php?mode=native&url=http://qst.wikis.com/topic/" + ( settings.procPublic ? "" : "display~" ) + settings.content ,
						dataType: "html",
						cache: false
					});
				}
				if( settings.destination && $target.length ) {
					get.done( function( data ) {
						if( $target.length ) {
							$target.html( data );
						}
					});
				}
				get.done( settings.success );
				get.fail( settings.error );
				get.always( settings.complete );
			}
		});
	};

	// Loaders
	var loaders= context.namespace( [ context.name, "loaders" ].join(".") );
	loaders.loadjscssfile=  function( filename, filetype ){
		var fileref;
		if ( filetype==="js" ){ //if filename is a external JavaScript file
			fileref= document.createElement( 'script' );
			fileref.setAttribute( "type","text/javascript" );
			fileref.setAttribute( "src", filename );
			document.getElementsByTagName( "body" )[0].appendChild( fileref );
		}
		else if ( filetype==="css" ){ //if filename is an external CSS file
			fileref= document.createElement( "link" );
			fileref.setAttribute( "rel", "stylesheet" );
			fileref.setAttribute( "type", "text/css" );
			fileref.setAttribute( "href", filename );
			document.getElementsByTagName( "head" )[0].appendChild( fileref );
		}
		// if ( typeof fileref!="undefined" ) {
		//  document.getElementsByTagName( "head" )[0].appendChild( fileref );
		//  }
	};
	
	
	
})( window.qst );

( function( context ){
	/**
	* Converts an xs:date or xs:dateTime formatted string into the local timezone
	* and outputs a human-readable form of this date or date/time.
	*
	* @param {string} gCalTime is the xs:date or xs:dateTime formatted string
	* @return {string} is the human-readable date or date/time string
	*/
	function formatGCalTime(gCalTime) {
		// text for regex matches
		var remtxt = gCalTime;

		function consume(retxt) {
			var match = remtxt.match(new RegExp('^' + retxt));
			if (match) {
				remtxt = remtxt.substring(match[0].length);
				return match[0];
			}
			return '';
		}

		// minutes of correction between gCalTime and GMT
		var totalCorrMins = 0;
		var year = consume('\\d{4}');
		consume('-?');
		var month = consume('\\d{2}');
		consume('-?');
		var dateMonth = consume('\\d{2}');
		var timeOrNot = consume('T');

		// if a DATE-TIME was matched in the regex
		var dateString;
		if (timeOrNot === 'T') {
			var hours = consume('\\d{2}');
			consume(':?');
			var mins = consume('\\d{2}');
			consume('(:\\d{2})?(\\.\\d{3})?');
			var zuluOrNot = consume('Z');

			// if time from server is not already in GMT, calculate offset
			if (zuluOrNot !== 'Z') {
				var corrPlusMinus = consume('[\\+\\-]');
				if (corrPlusMinus !== '') {
					var corrHours = consume('\\d{2}');
					consume(':?');
					var corrMins = consume('\\d{2}');
					totalCorrMins = (corrPlusMinus==='-' ? 1 : -1) *
					(Number(corrHours) * 60 +
					(corrMins==='' ? 0 : Number(corrMins)));
				}
			}

			// get time since epoch and apply correction, if necessary
			// relies upon Date object to convert the GMT time to the local
			// timezone
			var originalDateEpoch = Date.UTC(year, month - 1, dateMonth, hours, mins);
			var gmtDateEpoch = originalDateEpoch + totalCorrMins * 1000 * 60;
			var ld = new Date(gmtDateEpoch);

			// date is originally in YYYY-MM-DD format
			// time is originally in a 24-hour format
			// this converts it to MM/DD hh:mm (AM|PM)
			dateString = (ld.getMonth() + 1) + '/' + ld.getDate() + ' ' +
				((ld.getHours()>12)?(ld.getHours()-12):(ld.getHours()===0?12:
			ld.getHours())) + ':' + ((ld.getMinutes()<10)?('0' +
			ld.getMinutes()):(ld.getMinutes())) + ' ' +
			((ld.getHours()>=12)?'PM':'AM');
		} else {
			// if only a DATE was matched
			dateString =  parseInt(month, 10) + '/' + parseInt(dateMonth, 10);
		}
		return dateString;
	}

	/**
	 * Creates an unordered list of events in a human-readable form
	 *
	 * @param {json} root is the root JSON-formatted content from GData
	 * @param {string} divId is the div in which the events are added
	 */
	context.listEvents= function( root, divId ) {
		var feed = root.feed;
		var events = document.getElementById(divId);
		if ( events.childNodes.length > 0 ) {
			events.removeChild(events.childNodes[0]);
		}

		// create a new unordered list
		var ul = document.createElement( 'ul' );

		// loop through each event in the feed
		for (var i = 0; i < feed.entry.length; i++) {
			var entry = feed.entry[i];
			var title = entry.title.$t;
			var start = entry['gd$when'][0].startTime;
			var entryLinkHref;

			// get the URL to link to the event
			for (var linki = 0; linki < entry['link'].length; linki++) {
				if (entry['link'][linki]['type'] === 'text/html' && entry['link'][linki]['rel'] === 'alternate') {
					entryLinkHref = entry['link'][linki]['href'];
				}
			}

			var dateString = formatGCalTime( start );
			var li = document.createElement( 'li' );

			// if we have a link to the event, create an 'a' element
			if ( false && typeof entryLinkHref !== 'undefined') {
				var entryLink = document.createElement( 'a' );
				entryLink.setAttribute( 'href', entryLinkHref );
				entryLink.appendChild( document.createTextNode( title ));
				li.appendChild( entryLink );
				li.appendChild( document.createTextNode(' - ' + dateString ));
			} else {
				// li.appendChild(document.createTextNode(title + ' - ' + dateString));
				li.appendChild( document.createTextNode( dateString + ' - ' + title ));
			}
			// append the list item onto the unordered list
			ul.appendChild( li );
		}
		events.appendChild( ul );
	};
	
	/**
	* Callback function for the GData json-in-script call
	* Inserts the supplied list of events into a div of a pre-defined name
	*
	* @param {json} root is the JSON-formatted content from GData
	*/
	context.insertUpcoming= function(root) {
		$("#upcoming").empty();
		qst.gcal.listEvents(root, 'upcoming');
	};
	
	context.fillSched= function( data ) {
		var reg= $( "#regattas" );
		reg.html( data );
		// Hide column 3 and 4
		reg.find("tr").each( function( i, e ){
			$(this).children().eq(2).hide().end().eq(3).hide();
		});
		// Clickable results
		reg.find("a").each( function(){
			var that=this, $this= $(this);
			$this.closest("tr").click( function(){
				window.location= that.href;
			}).hover(
				function () {
					$(this).children().andSelf().css( {cursor:"pointer"} );
				},
				function () {
					$(this).children().andSelf().css( {cursor:"auto"} );
				}
			);
		});
		reg.closest(".row").equalHeights();
		reg.show();
	};
	
	context.errorSched= function(){
		$("#regattas").append("<p>error loading.</p>");
	};

})( qst.gcal );


$.fn.equalHeights = function(px) {
	$( this ).each( function(){
		var currentTallest = 0;
		$( this ).children().each(function(i){
			if ( $( this ).height() > currentTallest ) { currentTallest = $( this ).height(); }
		});
		$( this ).children().css( { 'min-height': currentTallest });
	});
	return this;
};


