$.fn.feedItemHover = function() {
    // Suppliment hover action for feed items in IE6
	$('.feed_wrapper li').hover(
		function() { 
			$(this).css('background-position', '0px ' + (parseInt($(this).css('backgroundPositionY'), 10) - 58) + 'px');
			$(this).addClass('hover');
		},
		function() { 
			$(this).css('background-position', '0px ' + (parseInt($(this).css('backgroundPositionY'), 10) + 58) + 'px');
			$(this).removeClass('hover');
		}
	);
}

/* BEGIN: FRONT DESK docready  */

AX.frontDeskTwitterFeed = function() {
	$("#twitterfeed h3").after("<ul id=\"twitterfeed-list\"></ul>");
	var protocol = document.location.protocol;
	var url = protocol + "//twitter.com/status/user_timeline/openforum.json?count=4&callback=?";
	$.getJSON(url, 
	function(data){ 
	$.each(data, function(i, item) { 
		var ImgSrc = (item.user["profile_image_url"]).replace(/http:/, protocol);
		$("#twitterfeed ul#twitterfeed-list").append("<li><div class='twitImage'><img src='/images/oflogo_normal.png' alt='OPEN Forum' width='32' height='32' /></div><div class='tweet'><p><a target='_blank' href=http://www.twitter.com/"
		+ item.user.screen_name + ">"
		+ item.user.screen_name 
		+ ":</a> "
		+ item.text
		+ "<em>"
		+ relative_time(item.created_at)
		+ "</em></p></div>"  
		+ "</li>"); 
		});
		$.fn.stripe('#twitterfeed ul'); 
	}); 
	
	function relative_time(time_value) {
		var values = time_value.split(" ");
		time_value = values[1] + " " + values[2] + ", " + values[5] + " " + values[3];
		var parsed_date = Date.parse(time_value);
		var relative_to = (arguments.length > 1) ? arguments[1] : new Date();
		var delta = parseInt((relative_to.getTime() - parsed_date) / 1000);
		delta = delta + (relative_to.getTimezoneOffset() * 60);
		var r = '';
		if (delta < 60) {
			r = 'a minute ago';
		} else if(delta < 120) {
			r = 'couple of minutes ago';
		} else if(delta < (45*60)) {
			r = (parseInt(delta / 60)).toString() + ' minutes ago';
		} else if(delta < (90*60)) {
			r = 'an hour ago';
		} else if(delta < (24*60*60)) {
			r = '' + (parseInt(delta / 3600)).toString() + ' hours ago';
		} else if(delta < (48*60*60)) {
			r = '1 day ago';
		} else {
			r = (parseInt(delta / 86400)).toString() + ' days ago';
		}

		return r;
	};
	
};

