$.fn.videoPlayButton = function() {
    $('.thumb').each(function() {
	    $(this).find('a img').after('<img src="/images/idea_hub/bkg.thumb-overlay-small.png" alt="play video" class="overlay" >');
	    $.ifixpng('/images/pixel.gif');
	    $('img[src$=.png]').ifixpng();    
	});
};
// $.fn.videoPlayButton();



var isFlashLoaded = 0;
var tcWasShown = false;
function pauseAfterVideoLoad() {
	//alert("pause called");
	if(tcWasShown == true){
		isFlashLoaded = 1;
		toggleVid('pause');
	}
}

function thisMovie(movieName) {
		if (navigator.appName.indexOf("Microsoft") != -1) {
			return window[movieName];
		} else {
			return document[movieName];
	}
	}
	
	//need to set to 1 with external interface call

	
	function toggleVid(action) {
		
		if(isFlashLoaded == 1) {
			thisMovie("videoPlayer").toggleFlashVideo(action);
			
		}
	}

$.fn.bindThumbsup = function() {
    $('.topic_tool_thumbsUp a').each(function() {
        var $link = $(this);
        $link.oneShotAjax({}, function() {
	        $link.html(parseInt($link.html(),10) + 1);
	        $link.replaceWith('<span class="recommendations">'+$link.html()+'</span>');
	    });
    });
};

$.fn.bindFlag = function() {
    $('.topic_tool_flag a:gt(0)').each(function() {
        var $link = $(this);
        $link.oneShotAjax({}, function() {
	        $link.html(parseInt($link.html(),10) + 1);
	        $link.replaceWith('<span class="recommendations">'+$link.html()+'</span>');
	        $('body').sysmessage('This post has been flagged for moderation', {type: 'confirmation'});
	     });
    });
	$('.topic_tool_flag a:eq(0)').each(function() {
        var $link = $(this);
        $link.oneShotAjax({}, function() {
					$('.discussion_tools a').trigger('click');
	        $('body').sysmessage('This post has been flagged for moderation', {type: 'confirmation'});
	     });
    });
};

// Comment pagination
$.fn.commentPagination = function() {
	$showAllPostButton = $('div.comments').find('.pagination').find('a');
	$showAllPostButton.click(function(){
		$showAllPostButton.addClass('all_posts_clicked');
		$showAllPostButton.find('#all_posts_text').remove();
	});
	$showAllPostButton.ajaxLoadContent({
		component: 'commentlist',
		container: 'div.comments div.pod_content',
		callback: function() {
			$('html,body').animate({scrollTop: $('div.comments').offset().top},'fast');
			$('div.comments .topic_tool_email a').bindLoadMessageForm();
			$('div#topic_comments .ContactIcon, ul.topics .ContactIcon').personaCard();
			$.fn.commentPagination();
			$.fn.bindThumbsup();
			$.fn.bindFlag();
			$.fn.bindTrackDiscussion(false);
		}
	});
};


$.fn.mediaCommentPagination = function() {
	var $showAll = $('a.all_posts');
	var text = $showAll.text();
	$showAll.text('');
	$showAll.append('<span id="all_posts_text" class="all_posts">show all comments ' + text.substr(text.indexOf('(')) + '</span>');
};

