﻿
(function ($) {
	var _path = location.pathname.toLowerCase();
	var _appPath = _path.substr(_path.indexOf('/'), (_path.indexOf('pages/') - _path.indexOf('/')));

	// ShareThis options
	try {
		stLight.options({ publisher: '6c9c1a3c-af9a-4df4-b965-71d537e4b524', onhover: false });
	}
	catch (err) { }

	$(document).ready(function () {
		Ensynch.init();
	});

	$(window).load(function(){
		// initialize subFeatureScroll
		$('.js-subFeatureScroller').subFeatureScroll();
	});

	// Ensynch namespace
	var ensynch = function () { }

	ensynch.prototype = {
		init: function () {
			// initialize main nav
			$('.s4-tn .root .selected').removeClass('selected');
			$('.s4-tn .root a').filter(function () {
				return ($(this).attr('href').toLowerCase() == _path);
			}).addClass('selected').parentsUntil('.root').addClass('selected');
			$('.mainNav .s4-tn .root ul.dynamic').prepend('<li class="top"></li>').append('<li class="bott"></li>');

			// initialize homeFeature
			$('.js-homeFeature').homeFeature();
			
			// initialize document lists
			$('.js-documents').each(function(){
				var jq = $(this);
				jq.click(Ensynch.downloadDocHandler);
				var tag = jq.children('.js-tag').text();
				var formUrl = jq.children('.js-formUrl').text();
				jq.append('<table cellspacing="0" cellpadding="0"><tbody></tbody></table>');
				jq = jq.find('tbody');
				Ensynch.beginGetList({listName: 'Documents', 
					fields: ['Name', 'Report_x0020_Description', 'Tags'], 
					tags: tag, 
					complete: function (p_result) {
						var xml = p_result.responseXML;
						if(xml){
							$(xml).find('[nodeName=z:row]').each(function () {
								var item = $(this);
								var tags = item.attr('ows_Tags');
								if(tags.indexOf(tag) >= 0){
									var fileName = item.attr('ows_FileRef').split('/')[1];
									var description = item.attr('ows_Report_x0020_Description') || '';
									jq.append('<tr><td class="js-marketo-form-root"><strong class="js-fileName">' + fileName + '</strong> &nbsp; &nbsp; <a class="js-docDownload" href="javascript:;">Download</a><br/>' + description + '<br /><iframe src="' + formUrl + '" frameborder="0" onload="Ensynch.docFrameLoaded(this);" scrolling="no" style="display:none;width: 630px; height:350px;"></iframe></td></tr>');
								}
							});
						}
					}
				});
			});

			// initialize marketo forms
			$('.js-marketo').each(function(){
				var jq = $(this);
				var formUrl = jq.children('.js-formUrl').text();
				var style = jq.attr("style");
				var width = 630;
				var height = 455;
				var m;
				var re = /(\w+):\s*(\d*)/i;
				if(style){
					while(m = re.exec(style)){
						if(m[1] == 'width'){
							width = m[2];
						}
						if(m[1] == 'height'){
							height = m[2]
						}
						style = style.replace(re, '');
					}
				}
				jq.attr("style", "");
				jq.append('<div class="js-marketo-form-root"><iframe src="' + formUrl + '" frameborder="0" onload="Ensynch.docFrameLoaded(this);" scrolling="no" style="width: ' + width + 'px; height:' + height + 'px;"></iframe></div>');
			});

			// initialize fb Like
			$('.js-fbLike').html('<iframe src="http://www.facebook.com/plugins/like.php?app_id=215959691781036&amp;href=' + encodeURIComponent(location.href) + '&amp;send=false&amp;layout=button_count&amp;width=90&amp;show_faces=false&amp;action=like&amp;colorscheme=light&amp;font=arial&amp;height=21" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:90px; height:21px;" allowTransparency="true"></iframe>');

			//
			$('.js-bondAdapt').html('<iframe src="http://awsc6.aspadapt.com/EnsynchWSC/" frameborder="0" width="100%" height="636"></iframe>');
			
			// initialize deathStar
			$('.js-deathStar').deathStar();

			// initialize eventItems
			$('.js-eventItem').eventItem();

			// initialize feeds
			$('.js-syndication').feedster();
		},
		downloadDocHandler: function(p_evt){
			if(p_evt.target.className == 'js-docDownload' && !p_evt.handled){
				p_evt.preventDefault();
				p_evt.stopPropagation();
				p_evt.handled = true;
				$(p_evt.target).closest('.js-marketo-form-root').find('iframe,.js-thankYou').toggle(200);
			}
			if(p_evt.target.className == 'js-downloadNow' && !p_evt.handled){
				p_evt.handled = true;
			}
		},
		docFrameLoaded: function(p_frame){
			try{
				var doc = p_frame.contentDocument || p_frame.contentWindow.document;
				if(doc.location.href.indexOf("//info.ensynch.net/") < 0){
					var jq = $(p_frame).closest('.js-marketo-form-root');
					$(p_frame).remove();
					var hasFile = jq.find('.js-fileName').length > 0;
					if(hasFile){
						var url = '/documents/' + jq.find('.js-fileName').text();
					}
					jq.append('<div class="js-thankYou">' + jq.closest('.js-documents,.js-marketo').find('.js-thankYou').html().replace('{document name}', jq.find('.js-fileName').text()) + '</div>');
					
					jq.find('.js-thankYou').show();

					if(hasFile){
						jq.find('.js-thankYou .js-downloadNow').attr('href', url);
						window.open(url, 'Ensynch Download', 'status=0,toolbar=0,menubar=0,location=0,width=302,height=240');
					}
				}
			}
			catch(err){}
		},
		beginGetList: function(p_options){
			var query = (p_options.tags)? '<query><Query><Where><Eq><FieldRef Name="Tags" /><Value type="Choice">' + p_options.tags + '</Value></Eq></Where></Query></query>': '';
			query = '';
			var fields = '<viewFields><ViewFields /></viewFields>';
			if (p_options.fields){
				fields = '<viewFields><ViewFields>';
				for(var i=0;i<p_options.fields.length;i++){
					fields += '<FieldRef Name="' + p_options.fields[i] + '" />';
				}
				fields += '</ViewFields></viewFields>';
			}
			var soap = '<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"><soapenv:Body><GetListItems xmlns="http://schemas.microsoft.com/sharepoint/soap/"><listName>' + p_options.listName + '</listName>' + query + fields + '<rowLimit>500</rowLimit></GetListItems></soapenv:Body></soapenv:Envelope>';
			
			jQuery.ajax({
				url: _appPath + '_vti_bin/lists.asmx',
				type: 'POST',
				contentType: 'text/xml; charset="utf-8"',
				dataType: 'xml',
				data: soap,
				complete: p_options.complete
		  });
		}
	}

	window.Ensynch = new ensynch();

	// home feature widget
	$.widget("ui.homeFeature", {
		// default options
		options: {
			autostart: true,
			featureDelay: 5
		},
		_create: function () {
			var self = this;
			this._width = this.element.width();
			this._height = this.element.height();
			this._container = $('<div class="js-container"></div>').css({ position: 'relative', 'z-index': 0, overflow: 'hidden', height: this._height, width: this._width }).appendTo(this.element);
			this._features = $('ul li', this.element).click(function (p_evt) {
				self.stop();
				self._setFeature(this, p_evt);
			});
			this.current(0);
		},
		_init: function () {
			if (this.options.autostart) {
				this.start();
			}
		},
		_setFeature: function (p_feature, p_evt) {
			if ($(p_feature).hasClass('on')) return;
			this._features.removeClass('on');
			var oldContent = $('.js-holder', this._container).css({ 'z-index': 100 });
			var newContent = $('<div class="js-holder">' + $('.js-content', p_feature).html() + '</div>').css({ position: 'absolute', 'z-index': 10, height: this._height, width: this._width }).hide().prependTo(this._container);
			
			if(oldContent.length > 0){
				oldContent.fadeOut(250, function(){
					newContent.fadeIn(150, function(){
						oldContent.remove();
					})
				});
			}
			else{
				newContent.show();
			}

			$(p_feature).addClass('on');
			if (p_evt) {
				this._trigger('setCurrent', p_evt, { feature: p_feature });
			}
		},
		start: function () {
			this.stop();
			var self = this;

			this._timeout = setTimeout(function () { self._next(); }, this.options.featureDelay * 1250);
		},
		stop: function () {
			if (this._timeout) {
				clearTimeout(this._timeout);
			}
		},
		_next: function () {
			var next = this.current() + 1;
			next = (next >= this._features.length) ? 0 : next;
			this.current(next);
			var self = this;
			this._timeout = setTimeout(function () { self._next(); }, this.options.featureDelay * 1000);
		},
		current: function (p_val) {
			if (p_val !== undefined) {
				if (p_val >= 0 && p_val < this._features.length) {
					this._setFeature(this._features[p_val]);
				}
			}
			else {
				return $('li.on', this.element).index();
			}
		},
		destroy: function () {
			$.Widget.prototype.destroy.apply(this, arguments); // default destroy
			// now do other stuff particular to this widget
		}
	});
	
	// subFeatureScroll
	$.widget("ui.subFeatureScroll", {
		options: {},
		_create: function(){
			var self = this;

			this._logos = this.element.find('.logos');
			this._startLeft = this._logos.position().left;
			this._logosWidth = 0;
			this._logoCount = 0;
			this._logos.find('li').each(function(){
				self._logosWidth += $(this).width();
				self._logoCount++;
			});

			this._logos.width(this._logosWidth);

			var sides = this.element.find('.side a');

			sides.hover(function(){
				var dest = ($(this).parent().hasClass('left'))? self._startLeft: -(self._logosWidth - (self._logos.parent().width() + self._startLeft));
				var diff = Math.abs(dest - self._logos.position().left);
				var dur = Math.floor((diff/(self._logosWidth/self._logoCount)) * 1500);
				//window.console.log('animating left from ' + self._logos.position().left + ' to ' + dest + ' over ' + dur + ' ms');
				self._logos.animate({left: dest}, dur);
			},
			function(){
				self._logos.stop(true, false);
			});

		},
		_init: function(){
		},
		destroy: function () {
			$.Widget.prototype.destroy.apply(this, arguments); // default destroy
			// now do other stuff particular to this widget
		}
	});

	// death star widget
	$.widget("ui.deathStar", {
		// default options
			options: {
		},
		_create: function () {
			var self = this;
			this._container = $('.js-container', this.element).empty().append('<div class="js-holder"></div>');
			this._items = $('ul.subNav > li:not(.top,.bott)', this.element).click(function (p_evt) {
				self._setItem(this, p_evt);
				p_evt.preventDefault();
				p_evt.stopPropagation();
			});
			this.element.click(function(p_evt){
				Ensynch.downloadDocHandler(p_evt);
				if(!p_evt.handled && p_evt.target.href && p_evt.target.href.indexOf('#') > 0 && p_evt.target.href.indexOf(location.pathname) > 0){
					self._setByTitle(p_evt.target.href.substr(p_evt.target.href.indexOf('#')));
					p_evt.handled = true;
					return false;
				}
			});
			this._setByTitle(window.location.hash);
		},
		_init: function () {
		},
		_setByTitle: function(p_title){
			var idx = 0;
			p_title = (p_title && p_title.length > 0 && p_title[0] == '#')? p_title.substr(1): p_title;
			var anchor = this.element.find('li > a.js-button[title="' + decodeURIComponent(p_title)  + '"]');
			if(anchor && anchor.length == 1){
				var idx = anchor.closest('li').index();
				idx = Math.max(idx - 1, 0);
			}
			this.current(idx);
		},
		_setItem: function (p_item, p_evt) {
			if ($(p_item).hasClass('selected') || $(p_item).hasClass('top') || $(p_item).hasClass('bott')) return;
			var content = $('.js-content', p_item);
			if(content.find('a.js-redirect').length == 1){
				var href = content.find('a.js-redirect').attr('href');
				var target = content.find('a.js-redirect').attr('target');
				if(target == '_blank'){
					window.open(href);
				}
				else{
					location.href = href;
					return;
				}
			}
			this._items.removeClass('selected');
			var holder = $('.js-holder', this._container[0]);
			var d = (holder.html() == '') ? 0 : 200;
			$('.js-holder', this._container[0]).fadeOut(d, function () {
				holder.empty().html(content.html()).show();
			});
			$(p_item).addClass('selected');
			$(document).scrollTop(0);
			if (p_evt) {
				this._trigger('setCurrent', p_evt, { item: p_item });
			}
		},
		current: function (p_val) {
			if (p_val !== undefined) {
				if (p_val >= 0 && p_val < this._items.length) {
					this._setItem(this._items[p_val]);
				}
			}
			else {
				return $('li.selected', this.element).index();
			}
		},
		destroy: function () {
			$.Widget.prototype.destroy.apply(this, arguments); // default destroy
			// now do other stuff particular to this widget
		}
	});

// eventItem widget
$.widget("ui.eventItem", {
		// default options
		options: {
	},
	_create: function () {
		var self = this;
		var dates = $.trim($('.js-eventDates', this.element).html()).split(',');
		this._startDate = this._parseDate(dates[0]);
		this._endDate = this._parseDate(dates[1]);

		this._calendar = $('.js-calendar', this.element);
		this._buildCalendars();
	},
	_init: function () {
	},
	_buildCalendars: function () {
		var startMonth = this._startDate.getMonth();
		var endMonth = this._endDate.getMonth();
		if (startMonth == endMonth) {
			var first = new Date(this._startDate.getFullYear(), startMonth, 1);
			this._buildCalendar(this._daysInMonth(startMonth), first.getDay(), this._startDate.getDate(), this._endDate.getDate());
		}
		else {
			var days = this._daysInMonth(startMonth);
			var first = new Date(this._startDate.getFullYear(), startMonth, 1);
			var end = new Date(this._startDate.getFullYear(), startMonth, days);
			this._buildCalendar(days, first.getDay(), this._startDate.getDate(), end.getDate());

			days = this._daysInMonth(endMonth);
			first = new Date(this._endDate.getFullYear(), endMonth, 1);
			var end = new Date(this._startDate.getFullYear(), startMonth, days);
			this._buildCalendar(days, first.getDay(), 1, this._endDate.getDate());
		}
	},
	_buildCalendar: function (p_days, p_firstIndex, p_startDay, p_endDay) {
		var count = Math.ceil((p_days + p_firstIndex) / 7) * 7;
		var lastIndex = p_firstIndex + p_days - 1;
		var startIndex = p_firstIndex + p_startDay - 1;
		var endIndex = p_firstIndex + p_endDay - 1;
		var items = [];
		for (var i = 0; i < count; i++) {
			if (i < p_firstIndex || i > lastIndex) {
				items.push('<li class="blank"></li>');
			}
			else if (i >= startIndex && i <= endIndex) {
				items.push('<li class="highlight">' + (i - p_firstIndex + 1) + '</li>');
			}
			else {
				items.push('<li>' + (i - p_firstIndex + 1) + '</li>');
			}
		}
		this._calendar.append('<ul class="calendar"><li class="day">S</li><li class="day">M</li><li class="day">T</li><li class="day">W</li><li class="day">Th</li><li class="day">F</li><li class="day">Sa</li>' + items.join('') + '</ul>');
	},
	_parseDate: function (p_val) {
		var parts = $.trim(p_val).split('.');
		return new Date(parts[0], parts[1] - 1, parts[2]);
	},
	_isLeapYear: function (p_y) {
		return ((p_y % 4 == 0) && (p_y % 100 != 0 || p_y % 400 == 0));
	},
	_daysInMonth: function (p_m, p_y) {
		return (p_m == 1 && this._isLeapYear(p_y) == true) ? 29 : [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][p_m];
	},
	destroy: function () {
		$.Widget.prototype.destroy.apply(this, arguments); // default destroy
		// now do other stuff particular to this widget
	}
});

// feedster
$.widget("ui.feedster", {
	// default options
	options: {
	},
	_create: function () {
		var self = this;
		this.nav = $('ul', this.element);
		this.nav.find('li').click(function(p_evt){self._onNavClick(p_evt);});
		this.containers = $('.columnTwoThirds', this.element);
		this._views = {twitter: [], facebook: [], youtube: [], linkedin: [], flickr: [], blogs: []};
		this._feeds = {facebook: {type: 'facebook'}, linkedIn: {type: 'linkedin'}}; // (DR) facebook and linked in are disabled by default
		self._initCount = 0;

		Ensynch.beginGetList({listName: '{3714FF53-8888-4D47-931E-D0C7AA01CED0}', 
			fields: ['URLwMenu'], 
			tags: '', 
			complete: function (p_result) {
				var xml = p_result.responseXML;
				if(xml){
					$(xml).find('[nodeName=z:row]').each(function () {
						var parts = $(this).attr('ows_URLwMenu').split(', ');
						self._feeds[encodeURI(parts[0])] = {};
						self._initCount++;
					});
				}
				self._processFeeds();
			}
		});
	},
	_init: function () { },
	_processFeeds: function(){
		var now = new Date().getTime();
		for(var p in this._feeds){
			if(!this._feeds[p].type || (this._feeds[p].type == 'twitter' && (now - this._feeds[p].loadTime) > 20000)){
				this._getFeed(p);
			}
		}
		var self = this;
		setTimeout(function(){self._processFeeds()}, 20000);
	},
	_getFeed: function (p_url) {
		// get 'http://plugins.jquery.com/project/jgfeed' plugin to handle cross domain rss requests
		var self = this;
		$.jGFeed(p_url, function (p_feed) {//author, description, feedUrl, link, title, type
			var result = {loadTime: new Date().getTime()};
			result.type = (p_url.match(/twitter\.com/i))? 'twitter': (p_url.match(/facebook\.com/i))? 'facebook': (p_url.match(/youtube\.com/i))? 'youtube': (p_url.match(/linkedin\.com/i))? 'linkedin': (p_url.match(/flickr\.com/i))? 'flickr': 'blogs';
			
			if (p_feed.entries) {

				for(var i=0; i < p_feed.entries.length; i++){
					var entry = p_feed.entries[i]; // title, link, author, published Date, contentSnippet, content, categories
					entry.parsedDate = Date.parse(entry.publishedDate);
					entry.date = new Date(entry.parsedDate);
					var author = /\(([^\)]+)/i.exec(entry.author);
					if(author){
						entry.parsedAuthor = author[1] || e;
					}
					else{
						entry.parsedAuthor = entry.author;
					}
					if(result.type == 'twitter'){
						entry.contentSnippet = entry.contentSnippet.replace(/(https?:\/\/[^\s]+)/gi, '<a href="$1" target="_blank">$1</a>');
						//entry.content = entry.content.replace(/(https?:\/\/[^\s]+)/gi, '<a href="$1" target="_blank">$1</a>');
					}
					self._addToView(result.type, entry);
				}
				
				self._feeds[p_url] = result;
				self._initCount--;

				if(self._initCount <= 0 && self.containers.filter(':visible').length == 0){
					self.show(self.nav.find('[data-view]:visible:eq(0)').attr('data-view'));
				}
			}
		});
	},
	_addToView: function(p_view, p_entry){
		var view = this._views[p_view];
		var found = false;
		for(var i=0;i<view.length; i++){
			if(view[i].link == p_entry.link){
				found = true;
				break;
			}
		}
		if(!found){
			p_entry._key = view.length;
			view.push(p_entry);
			view.sort(function(a, b){
				return b.parsedDate - a.parsedDate;
			});
			this._buildPosts(p_view);
		}
	},
	_buildPosts: function (p_view) {
		var view = this._views[p_view];
		if(view.length > 0){
			this.nav.find('.' + p_view + ':hidden').fadeIn(200);
		}
		else{
			this.nav.find('.' + p_view + ':visible').fadeOut(200);
		}

		var container = this.containers.filter('[data-view=' + p_view + ']');
		for(var i =0;i<view.length;i++){
			var item = container.find('p[data-key=' + view[i]._key + ']');
			if(item.length == 0){
				var markup;
				if(p_view == 'twitter'){
					markup = '<p data-key="' + view[i]._key + '">' + view[i].content + ' via <a target="_blank" href="http://twitter.com/' + view[i].parsedAuthor.replace(' ', '') + '">' + view[i].parsedAuthor + '</a></p>';
				}
				else{
					var formattedDate = (view[i].date)? ' on ' + (view[i].date.getMonth() + 1) + '/' + view[i].date.getDate() + '/' + view[i].date.getFullYear(): '';
					markup = '<p data-key="' + view[i]._key + '"><a href="' + view[i].link + '" target="_blank"><strong>' + view[i].title + '</strong></a> by <a href="' + view[i].link + '" target="_blank">' + view[i].parsedAuthor + '</a>' + formattedDate + '<br/>' + view[i].contentSnippet + '</p>';
				}
				var current = container.find('p:eq(' + i + ')');
				if(current.length > 0){
					current.before(markup);
				}
				else{
					container.append(markup);
				}
			}
		}
	},
	show: function(p_view){
		var view = this._views[p_view];
		if(view.length > 0){
			this.nav.find('li.selected').removeClass('selected');
			this.nav.find('[data-view=' + p_view + ']').closest('li').addClass('selected');
			var vis = this.containers.filter(':visible');
			if(vis.length > 0){
				var self = this;
				vis.fadeOut(200, function(){
					vis.hide();
					self.containers.filter('[data-view=' + p_view + ']').show();
				});
			}
			else{
				this.containers.filter('[data-view=' + p_view + ']').show();
			}
		}
	},
	_onNavClick: function(p_evt){
		if($('[data-view]', p_evt.target)){
			this.show($(p_evt.target).attr('data-view'));
		}
	},
	destroy: function () {
		$.Widget.prototype.destroy.apply(this, arguments); // default destroy		// now do other stuff particular to this widget	
	}
});
})(jQuery);