$(document).ready(function() {
	
	AX.frontDeskTwitterFeed();
	$.fn.thisWeeksPoll();
	
	$('.acceptpay-ext-link').click(function(){
		var linkUrl = $(this).attr('href');
		window.open(linkUrl);
		return false;
	});
	
	// Popup welcome video
	$('#welcome_video, .welcome_popup').bind('click',function(){
		window.open ($(this).attr('href'),"Welcome","status=0,toolbar=0,location=0,menubar=0,resizable=0,scrollbars=0,height=319,width=547");
		return false;
	});
	
	$('#featured_discussions #discussion_links li a').click(function(e) {
		e.preventDefault();
		if(!$(this).hasClass('active')) {
			$(this).addClass('active').parent().siblings().find('a.active').removeClass('active');
		}
	});
	
	$('.business_filters select').customSelect({ scrollThreshold: 6, scrollFactor: 200 });
	$('.business_filters select').change(function() {
		$('#business_filters_submit').trigger('click');
	});
	
	
	$('#feed_nav li a').click(function(e) {
		e.preventDefault();
		if(!$(this).hasClass('active')) {
			$(this).addClass('active').parent().siblings().find('a.active').removeClass('active');
		}
	});
	
	$('#featured_experts_nav li a').click(function(e) {
		e.preventDefault();
		if(!$(this).hasClass('active')) {
			$(this).addClass('active').parent().siblings().find('a.active').removeClass('active');
			
		}
	});

	/* Fulfillment tooltips */
	$('#fulfillment li a').wrapInner('<span></span>');
	$('#fulfillment li').hover( function() {
			$(this).addClass('hover');
			$this = $(this);
			$this.find('div.tooltip p a').css('marginTop', -1 * Math.floor($this.find('div.tooltip p a').outerHeight() / 2));
		}, function() {
			$(this).removeClass('hover');
		}
	);
	
	//Not a Business Owner tout actions
	
	//call to action	
	$('#btn_not_an_owner a').click(function(){
		$('#not_owner').show();
		return false;
	});
	
	//close tout
	$('#not_owner p.close').click(function(){
		$('#not_owner').hide(); 
		
	});
	
	//show dropdown
	$('#not_owner #btn-products').hover(
		function() {
			$(this).addClass('hover');
		},
		function() {
			$(this).removeClass('hover');
		}
	);

	
	$.fn.loadNewPostForm();
	
	// Start default text plugin site-wide
	$('input:text, textarea').defaultText();
	
	//feed items IE6 hover state
	if ($.browser.msie && ($.browser.version < 7)) {
	    $.fn.feedItemHover();
	}
	
	// stripe feed items list
	$.fn.stripe('div.feed_items ul');
	
	$.fn.bindFeedItemLinks();
	
	$.fn.sortFeedItems();
	
	$.fn.feedItemPagination();
	
	$.fn.sortMiniConnectodex();
	
	$('div.thumb').each(function() {
		if ($.browser.msie && ($.browser.version < 7)) { 
			if ($(this).hasClass("video")) {
				$(this).find('a img').after('<img src="/images/idea_hub/bkg.thumb-overlay-med.gif" alt="play video" class="overlay" />');
			};
		} else {
			if ($(this).hasClass("video")) {
				$(this).find('a img').after('<img src="/images/idea_hub/bkg.thumb-overlay-med.png" alt="play video" class="overlay" />');
			}
		};        
	});
	
	$(".ContactCarousel").contactcarousel({ visible: 4  });
	
	$('#NavColumnAccordion a, ul.featured_carousel li a, #feed_preferences a, #current_user a, #fulfillment a, #have-you-met li a, p.contacts a').filter(function() {
		var pattern = /^\//;
		return $(this).attr('href') && $(this).attr('href') != '' && pattern.test($(this).attr('href'));
	}).each(function() {
		var url = $(this).attr('href');
		$(this).attr('href', 'http://' + window.location.hostname + url);
	});

	
	
	$('a.survey').click(function(e){
		e.preventDefault();
		window.open($(this).attr('href'),'','status=0,toolbar=0,location=0,menubar=0,resizable=0,scrollbars=0,height=620,width=850');
	});
	
	$('.topics_quick_nav').customList({ width: 144 });
	$('.seek_provide_filter').customList({ width: 160 });
	$('#seek_provide_overview li.customList-items').css('top','-5px');

	$('.featured_slideshow').featuredSlideshow();
	
	//new paging box
	$('div#featured_experts ul#experts_paged_list').featured_experts_pager({ pageSize: 6 });
	
	if($('#HomeRoladexExpand').size() > 0) {
		$('#HomeRoladexExpand').flash({ 
			src: '/flash/HomeRoladexExpand.swf',
			width: 470,
			height: 420,
			wmode: 'transparent', 
			flashvars: { xmlPath: "/connectodex/?component=rolodex&m=e" }
			//flashvars: { xmlPath: "/flash/roladex.xml" }
		},
		{ 
			expressInstall: true,
			version: 9 
		});
	} else if($('#HomeRoladexSmall').size() > 0) {
		$('#HomeRoladexSmall').flash({ 
			src: '/flash/HomeRoladexSmall.swf',
			width: 484,
			height: 182,
			wmode: 'transparent', 
			flashvars: { xmlPath: "/connectodex/?component=rolodex&m=s" }
			//flashvars: { xmlPath: "/flash/roladex.xml" }
		},
		{ 
			expressInstall: true,
			version: 9 
		});
	}

	//utility nav clicks - logged out
	$('#LoggedOutUtility li a').click(function(){
        var btnType = $(this).parent().attr('id'); var action = '';
        switch(btnType){
            case 'UtilityLogin':
                btnType = 'login_left'; action = 'login';
                break;
            case 'UtilityRegister':
                btnType = 'register_left'; action = 'register';
                break;
            case 'UtilityAbout':
                btnType = 'about_left'; action = 'browse';
                break;
            case 'UtilityNoCard':
                btnType = 'apply_left'; action = 'apply_now';
                break;
        }
        $.fn.setOmnitureValuesSync(this, {
            channel: 'home',
            prop30: 'home:'+btnType,
            prop1: 'home:'+btnType,
            prop6: 'passive',
            prop7: action,
            prop10: 'not logged in',
            evar1: 'home:'+btnType,
            evar6: 'passive',
            evar7: action,
            evar10: 'not logged in'                        
        });
    });
		
	//utility nav clicks - logged in
	$('#Utility li a').click(function(){
		var btnType = $(this).parent().attr('id');
		switch(btnType){
			case 'UtilityNavProfile':
				btnType = 'profile_left';
				break;
			case 'UtilityNavSettings':
				btnType = 'settings_left';
				break;
			case 'UtilityNavContacts':
				btnType = 'contacts_left';
				break;
			case 'UtilityNavMessages':
				btnType = 'help_left';
				break;
		}
		$.fn.setOmnitureValuesSync(this, {
			channel: 'home',
			prop1: 'home',
			evar1: 'home',
			prop6: 'passive',
			evar6: 'passive',
			prop10: 'logged in',
			evar10: 'logged in',
			mobile: 'No',
			prop30: 'home:'+btnType
		});
		
		return true;
	});
	
	$('.FrontDesk .btn_member_log_in').click(function() {
		$.fn.setOmnitureValuesSync(this, {
			channel: 'home',
			prop1: 'home:login_right',
			evar1: 'home:login_right',
			prop6: 'passive',
			evar6: 'passive',
			prop7: 'login',
			evar7: 'login',
			prop10: 'not logged in',
			evar10: 'not logged in',
			prop30: 'home:login_right'
		});
		
		return true;
	});
	
	$('.FrontDesk .btn_register').click(function() {
		$.fn.setOmnitureValuesSync(this, {
			channel: 'home',
			prop1: 'home:register_right',
			evar1: 'home:register_right',
			prop6: 'passive',
			evar6: 'passive',
			prop7: 'register',
			evar7: 'register',
			prop10: 'not logged in',
			evar10: 'not logged in',
			prop30: 'home:register_right'
		});
		
		return true;
	});
	
	$('#open_card_link a').click(function() {
		$.fn.setOmnitureValuesSync(this, {
			channel: 'home',
			prop1: 'home:apply_right',
			evar1: 'home:apply_right',
			prop6: 'passive',
			evar6: 'passive',
			prop7: 'browse',
			evar7: 'browse',
			prop10: 'not logged in',
			evar10: 'not logged in',
			prop30: 'apply_right'
		});
		
		return true;
	});
	
	//your activity nav clicks
	$('#feed_nav li a').click(function(){
		$.fn.setOmnitureValues({
			pagename: 'home:main:your_activity:navigation',
			prop6: 'passive',
			prop7: 'browse',
			prop10: 'logged in',
			evar6: 'passive',
			evar7: 'browse',
			evar10: 'logged in'						
		});
		
		return true;
	});
	
	//insights pagination clicks
	$('#insights .pagination li a').click(function() {
		$.fn.setOmnitureValues({
			channel: 'home',
			pagename: 'home:insights:navigation',
			prop1: 'home:insights',
			evar1: 'home:insights',
			prop6: 'passive',
			evar6: 'passive',
			prop7: 'browse',
			evar7: 'browse',
			prop10: 'both',
			evar10: 'both'						
		});
		
		return true;
	});
	
	//start survey click
	$('#start_survey').click(function() {
		$.fn.setOmnitureValuesSync(this, {
			channel: 'home',
			pagename: 'home:showcase:site_survey',
			prop1: 'home:showcase',
			evar1: 'home:showcase',
			prop6: 'active',
			evar6: 'active',
			prop7: 'take_survey',
			evar7: 'take_survey',
			prop10: 'logged in',
			evar10: 'logged in'
		});
		
		return true;
	});
	
	$('#customList-provide_filter a').click(function() {
		var $a = $(this);
		
		$.fn.setOmnitureValues({
			channel: 'home',
			pagename: 'home:connections:more_provides',
			prop1: 'home:connections',
			evar1: 'home:connections',
			prop6: 'passive',
			evar6: 'passive',
			prop7: 'browse',
			evar7: 'browse',
			prop10: 'both',
			evar10: 'both',
			callback: function() {
				window.location = $a.attr('href');
			}
		});
		
		return false;
	});
	
	$('#customList-seek_filter a').click(function() {
		var $a = $(this);
		
		$.fn.setOmnitureValues({
			channel: 'home',
			pagename: 'home:connections:more_seeks',
			prop1: 'home:connections',
			evar1: 'home:connections',
			prop6: 'passive',
			evar6: 'passive',
			prop7: 'browse',
			evar7: 'browse',
			prop10: 'both',
			evar10: 'both',
			callback: function() {
				window.location = $a.attr('href');
			}
		});
		
		return false;
	});
	
	$('.followOPEN a').click(function() {
		$.fn.setOmnitureValues({
			channel: 'home',
			prop1: 'home',
			evar1: 'home',
			prop6: 'passive',
			evar6: 'passive',
			prop7: 'browse',
			evar7: 'browse',
			prop10: 'both',
			evar10: 'both',
			prop30: 'home:twitter_follow'
		});
	});
	
	$('#accept_pay .image a').click(function() {
		$.fn.setOmnitureValuesSync(this, {
			prop30: 'opentools:home:accept_pay'
		});
	});
	
	$('#accept_pay .link a').click(function() {
		$.fn.setOmnitureValuesSync(this, {
			prop30: 'opentools:home:accept_pay:join_conversation'
		});
	});
});