//
//---------- BEGIN: Comment form AJAX ----------
// Comment form
$.fn.commentForm = function() {
	$('#add_comment').val('').defaultText();
	$('form.comments_add').submit(function() {

		//disable submit while processing
		$('.formKit_submit input').attr('disabled', 'disabled');
		$('<div id="AjaxLoader" style="display: block !important;">Loading...</div>').appendTo('#PageWrapper');
		
		$this = $(this);
		var ajaxPostURL = $this.attr('action');
		ajaxPostURL += ajaxPostURL.indexOf('?') > 0 ? '&' : '?';
		ajaxPostURL += 'component=' + $this.metadata().component;
		
		$('#add_comment').blur();
		
		if ( $('#add_comment', $this).val() == $('#add_comment', $this).metadata().defaultvalue || !/\w/.test($('#add_comment', $this).val())) {
			$('body').sysmessage('Comment cannot be empty.', {type: 'error'});
			$('#LayoutWrapper .sysmessage').css('top', '-999999px');

			//re-enable submit
			$('.formKit_submit input').removeAttr('disabled');
			$('#AjaxLoader').remove();

		} else {
			var topicName = parseTitle('topic'),
                username = $('#Global_Auth ul li.view_profile a').length != 0 ? $('#Global_Auth ul li.view_profile a').attr('href').split('username=')[1] : $('.linkedIn .salutation').text().toLowerCase().split('welcome, ')[1].replace('.', '').replace(' ', '-');
			
			$.ajax({
				type: 'POST',
				url: ajaxPostURL,
				data: 'add_comment=' + encodeURIComponent($('#add_comment').val()),
				dataType: 'html',
				success: function(html) {
					if ( ajaxSuccess(html) ) {
						$('div.comments div.pod_content').html( html );

						$('#form_comment').trigger('success.form.ax');

						// Rebind pagination
						$.fn.commentPagination();
						$('div.comments .topic_tool_email a').bindLoadMessageForm();
						$.fn.bindThumbsup();
	                    $.fn.bindFlag();
	                    $.fn.bindTrackDiscussion(false);
	                    
						// Reset form values to null
						$('#add_comment').val('').defaultText();

						$('div#topic_comments .ContactIcon, ul.topics .ContactIcon').personaCard();
						
						$('.comment_count').html(parseInt($('.comment_count').html(),10) + 1);
						var comments_size = $('li.topic').size();
						$('a.comments').text(comments_size);
						
						if ($('.comment_count_text').length > 0) {
							var text = parseInt($('.comment_count').text()) == 1 ? " response" : " responses";
							$('.comment_count_text').html(text);
						}
						
						// Reset the character count
						if ($('textarea').length > 0) {
							$('#charsLeft').text($('textarea').metadata().charLimit);
						}
						
						$('#archived_comments').removeClass('active');
					}
				}
			});
			//re-enable submit
			$('.formKit_submit input').removeAttr('disabled');
			$('#AjaxLoader').remove();
		}
		
		return false;
	});
};

//---------- END: Comment form AJAX ----------
//


//
//---------- BEGIN: Discussions AJAX ----------

// Close buttons
$.fn.bindCloseForm = function() {
	$('.form_well_close, .button_cancel').click(function() {
		$('#form_well').remove();

		return false;
	});
};


// Discussions pagination
$.fn.discussionsPagination = function() {
	$('span.discussion_list div.pagination a').ajaxLoadContent({
		component: 'discussionlist',
		container: 'span.discussion_list',
		callback: function() {
			$('html,body').animate({scrollTop: $('div#discussion_content_well').offset().top},'fast');
			$.fn.discussionsPagination();
			//$.fn.loadDiscussionDetail();
			$.fn.bindThumbsup();
			$.fn.bindFlag();
			$.fn.thisWeeksPoll();
			$('div#discussion_content_well .ContactIcon').personaCard();
			//$.fn.setPaginationWidth();
		}
	});
	//$.fn.setPaginationWidth();
};

$.fn.sortDiscussion = function() {
	$('ul#discussion_filter a').ajaxLoadContent({
		component: 'discussionlist',
		container: 'div#discussion_content_well span.discussion_list',
		callback: function() {
			//$.fn.loadDiscussionDetail();
			$.fn.discussionsPagination();
			$('div#discussion_content_well .ContactIcon').personaCard();
		}
	});
};

$.fn.loadDiscussionDetail = function() {
	$('h3.topic_title a').ajaxLoadContent({
		content: 'div#discussion_content_well',
		container: 'div#discussion_content_well',
		callback: function() {
			$.fn.loadDiscussionList();
			$.fn.commentForm();
			$.fn.commentPagination();
			$.fn.mediaCommentPagination();
			$('.topic_tool_email a').bindLoadMessageForm();
			$('div#discussion_content_well .ContactIcon').personaCard();
			$.fn.bindThumbsup();
			$.fn.bindFlag();
			$.fn.bindTrackDiscussion(true);
			$.fn.bindCharacterCounting();
			$.fn.thisWeeksPoll();
		}
	});
};

$.fn.bindCharacterCounting = function() {
	var commentArea = $('textarea');
	if (commentArea.length > 0) {
		commentArea.textarea();
		if(commentArea.val() == commentArea.metadata().defaultvalue) {
			$('.charLimit[rel=' + commentArea.attr('name') + ']').html( '<span>' + commentArea.metadata().charLimit + '</span> characters left');
		}
	}
};

