(function($){
	function footer_gallery(elem) {
		var elem = $(elem),
			container = elem.parent(),
			containerW = container.width(),
			gallery = $(">ul", elem),
			galleryItems, galleryItemsW,
			galleryW, left, 
			pageCount, expectedW, i, l, extraW,
			endPoint, restartPoint;
			
			
		//$(">ul>li", elem).shuffle();
		
		galleryItems = $(">ul>li", elem);
		galleryItemsW = [];
		galleryW = 0;
		
		$(">li", gallery).each(function(){
			var w = $(this).outerWidth();
			
			galleryW += w;
			galleryItemsW.push(w);
		});
		
		//setup endless rolling
		
		//we need at least 2 page
		pageCount = Math.max(2, Math.ceil(galleryW / containerW));
		
		expectedW = pageCount * containerW;
		
		endPoint = -galleryW;
		i = 0;
		extraW = 0;
		while (galleryW < expectedW || extraW < containerW) {
			galleryW += galleryItemsW[i];
			extraW += galleryItemsW[i];
			gallery.append( $(galleryItems[i]).clone().addClass("clone") );
			
			galleryItemsW.push( galleryItemsW[i] );
			
			i++;
			if (i > galleryItems.length-1) {
				i = 0;
			}
		}
		
		l = 0;
		gallery.css({
			left: l,
			width: galleryW
		});
		
		//setup interval
		(function(obj, x){
			var l = 0;
			window.setInterval(
				function() {
					l -= 1;
					obj.css("left", l);
					
					if (l <= x) {
						obj.css("left", 0);
						l = 0;
					}
				},
				30
			);
		})(gallery, endPoint);
		
		
		elem = container = galleryItems = gallery = null;
	}
	
	function init_conference() {
		$("#conference, #conferencelogin").each(function(){
			var 
				el = $(this),
				navs = $(".tabs-nav > li > a", el),
				current = "";
			
			function getContent(href) {
				var h = (href || "").replace("#", ""),
					c = (h !== "") ? $("#" + h) : null;
				
				if ( c !== null && c.length ) {
					return c;
				}
				
				return null;
			}
			
			function showDefault() {
				var c, cur;
				
				cur = navs.parent().filter(".active:eq(0)");
				if ( cur.length < 1 ) {
					cur = navs.parent().not(".disabled").filter(":eq(0)").find(">a");
				} else {
					cur = cur.find(">a");
				}
				
				c = getContent(cur.attr("href"));
				c.show();
				current = $(cur);
				$(cur).parent().addClass("active");
			}
			
			$(".tabs-contents", this).children().hide();
			
			
			
			navs.each(function(){
				var href = ($(this).attr("href") || "").replace("#", ""),
					c = getContent(href), nav = $(this);
					
				if ( c ) {
					
					
					$("a[href='#" + href + "']").not(this).click(function(){
						nav.trigger("click");
						return false;
					});
					
				} else {
					$(this).parent().addClass("disabled");
				}
			});
			
			navs.click(function(ev){
				var c, old, a = $(ev.target).closest("a");
				
				c = getContent(a.attr("href"));
				
				if ( c ) {
					if ( current ) {
						old = getContent(current.attr("href"));
						if ( old ) {
							old.hide();
						}
						current.parent().removeClass("active");
					}
					
					c.show();
					current = $(this);
					current.parent().addClass("active");
					
					return false;
				}
			});
			
			showDefault();
			
			
		});
	}
	
	function init_accordion() {
		$(".accordion-header").live("click", function(e){
			var t = $(e.target).closest("li");
				
			if ( t.hasClass("accordion-active") ) {
				t.removeClass("accordion-active");
			} else {
				t.addClass("accordion-active");
			}
			
			return false;
		});
		
		
	}
	
	photo_highllight_loader = function(container, apiKey) {
		var self = this;
		
		this.items = [];
		this.running = false;
		
		this.container = container;
		this.apiKey = apiKey;
		

		//use another ajax request to get the geo location data for the image
		/*
		$.getJSON('http://api.flickr.com/services/rest/?&method=flickr.photos.geo.getLocation&api_key=' + apiKey + '&photo_id=' + photoID + '&format=json&jsoncallback=?',
			function(data){
			
				//if the image has a location, build an html snippet containing the data
				if(data.stat != 'fail') {
					pLocation = '<a target="_blank" href="http://www.flickr.com/map?fLat=' + data.photo.location.latitude + '&fLon=' + data.photo.location.longitude + '&zl=1">' + data.photo.location.locality._content + ', ' + data.photo.location.region._content + ' (Click for Map)</a>';
				}
			});
		*/
		
		
		/*
		$.getJSON('http://api.flickr.com/services/rest/?method=flickr.photos.getSizes&api_key=' + apiKey + '&photo_id=' + photoID + '&format=json&jsoncallback=?',
			function(data){
			
				//if the image has a location, build an html snippet containing the data
				if(data.stat != 'fail') {
					if ( typeof data.sizes.size[4] !== "undefined" ) {
						detailImage = data.sizes.size[4].source || "";
					}
				}
			});
		*/
		/*
		$.jsonp({
			url:'http://api.flickr.com/services/rest/?method=flickr.photos.getSizes&api_key=' + apiKey + '&photo_id=' + photoID + '&format=json&jsoncallback=?',
			success: function(data){
			
				//if the image has a location, build an html snippet containing the data
				if(data.stat != 'fail') {
					if ( typeof data.sizes.size[4] !== "undefined" ) {
						detailImage = data.sizes.size[4].source || "";
					}
				}
			}
		});
		*/

		//use another ajax request to get the tags of the image
		/*
		$.getJSON('http://api.flickr.com/services/rest/?&method=flickr.photos.getInfo&api_key=' + apiKey + '&photo_id=' + photoID + '&format=json&jsoncallback=?',
			function(data){
		*/
		/*
		$.jsonp({
			url: 'http://api.flickr.com/services/rest/?&method=flickr.photos.getInfo&api_key=' + apiKey + '&photo_id=' + photoID + '&format=json&jsoncallback=?',
			success: function(data) {
			
				//if the image has tags
				if(data.photo.tags.tag != '') {
					
					//create an empty array to contain all the tags
					var tagsArr = new Array();
					
					//for each tag, run this function
					$.each(data.photo.tags.tag, function(j, item){
					
						//push each tag into the empty 'tagsArr' created above
						tagsArr.push('<a href="http://www.flickr.com/photos/tags/' + item._content + '">' + item.raw + '</a>');
						
					});
					
					//turn the tags array into a string variable
					var tags = tagsArr.join(', ');
				}
			
				//create an imgCont string variable which will hold all the link location, title, author link, and author name into a text string
				var imgCont = '<li id="flkcr_'+photoID+'">';
				
				if ( detailImage !== "" ) {
					imgCont += '<a href="'+detailImage+'" title="'+data.photo.title._content+'" class="conference-photo-highlight">';
				}
				
				imgCont += '<img src="' + photoURL + '" alt="" class="photo" />';
				
				if ( detailImage !== "" ) {
					imgCont += '</a>';
				}
				
				imgCont += '<div class="desc">' +
							'<div class="desc-title"><a class="title" href="http://www.flickr.com/photos/' + data.photo.owner.nsid + '/' + photoID + '">' + data.photo.title._content + '</a></div>' +
							'<div class="desc-author"><span class="desc-label">by</span> <a href="http://flickr.com/photos/' + data.photo.owner.nsid + '">' + data.photo.owner.username + '</a></div>' +
							'<div class="desc-comments"><span class="desc-label">Comments:</span> <span>' + data.photo.comments._content + '</span></div>';
							
				//if there are tags associated with the image
				if (typeof(tags) != 'undefined') {

					//combine the tags with an html snippet and add them to the end of the 'imgCont' variable
					imgCont += '<div class="desc-tags"><span class="desc-label">Tags:</span> ' + tags + '</div>';
				}

				//if the image has geo location information associate with it
				if(typeof(pLocation) != 'undefined'){
					//combine the geo location data into an html snippet and at that to the end fo the 'imgCont' variable
					imgCont += '<div class="desc-location"><span class="desc-label">Location:</span> ' + pLocation + '</div>';
				}

				//add the description & html snippet to the end of the 'imgCont' variable
				imgCont += '<div class="desc-text"><span class="desc-label">Decription:</span> ' + data.photo.description._content + '</div>';
				
				imgCont += '</div></li>';

				//append the 'imgCont' variable to the document
				$(imgCont).appendTo(container).find(">.conference-photo-highlight").colorbox({rel:"conference-photo-highlight"});

				//delete the pLocation global variable so that it does not repeat
				delete pLocation;
			}
		});
		*/
		
		return this;
	}
	
	$.extend(photo_highllight_loader.prototype, {
		addItem: function(item) {
			this.items.push(item);
			
			if ( !this.running ) {
				this.loadNext();
			}
		},
		
		loadNext: function() {
			var item;
			if ( this.items.length ) {
				this.running = true;
				item = this.items.shift();
				this.load(item);
			} else {
				this.running = false;
			}
			
		},
		
		load: function(item) {
			this.item = item;
		
			//build the url of the photo in order to link to it
			this.photoURL = 'http://farm' + item.farm + '.static.flickr.com/' + item.server + '/' + item.id + '_' + item.secret + '_m.jpg';
				
			//turn the photo id into a variable
			this.photoID = item.id;
			
			//for detail image popup
			this.detailImage = "";
			
			this.imgCont = $('<li id="flkcr_'+this.photoID+'"><div class="loading"></div></li>').appendTo(this.container);
			
			this.getSizes();
		},
		
		getSizes: function(){
			var self = this;
			/*
			window.setTimeout(function() {
				$.getJSON('http://api.flickr.com/services/rest/?method=flickr.photos.getSizes&api_key=' + self.apiKey + '&photo_id=' + self.photoID + '&format=json&jsoncallback=?', function(data) {
					self.getSizesOk.call(self, data);
				});
			},13);
			*/
			
			$.getJSON('http://api.flickr.com/services/rest/?method=flickr.photos.getSizes&api_key=' + self.apiKey + '&photo_id=' + self.photoID + '&format=json&jsoncallback=?', function(data) {
				self.getSizesOk.call(self, data);
			});
		},
		
		getSizesOk: function(data) {
			if(data.stat != 'fail') {
				if ( typeof data.sizes.size[4] !== "undefined" ) {
					this.detailImage = data.sizes.size[4].source || "";
				}
			}
			
			this.getInfo();
			
			
		},
		
		getInfo: function() {
			var self = this;
			/*
			window.setTimeout(function() {
				$.getJSON('http://api.flickr.com/services/rest/?&method=flickr.photos.getInfo&api_key=' + self.apiKey + '&photo_id=' + self.photoID + '&format=json&jsoncallback=?', function(data){
					self.getInfoOk.call(self, data);
				});
			}, 13);
			*/
			
			$.getJSON('http://api.flickr.com/services/rest/?&method=flickr.photos.getInfo&api_key=' + self.apiKey + '&photo_id=' + self.photoID + '&format=json&jsoncallback=?', function(data){
				self.getInfoOk.call(self, data);
			});
		},
		
		getInfoOk: function(data) {
			var item = this.item,
				photoID = this.photoID,
				detailImage = this.detailImage,
				photoURL = this.photoURL,
				imgCont = this.imgCont,
				html = "";
				
				
			
			//if the image has tags
			if(data.photo.tags.tag != '') {
				
				//create an empty array to contain all the tags
				var tagsArr = new Array();
				
				//for each tag, run this function
				$.each(data.photo.tags.tag, function(j, item){
				
					//push each tag into the empty 'tagsArr' created above
					tagsArr.push('<a href="http://www.flickr.com/photos/tags/' + item._content + '">' + item.raw + '</a>');
					
				});
				
				//turn the tags array into a string variable
				var tags = tagsArr.join(', ');
			}
			
			if ( detailImage !== "" ) {
				html += '<a href="'+detailImage+'" title="'+data.photo.title._content+'" class="conference-photo-highlight">';
			}
			
			html += '<img src="' + photoURL + '" alt="" class="photo" />';
			
			if ( detailImage !== "" ) {
				html += '</a>';
			}
			
			html += '<div class="desc">' +
						'<div class="desc-title"><a class="title" href="http://www.flickr.com/photos/' + data.photo.owner.nsid + '/' + photoID + '">' + data.photo.title._content + '</a></div>' +
						'<div class="desc-author"><span class="desc-label">by</span> <a href="http://flickr.com/photos/' + data.photo.owner.nsid + '">' + data.photo.owner.username + '</a></div>' +
						'<div class="desc-comments"><span class="desc-label">Comments:</span> <span>' + data.photo.comments._content + '</span></div>';
						
			//if there are tags associated with the image
			if (typeof(tags) != 'undefined') {

				//combine the tags with an html snippet and add them to the end of the 'imgCont' variable
				html += '<div class="desc-tags"><span class="desc-label">Tags:</span> ' + tags + '</div>';
			}

			//if the image has geo location information associate with it
			if(typeof(pLocation) != 'undefined'){
				//combine the geo location data into an html snippet and at that to the end fo the 'imgCont' variable
				html += '<div class="desc-location"><span class="desc-label">Location:</span> ' + pLocation + '</div>';
			}

			//add the description & html snippet to the end of the 'imgCont' variable
			html += '<div class="desc-text"><span class="desc-label">Decription:</span> ' + data.photo.description._content + '</div>';
			
			html += '</div>';

			//append the 'imgCont' variable to the document
			//$(imgCont).appendTo(container).find(">.conference-photo-highlight").colorbox({rel:"conference-photo-highlight"});
			
			imgCont.html(html);
			if ( detailImage !== "" ) {
				imgCont.find(">.conference-photo-highlight").colorbox({rel:"conference-photo-highlight"});
			}
			
			this.loadNext();
		}
	});
	
	
	function init_photos_highlights() {
		$("#photos_highlights_gallery").each(function(){
			var elem = $(this),
				container = $(">ul", elem),
				apiKey = elem.attr("data_apikey"),
				loader = new photo_highllight_loader(container, apiKey);
				
			function callback(data) {
				//loop through the results with the following function
				$.each(data.photoset.photo, function(i,item){
					//new photo_highllight_item(container, apiKey, item);
					loader.addItem(item);
				});
			}
				
			$.getJSON('http://api.flickr.com/services/rest/?&method=flickr.photosets.getPhotos&api_key=' + apiKey + '&photoset_id=72157627840483946&format=json&jsoncallback=?', callback);
		});
	}
	
	function init_event_documents() {
		$("#event_documents_tree").each(function(){
			var elem = $(this),
				container = $(">ul", elem),
				baseurl = elem.attr("data_baseurl");
				
			function callback(data) {
				$.each(data, function(i, parent){
					var $parent = $('<li><div class="accordion-header"><h4>'+ parent +'</h4></div>' +
						'<div class="accordion-content">' +
							'<table class="documents"></table></div></li>').appendTo(container).find("table.documents"),
							url = baseurl;
							
					url = url + '?' +
						$.param({
							'method':'getDocs',
							'parent': parent})
						+ '&jsoncallback=?';
					
					$.getJSON(url, function(data){
						$.each(data, function(i, doc){
							var html = "",
								filename, ext,
								ico = "",
								m = doc.filename.match(/^(.+)\.(pdf|doc|docx|docm|dotx|dotm|xls|xlsx|xlsm|xltx|xltm|xlsb|xlam|xll|ppt|pptx|pptm|potx|potm|ppam|ppsx|ppsm)$/i);
								
							if ( m ) {
								filename = m[1];
								ext = m[2];
								
								//http://en.wikipedia.org/wiki/Microsoft_Office_2007_filename_extensions
								//http://msdn.microsoft.com/en-us/library/cc313105%28v=office.12%29.aspx
								switch (ext.toLowerCase()) {
									case "doc":		
									case "docx":	//Word 2007 XML Document
									case "docm":	//Word 2007 XML Macro-Enabled Document
									case "dotx":	//Word 2007 XML Template
									case "dotm":	//Word 2007 XML Macro-Enabled Template
										ico = "doc-word";
										break;
	
									case "xls":
									case "xlsx": 	//Excel 2007 XML Workbook
									case "xlsm": 	//Excel 2007 XML Macro-Enabled Workbook
									case "xltx": 	//Excel 2007 XML Template
									case "xltm": 	//Excel 2007 XML Macro-Enabled Template
									case "xlsb": 	//Excel 2007 binary workbook (BIFF12)
									case "xlam": 	//Excel 2007 XML Macro-Enabled Add-In
									case "xll": 	//Excel 2007 compiled macros[1]
										ico = "doc-excel";
										break;
										
									case "ppt":	
									case "pptx": 	//PowerPoint 2007 XML Presentation
									case "pptm": 	//PowerPoint 2007 Macro-Enabled XML Presentation
									case "potx": 	//PowerPoint 2007 XML Template
									case "potm": 	//PowerPoint 2007 Macro-Enabled XML Template
									case "ppam": 	//PowerPoint 2007 Macro-Enabled XML Add-In
									case "ppsx": 	//PowerPoint 2007 XML Show not work
									case "ppsm": 	//PowerPoint 2007 Macro-Enabled XML Show
										ico = "doc-p";
										break;
										
									case "pdf":
										ico = "doc-pdf";
										break;
										
									default:
										ico = "doc-p";
										break;
								}
								
								html = '<tr><th scope="row">'+doc.timestamp+'</th>' +
									'<td><a href="'+doc.url+'" title="" target="_blank"><span class="'+ico+'">'+ doc.filename +'</span></a></td>' +
									'</tr>';
									
								$(html).appendTo($parent);
							}
						});
					});
				});
			}
				
			$.getJSON(baseurl + '?method=getParents&jsoncallback=?', callback);
			
		});
	}
	
	function init_invitation_form() {
		$(".contactUsForm form").each(function(){
			var state = $('#state'),
				country = $('#country');
				
			if ( state.length && country.length ) {
				country.bind("change", function(){
					if ( country.val() == "United States" ) {
						state.closest("fieldset").show();
					} else {
						state.closest("fieldset").hide();
					}
				});
				
				if ( country.val() == "United States" ) {
					state.closest("fieldset").show();
				} else {
					state.closest("fieldset").hide();
				}
			}
		});
	}
		
	$(function() {
		//6 Jan, 2011: SUKI - footer gallery
		$('.gallery-holder').each(function(){
			footer_gallery(this);
		});
		
		var today = new Date();
		var dayx = new Date('January 10, 2012')
		var days_left=days_between(dayx,today);
		
		var a=[];
		
		a[0]=Math.floor(days_left/100);
		a[1]=Math.floor(days_left%100/10);
		a[2]=Math.floor(days_left%100%10);
		
		$('.std .days span:first').html(a[0]);
		$('.std .days span:nth-child(2)').html(a[1]);
		$('.std .days span:last').html(a[2]);
		
		init_conference();
		
		init_accordion();
		
		init_photos_highlights();
		
		init_event_documents();
		
		init_invitation_form();
		
		if ( typeof $.fn.colorbox !== "undefined" ) {
			$(".recentevents-popup").colorbox({
				innerWidth: 900,
				innerHeight: 500,
				scrolling: false,
				iframe:true,
				opacity:0.75
			});
		}
	});


	function days_between(date1, date2) {

		// The number of milliseconds in one day
		var ONE_DAY = 1000 * 60 * 60 * 24

		// Convert both dates to milliseconds
		var date1_ms = date1.getTime()
		var date2_ms = date2.getTime()

		// Calculate the difference in milliseconds
		var difference_ms = Math.abs(date1_ms - date2_ms)
		
		// Convert back to days and return
		return Math.round(difference_ms/ONE_DAY)

	}

})(jQuery);