/* END: FRONT DESK docready  */

// Feed item click action
$.fn.bindFeedItemLinks = function() {
	$('.feed_items li').click(function() {
		window.location = $(this).find('a').attr('href');
		}).append($('<div class="feed_item_link"></div>'));
};

// sort feed tems list
$.fn.sortFeedItems = function() {
	$('ul#feed_nav a').ajaxLoadContent({
		component: 'MyFeed',
		container: 'div.feed_wrapper',
		callback: function() {
			$.fn.stripe('div.feed_items ul');
			$.fn.bindFeedItemLinks();
			$.fn.feedItemPagination();
		}
	});
};

// paginate feed items list
$.fn.feedItemPagination = function() {
	$('div.pagination a').ajaxLoadContent({
		component: 'MyFeed',
		container: 'div.feed_wrapper',
		callback: function() {
			$('html,body').animate({scrollTop: $('#feed_reader').offset().top},'fast');
			$.fn.stripe('div.feed_items ul');
			$.fn.bindFeedItemLinks();
			$.fn.feedItemPagination();
			//feed items IE6 hover state
	        if ($.browser.msie && ($.browser.version < 7)) {
	            $.fn.feedItemHover();
	        }
	        
			$.fn.setPaginationWidth();
		}
	});
	
	$.fn.setPaginationWidth();
};