$.fn.loadDiscussionList = function() {
	$('div#comments_tools a').ajaxLoadContent({
		content: 'div#discussion_content_well',
		container: 'div#discussion_content_well',
		callback: function() {
			$.fn.sortDiscussion();
			$.fn.loadDiscussionDetail();
			$.fn.loadNewPostForm();
			$.fn.discussionsPagination();
			$.fn.bindThumbsup();
			$.fn.bindFlag();
			$.fn.thisWeeksPoll();
			$('div#discussion_content_well .ContactIcon').personaCard();
			$('ul#discussion_filter').customList({ width: 130 });
			$('ul#category_filter, ul#postedsince_filter, ul#sort_filter').customList({ width: 130, scrollThreshold: 12 });
			$('ul.topics ul.topic_tools').hide();
			$('.topic').hover(function() {
				$(this).find('ul.topic_tools').show();
			}, function() {
				$(this).find('ul.topic_tools').hide();
			});
		}
	});
};

// Process new post form
$.fn.bindProcessForm = function () {
	$('#form_well .formKit_form').submit(function () {

		$this = $(this);

		//disable submit while processing
		$('<div id="AjaxLoader" style="display: block !important;">Loading...</div>').appendTo('#PageWrapper');
		$('.formKit_submit').find('input').attr('disabled', 'disabled');

		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)) {
					//Triggering discussion success omniture tracking
					$('#create_discussion').trigger('success.discussion.ax');

					// 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];
					window.location = axDiscussionURL;
					//re-enable submit
					$('#AjaxLoader').remove();
					$('.formKit_submit').find('input').removeAttr('disabled');

					$('body').css('display', 'none');

					$('#form_well').remove();
				}else{
					$('#AjaxLoader').remove();
					$('.formKit_submit').find('input').removeAttr('disabled');
				}

			}

		});

		return false;
	});

};

