(function($){

	$(document).ready(function(){

		/*-----------------------------------------------------
			JavaScript for the iVillage - Entertainent Homepage
		-----------------------------------------------------*/

		var post_chimed_event_to_server = function(content_id) {
			jQuery.ajax({
				url:nethat_site.prefix + '/stats/chimed/event',
				type:'POST',
				dataType:'json',
				data:{content_id:content_id}
			});
		};
		// This form should only exist if a comment should be posted when
		// the page loads.  This usually/only occurs when the a user tries
		// to post a comment, but is redirected for authentication during
		// the process.  Prior to the redirect, we put the comment in a
		// cookie and use the cookie to populate this form.
		if (current_user) {
			var content_uri = $('#hidden-chime-form input[name=contentURI]').val();
			$('#hidden-chime-form form').submit();
			post_chimed_event_to_server(content_uri);
		}

		// Compile URLs from carousel to make AJAX call
	
		var chime_in = $('#chime-in');
		var chime_in_trans = $('#chime-in-trans');
		var chime_form = $('form#chime-in-form',chime_in);
		var chimes = $('ul#chimes');
		var feat_credit = $('#feature-meta > p.credit');
		var iframe = '';
		var mzinga_webtag = $('#chime-in-form ').attr('action').replace(/.*webtag=([a-z0-9-])/, '$1');
		
		var caro_arr = '';
		var caro_invoked = false;
		var caro_links = $('#carousel .hero .service-url').not(':empty');
		caro_links.each(function(i,elem){
			caro_arr += 'content_url[]='+ escape($(this).html());
			if(i != parseInt(caro_links.length - 1)) caro_arr += '&';
		});
	
		// Invoke Twitter-style character limits on form
		chimeValidation( chime_in, $('textarea#chime-input', chime_in), $('button', chime_in) );

		// Instantiate the homepage carousel
		
		var slide_count = $('#feature-meta .slide-count');
		var slide_count_curr = $('.curr',slide_count);
		var slide_count_total = $('.total',slide_count);
	
		// Update slideshow counter

		var slideshow = $('#single-view #carousel ul');
		var caro_items = $('.hero',slideshow).length;
		slide_count_total.text(caro_items);
		
		$("#carousel").jCarouselLite({
			btnNext: "#carousel-ctrls .next",
			btnPrev: "#carousel-ctrls .prev",
			speed: 1000,
			visible:1,
			easing: 'easeOutQuart',
			beforeStart: function(slide) {
				caro_invoked = true;
				chime_in.hide();
				chime_in_trans.hide();
				feat_credit.fadeOut();
				if(slide.children('.ad').length) iframe.addClass('hide');
		    	},
		    	afterEnd: function(slide) {
					feat_credit
						.text(slide.attr('rel'))
						.fadeIn();
			
					var heros = $('li.hero');
					var slide_index = heros.index(slide);
					switch(slide_index){
						case parseInt($(this).children().length - 1):
							slide_count_curr.text('1');
							break;
						case 0:
							slide_count_curr.text(caro_items);
							break;
						default:
							slide_count_curr.text(heros.index(slide));
							break;
					}
			
					var slide_service_url = $(slide).find('div.service-url').text();
					if(slide_service_url != null){
						if(chime_data && slide_service_url.length) updateChimePanel(slide_service_url);
					}	
				
					if(!iframe.length){
						iframe = slide.find('#single-view-ad').not('.rendered');
						iframe
							.attr('src',nethat_site.prefix+'/hero-single-ad')
							.addClass('rendered');
					}else{
						if(slide.find('.ad > iframe')) iframe.removeClass('hide');
					}
				
		    	}
		});
		
		// Allows hover state on background images for home heroes and list features
		var homepage_features = $('#highlights .highlight, #highlights .hero');
		homepage_features.hover(function(e){
			if($(e.target).hasClass('highlight') || $(e.target).hasClass('hero')){
				$(this).addClass('active').css('cursor','pointer');
			}
		},function(e){
			$(this).removeClass('active').css('cursor','default');	
		}).bind("click", function(e){
			if($(e.target).hasClass('highlight') || $(e.target).hasClass('hero')){
				window.location.href = $(this).find('h2 > a').attr('href');
			}
		});

		// Function to update the chime panel.
		function updateChimePanel(url){
		
			// Don't bother with the chimes if there is no url 
			if (url == undefined)
				return;		
			
			// If the link is external, we don't need to show the chime panel
		
			var real_url = $('#carousel li .service-url').filter(':contains('+url+'):first').siblings('h2').find('a');
		
			if (real_url.hasClass("external"))
				return;
		
			// Clear out old chimes
			chimes
				.children()
				.not('.read-full')
				.remove();
		
			// Update URL of 'Read Full Thread'
			chimes
				.find('.read-full a')
				.attr('href', real_url.attr('href')+'#chime-in');
		
			var chime_counter = 0;
			$.each(chime_data.comments,function(i){
				if(this.service_url.indexOf(url) > -1){
					if(chime_counter < 3){
						buildChime(this.author,this.image,this.date_posted_distance,this.message_text,false,'end',this.user_id);
						chime_counter++;
					}
				}
			});
			$('#chimes .top, #chimes .btm').ifixpng();
		
			// Update the chime panel question
			chime_question = $('#carousel li .service-url').filter(':contains('+url+'):first').siblings('h2').find('.chime-in-q').text();
			$('#chime-input h4').text(chime_question);
		
			// Update hidden form fields
			$('#chime-input input[name=subject]').val(chime_question)
			$('#chime-input input[name=contentURI]').val(url)
			comments_id = $('#carousel li .service-url').filter(':contains('+url+'):first').siblings('.comments-id:first').text();
			$('#chime-input input[name=contentID]').val(comments_id)
			content_url = $('#carousel li .service-url').filter(':contains('+url+'):first').siblings('h2').find('a:first').attr('href');
			$('#chime-input input[name=contentURL]').val(content_url)

			// Reset Chime In System
			$('textarea#chime-input',chime_in).val('');
			$('span.char-remaining',chime_in)
				.removeClass('char-remaining-low')
				.removeClass('char-remaining-over')
				.text('140');
			$('button',chime_in).addClass('disabled');

			$('.pngfix', chime_in);
			chime_in.css({'left':'628px','display':'none'}).fadeIn('fast');
			if(msie6) chime_in_trans.css('opacity','0.5');
			chime_in_trans.css({'left':'628px','display':'none'}).fadeIn('fast');
		}

		// Get JSON comments for all features

		var chime_data;

		// Remove hide class from list view and make AJAX call for comments
		$.ajax({
			url: nethat_site.prefix + "/comments/list.json",
			type: "GET",
			dataType: "json",
			data: caro_arr,
			success: function(json){
				chime_data = json;
				if(chime_data && !caro_invoked) updateChimePanel($('#carousel li:eq(1)').find('.service-url').html());
			},
			error: function() {}
		});

		// Intercept the submission

		chime_form.bind('submit',function(e){
	
			// Checks whether form has valid number of characters
			if(!$('button',chime_form).hasClass('disabled')){
				var chime_text = $('textarea', this).val();
				var content_url = $('input[name=contentURL]', this).val();
				var content_uri = $('input[name=contentURI]', this).val();
				var comments_id = $('input[name=contentID]', this).val();

				json = {'author':current_user, 'image':nethat_site.prefix+'/images/global/icons/ph-chime-profile.png', 'content_url':content_url, 'service_url':content_uri, 'content_id':comments_id, 'date_posted_distance':'less than a second', 'message_text':chime_text}

				if (current_user == null && $(this).data('prevent-default')) {
					e.preventDefault();
					$.ajax({
						url: nethat_site.prefix + "/comments/store.json",
						type: "POST",
						dataType: "json",
						data: json
					});
					$.fn.login_lightbox();
				}
				else {
					chime_data.comments.splice(0,0, json);
					removeChime(3);
					if(current_user == null) current_user = $('#signature',chime_in).val();
					buildChime(current_user, null, 'less than a second', chime_text, true, 'start',$('#uid',chime_in).val());
					post_chimed_event_to_server(content_uri);
				}
	
			}else{ e.preventDefault(); }

		});

		// When the iframe loads with the results of the post, clear the field.

		$('iframe[name=mzinga]').load(function(){
			$('#chime-input-wrap textarea').val('');
		});
	
		// Function to remove chime from list
		// Accepts a number (which chime in list to remove)

		function removeChime(chime_num){
			chimes.children().not('.read-full').filter(':eq('+parseInt(chime_num-1)+')').remove();
		}

		// Function to build a chime

		function buildChime(user,image,pub_date,comment,anim,inject,user_id){
			if (user == null)
				user = 'Anonymous';
			if (image == null || image == '') {
			    if (nethat_user.name == user && nethat_user.icon != '') {
	    			image = nethat_user.icon;
	    		} else {
					image = nethat_site.prefix + '/images/global/icons/ph-chime-profile.png';
				}
			}

			// create the profile link
			if ($.trim(user_id).length == 0) {
				var profile_link = '#';
			} else {
				var profile_link = 'http://messageboards.ivillage.com/dir-app/bbCard/profile.asp?webtag=' + mzinga_webtag + '&uid=' + user_id;
			}
			
			if(comment.length > 80) comment = comment.substring(0,80) + '...';
			var new_chime = $('\
				<li>\
					<div class="top"></div>\
					<div class="rep">\
						<h5><span><a href="' + profile_link + '" onclick="window.open(this.href,\'profile\',\'height=600,width=600\');return false;">'+ user +'</a></span> replied ' + pub_date + ' ago</h5>\
						<a href="' + profile_link + '" onclick="window.open(this.href,\'profile\',\'height=600,width=600\');return false;"><img src="'+image+'" width="60" height="60" alt="'+user+'" /></a>\
						<blockquote>'+ comment +'</blockquote>\
					</div>\
					<div class="btm"></div>\
				</li>');
			if(inject == 'start'){	
				new_chime = chimes
					.prepend(new_chime)
					.children()
					.filter(':eq(0)');
			}else{
				new_chime = chimes
					.find('.read-full')
					.before(new_chime)
					.children()
					.filter(':eq(0)');		
			}
			if(anim) new_chime.hide().slideDown('slow');
		}

		// Listen for login lightbox events

		$('.login-lightbox-listener').each(function() {
		    $(this).data('prevent-default', true);
		});

		$('.login-lightbox-listener').bind('submit-guest submit-anonymous', function(e, name, email){
		    $('#signature', chime_in).val(name) || "Anonymous";
		    $('#email', chime_in).val(email) || "anonymous@ivillage.com";
		    $(this).data('prevent-default', false);
		    $(this).submit();
		});
	
		$('.media-filter a.list-view').bind('click', function(){
			$('#list-view').removeClass('hide');
			var iframe = $('#list-view-ad').not('.rendered');
			if(iframe.length){
				iframe
					.attr('src',nethat_site.prefix+'/hero-multi-ad')
					.addClass('rendered');
			}
		});
		
		// Stagger home carousel and list view images
		$('#single-view li.hero[ivbgimg], #list-view div.highlight[ivbgimg]').staggerImages();
	
	});

})(jQuery);