// sort feed tems list
$.fn.sortMiniConnectodex = function() {
	$('ul#featured_experts_nav a').ajaxLoadContent({
		component: 'MiniConnectodex',
		content: '#experts_paged_list',
		container: '#experts_paged_list',
		callback: function() {
			$('div#featured_experts ul#experts_paged_list').featured_experts_pager({ pageSize: 6 });
			$('div#featured_experts ul#experts_paged_list .ContactIcon').personaCard();
		}
	});
};


// add new discussion bindings
// Process new post form
$.fn.bindProcessForm = function() {
	$('#form_well .formKit_form').submit(function() {

		$this = $(this);

		var ajaxPostURL = $this.attr('action');
		ajaxPostURL += ajaxPostURL.indexOf('?') > 0 ? '&' : '?';
		ajaxPostURL += 'component=' + $this.metadata().component;
		
		if ( $('input#subject').val() == $('input#subject').metadata().defaultvalue ) {
			$('input#subject').val('');
		}
		if ( $('textarea#message').val() == $('textarea#message').metadata().defaultvalue ) {
			$('textarea#message').val('');
		}

		$.ajax({
			type: 'POST',
			url: ajaxPostURL,
			data: 'topic=' + encodeURIComponent($('select#topic').val()) + '&subject=' + encodeURIComponent($('input#subject').val()) + '&message=' + encodeURIComponent($('textarea#message').val()),
			dataType: 'html',
			success: function(html) {

				if ( ajaxSuccess(html) ) {
					// Parse returned URL and determine if it's from the current section
					var $obj = $('<div id="ajaxContainer">').html(html);
					var axDiscussionURL = $obj.find('a').attr('href');
					var axDiscussionTopic = axDiscussionURL.split('/')[3];

					if (axDiscussionURL.split('/')[3] == location.href.split('/')[5]) { // Same topic
						$('div#discussion_content_well').ajaxLoadContent({
							trigger: axDiscussionURL,
							content: 'div#discussion_content_well',
							container: 'div#discussion_content_well',
							callback: function() {
								$.fn.loadDiscussionList();
								$.fn.commentForm();
							}
						});
					} else { // Different topic
						window.location = axDiscussionURL;
					}
                    
                    //ask the members track submit
                    $.fn.setOmnitureValues({
						pagename: 'home:main:ask_members:submit',
                        prop6: 'active',
                        prop7: 'submit_question',
                        prop10: 'logged in',
                        events: 'event8',
                        evar6: 'active',
                        evar7: 'submit_question',
                        evar10: 'logged in'
					});
                       
					$('#form_well').remove();
				}
			}
		});

		return false;
	});
};