// Load post form
$.fn.loadNewPostForm = function() {
	$('p.topics_add_post a').ajaxLoadContent({
		content: 'div#discussion_content_well',
		container: 'div#form_well',
		timeout: 60000,
		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 (but not for IE6)
			if ($.browser.msie && ($.browser.version < 7)) {
				$('div#form_well').append('<iframe id="form_well_shim" src="" frameborder="2" scrolling="no" height="1">');
				$('iframe#form_well_shim').css({
					background: 'transparent',
					height: $('div#form_well').height(),
					left: 0,
					position: 'absolute',
					top: 0,
					width: $('div#form_well').width(),
					zIndex: 1
				});
			} else {
				$('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();
		}
	});
};

// Omniture implementation for discussions - topics and feedback
$.fn.bindTrackDiscussion = function(trackDetail) {

	if ($('#LayoutWrapper').hasClass('Topic')) {
		//set omniture vals
		var topicName = parseTitle('topic');
		var itemName = $("#topic h3").text();
		
	
		
		//discussion detail
		if(trackDetail){
			

    }
                            
    //share click - OPEN Mic share
    if ($('.topic_entry a').text().toLowerCase().indexOf('podcast') > -1) {

    }
                                    
  } else if ($('#LayoutWrapper').hasClass('Feedback')) {
    
	
		//feedback discussion detail
		if(trackDetail){
			AX.TrackingData = {
				'guid': '',
				'pageTitle': 'DiscussionDetail',
				'contentType': '',
				'contentTitle': '',
				'userState': AX.user_state
			};

			AX.OmnitureScope = {
				'omn_language': 'en',
				'omn_hierarchy': 'US|OPENForum|SpecialFeatures|Feedback',
				'omn_pagename': AX.TrackingData.pageTitle,
				'omn_loginstatus': AX.TrackingData.userState
			};

			AX.Analytics.init();
    }
  } else if($('#LayoutWrapper').hasClass('AcceptPay')){
	
		//feedback discussion detail
		if(trackDetail){
			AX.TrackingData = {
				'guid': '',
				'pageTitle': 'DiscussionDetail',
				'contentType': '',
				'contentTitle': '',
				'userState': AX.user_state
			};

			AX.OmnitureScope = {
				'omn_language': 'en',
				'omn_hierarchy': 'US|OPENForum|SpecialFeatures|Feedback|AcceptPay',
				'omn_pagename': AX.TrackingData.pageTitle,
				'omn_loginstatus': AX.TrackingData.userState
			};

			AX.Analytics.init();
    }
	
	} //end if
}

$.fn.bindPopularToday = function() {
	$('#popular_today .popular_today_content:not(:first)').hide();
	
	$('#popular_today_navigation li a').click(function() {
		var $this = $(this);
		if ($this.attr('id') == 'tab_1') {
			$('#popular_today_navigation').addClass('most_viewed').removeClass('most_commented');
			$.cookie("AOF_popular_today", "most_viewed");
		} else {
			$('#popular_today_navigation').addClass('most_commented').removeClass('most_viewed');
			$.cookie("AOF_popular_today", "most_commented");
		}
		
		var content_id = $this.attr('id') + '_content';
		
		$('#popular_today .popular_today_content').hide();
		$('#popular_today #' + content_id).show();
		
		return false;
	});
}

$.fn.readPopularTodayCookie = function() {
	if($.cookie("AOF_popular_today") != null) {
		var popTodCookie = $.cookie("AOF_popular_today");
		$('#popular_today_navigation').removeClass().addClass(popTodCookie);
		if (popTodCookie == 'most_viewed') {
			var panelId = 'tab_1_content';
		} else {
			var panelId = 'tab_2_content';
		}
		
		$('#popular_today .popular_today_content').hide();
		$('#popular_today #' + panelId).show();
	}
}

$.fn.bindAttendanceToggle = function(attendMessage, unattendMessage) {
	$('#featured_action_attend').find('a').click(function(e){
		e.preventDefault();
	});
	
	$('#featured_action_attend a').oneShotAjax({ component: 'attendance_toggler'}, function() {
		var attendLink = $(this);
		
		if(attendLink.hasClass('event_action_clicked')) {
			attendLink.removeClass('event_action_clicked');
			$('body').sysmessage(unattendMessage, {type: 'confirmation'});
		} else {
			attendLink.addClass('event_action_clicked');
			$('body').sysmessage(attendMessage, {type: 'confirmation'});
		}
		
		var updateAttendeesUrl = window.location.pathname + '?a=1'; // the '?a=1' makes sure we have a valid url since the ajaxLoadContent call just does += '&component'

		$('#event_attendees_wrapper').ajaxLoadContent({
				trigger: updateAttendeesUrl,
				component: 'attendance_list',
				container: '#event_attendees_wrapper',
				callback: function() {
					$('.ContactCarousel').contactcarousel({ visible: 5 });
					
					$carouselWrapper = $('.carousel_wrapper');
					if($carouselWrapper.find('ul').find('li').length > 5){
						$carouselWrapper.css('left', '34px');
					}
				}
		});
	});
}

AX.setupAccordion = function()
{
	var $accordionMostPopular = $('#accordion_most_popular');
	var $accordionOFCommunity = $('#accordion_of_community');

	if($accordionMostPopular.length > 0)
	{
		$accordionMostPopular.accordion({
			'clickElements': 'h4 a',
			'accordionContainer' : 'ul',
			'tabContainer' : 'li',
			'contentContainer': 'div',
			'ititialTab': 2,
			'accordionAnim':AX.accordionAnimation,
			'animationDisabledClasses':['ie7']
		});
	}

	if($accordionOFCommunity.length > 0)
	{
		$accordionOFCommunity.accordion({
			'clickElements': 'h4 a',
			'accordionContainer': 'ul',
			'tabContainer': 'li',
			'contentContainer': '.of_community_members_content',
			'ititialTab': 1,
			'accordionAnim': AX.accordionAnimation,
			'animationDisabledClasses': ['ie7']
		});
	}

	// accordionChangeStart Binding.
	$(window).bind('accordionChangeStart', function(e, params) {
		if(params.id === 'accordion_top_stories') {
			AX.heroGalleryImageChange(params);
		}
		if (params.id.match(/accordion_most_popular|accordion_of_community/gi)) {
			if ( typeof $.cookie === 'function' ) {
				$.cookie(params.id+'_state', params.vars.tabIndex.toString(), {path:'/'});
			}
		}
	});
};

$(document).ready(function () {
	

  if ($.browser.msie && $.browser.version == "6.0") {
    $('.more_info_tip').ifixpng();
    $('.more_info_close').live('click', function () {
      $('.more_info_tip').css('display', 'none');
    });
  }
  $.fn.bindPopularToday();
  $.fn.readPopularTodayCookie();
  $('#linked_in_login').submitReplace();

  var topicName = parseTitle('topic');
  var detailPage = $('#LayoutWrapper').hasClass('Articles') ? 'article_detail' : $('#LayoutWrapper').hasClass('Videos') ? 'video_detail' : '';

  var prop30 = 'idea-hub:topics:' + topicName + ':' + detailPage;


	AX.setupAccordion();

	//remove click event from hover on Share Tools
	$('#footer_media, #EventShareLinksBottom').find('.share_other_button').click(function(e){
		e.preventDefault()
	});

	//START: Track email shares
    $('#footer_dropdown_email, #footer_share_email').click(function () {
      var emailShareURLhost = window.location.host,
				  emailShareURLtopic = AX.TrackingData.topic,
					emailShareURLpath = window.location.pathname,
					emailShareURLPathCollection = emailShareURLpath.split('/'),
				  emailShareURLmedia = emailShareURLPathCollection[1].replace('s', ''),
				  emailShareURLtitle = emailShareURLPathCollection[2];

      var emailShareUrl;

      if (emailShareURLpath.search('idea-hub') > -1) {
        emailShareUrl = 'SharedUrl=http://' + emailShareURLhost + emailShareURLpath + '&SharedType=SendToAFriend';
      } else {
        emailShareUrl = 'SharedUrl=http://' + emailShareURLhost + '/idea-hub/topics/' + emailShareURLtopic + '/' + emailShareURLmedia + '/' + emailShareURLtitle + '&SharedType=SendToAFriend';
      }

      $.ajax({
        url: '/tools/sharedTracker/index.trackitem_by_shared.ajax.aspx',
        data: emailShareUrl
      });
    });
    //END: Track email shares

  // is this a Video page?
  if ($('.IdeaHub .Videos').length) {
    var isVideoPage = 1;
  }

  //BEGIN: terms & conds popup
  var tcAlreadyShown = false;

  var showTC = function () {
    tcWasShown = true;
    $('#tc_accept').attr("disabled", "disabled").addClass("disabled");

    var litCC = $('#terms_accept');

    $('body').sysmessage(litCC, {
      autoDismiss: false,
      appendClose: false,
      lightbox: true
    });

    var $thisSysmessage = $('body .sysmessage');

    var commentAnchor = $('a[name=comment-form-block]');
    var commentOffset = commentAnchor.offset();
    if ($.browser.msie && !/MSIE 6\.0/i.test(window.navigator.userAgent)) {
      var tcTop = $("html").scrollTop() + 150;
    } else if ($.browser.safari) {
      var tcTop = $("body").scrollTop();
    } else {
      var tcTop = $("html").scrollTop();
    }

    $thisSysmessage.attr('id', 'terms_conditions');
    $thisSysmessage.css({ 'position': 'fixed', 'top': tcTop, 'left': '50%', 'display': 'block', 'margin-left': '-200px', 'margin-top': '100px' }).prev().css('height', '100%');

    $('input[name="agree"]').click(function () {
      var allChecked = $('input[name="agree"]').length == $('input[name="agree"]:checked').length;
      var $tcAccept = $('#tc_accept');
      if (!allChecked) {
        $tcAccept.attr("disabled", "disabled").addClass("disabled");
      } else {
        $tcAccept.removeAttr("disabled").removeClass("disabled");
      }
      toggleVid('play');
    });

    $('#tc_cancel').click(function () {
      $thisSysmessage.css('display', 'none').prev().css('display', 'none');
      tcAlreadyShown = true;
      toggleVid('play');
      return false;
    });
  };

  if ($('#terms_accept').length) {

    if ($.cookie('tc_prompted') != 'true') {
      //$.cookie('tc_prompted', 'true', { path: '/' });
      showTC();
    }

    $('#showTerms').click(function () {
      if (tcAlreadyShown) {
        toggleVid('pause');
		var $thisSysmessage = $('body .sysmessage');
        $thisSysmessage.show().prev().show();
        } else {
        showTC();
      }
    });
  }

  $('.print_terms').click(function () {
    var pDataHead = "<html><head><title>AMEX OpenForum Terms and Conditions</title></head><body>";
    var pDataFoot = "</body></html>";
    var TandC = $('.terms blockquote').html();
    var pData = pDataHead + TandC + pDataFoot;
    newWin = window.open("", "printVersion");
    newWin.document.write(pData);
    newWin.document.close();
    newWin.focus();
    newWin.window.print();
    newWin.window.close();
    return false;

  });


  //END: terms & conds popup	


});