// Load post form
$.fn.loadNewPostForm = function() {
	$('#ask_the_members p.button a').ajaxLoadContent({
		content: 'div#discussion_content_well',
		container: 'div#form_well',
		preCallback: function() {
			$('body').append('<div id="form_well" class="post_topic">');
		},
		callback: function() {

			$('div#form_well').append('<a href="#" class="form_well_close">X</a>').show();
			$.fn.bindCloseForm();
			$.fn.bindProcessForm();

			//$('.formKit_select select').customSelect();
			$('div#form_well .formKit_textarea textarea').textarea();
			$('div#form_well :text, #form_well textarea').formKit().defaultText();

			// Add Shadow
			$('div#form_well').append('<div class="form_well_shadow_r"></div><div class="form_well_shadow_br"></div><div class="form_well_shadow_b"></div>');
			$('div#form_well div.form_well_shadow_r').css({
				height: $('div#form_well').outerHeight() - 10
			});
			$('div#form_well div.form_well_shadow_b').css({
				width: $('div#form_well').outerWidth() - 10
			});

			$('div#form_well').vCenter();
		}
	});
};

// Close buttons
$.fn.bindCloseForm = function() {
	$('.form_well_close, .button_cancel').click(function() {
		$('#form_well').remove();
		return false;
	});
};

/* BEGIN: featured content slideshow */

(function() {

	$.fn.featuredSlideshow = function(options) {
		var opts = $.extend({}, $.fn.featuredSlideshow.defaults, options);
		return this.each(function() {
			var $this = $(this);
			var o = $.meta ? $.extend({}, opts, $this.data()) : opts;
			
			var hoverInterval = autoAdvance($this);
			 
			$this.hover(function() {
				clearInterval(hoverInterval);
			}, function() {
				hoverInterval = autoAdvance($this);
			});
			
			$('ul.pagination li', $this).not('.prev, .next').click(function() {
				$.fn.featuredSlideshow.advance($('ul.slides li:eq('+($(this).prevAll().size() - 1)+')'));
				return false;
			});
			$('ul.pagination li.prev', $this).click(function() {
				var prev = $('ul.slides li.active', $this).prev().size() == 0 ? $('ul.slides li:last', $this) : $('ul.slides li.active', $this).prev();
				$.fn.featuredSlideshow.advance(prev);
				return false;
			});
			$('ul.pagination li.next', $this).click(function() {
				var next = $('ul.slides li.active', $this).next().size() == 0 ? $('ul.slides li:first', $this) : $('ul.slides li.active', $this).next();
				$.fn.featuredSlideshow.advance(next);
				return false;
			});
						
			//functionality
			
		});
	};

	// private
	function autoAdvance($this) {
		return setInterval(function() {
			$.fn.featuredSlideshow.advance($('ul.slides li.active', $this).next().size() == 0 ? $('ul.slides li:first', $this) : $('ul.slides li.active', $this).next());
		}, 30000);
	};

	//public
	$.fn.featuredSlideshow.advance = function($slide) {
		var paginationIndex = $slide.prevAll().size() + 1;
		$slide.stop().parent().parent().find('.pagination li:eq('+paginationIndex+')').addClass('active').siblings().removeClass('active');
		$slide.animate({ opacity: 0 }, 1, function() {
			$(this).addClass('on_deck');
		});
		$slide.animate({ opacity: 1}, 250, function() {
			$(this).siblings('.active').removeClass('active');
			$(this).addClass('active').removeClass('on_deck');
		});
	};

	$.fn.featuredSlideshow.defaults = {
		
	};

})(jQuery);


/* END: featured content slideshow */
