$(function(){
	current_product = null;
	current_player = null;
	product_name = null;
	unique_product_name = null;
	video = false;
	
	original_height = 0;
	
	expand_top_style = 'clip';
	expand_bottom_style = 'blind';
	collapse_top_style = 'blind';
	collapse_bottom_style = 'blind';
	toggle_speed = 500;
	
	default_review_text = 'Write your review here...';
	
	$('.product_thumbnail').click(function () {
		toggle_player($(this).parent().parent().parent());
	});
	
	$('.more_info').click(function () {
		toggle_player($(this).parent().parent().parent().parent());
	});
	
	$('.product_close').click(function () {
		collapse_player($(this).parent().parent());
	});
	
	function toggle_player(player){
		if(current_product != $(player).attr('product_id') && current_product != null){
			collapse_player($('#product_'+current_product));
		}
		
		if (!$(player).find(".product_content_open").is(':visible') ) {
			original_height = player.height();
			current_product = $(player).attr('product_id');
			current_player = player;
			expand_player(player);
			product_name = $(player).attr('title');
			unique_product_name = product_name +' - '+current_product;
		} else {
			collapse_player(player);
		}
	}
	
	function expand_player(player){
		if($(player).attr('product_type') == 'Bundle'){
			window.location.href = '/bundle/'+$(player).attr('product_id')+'/'+$(player).attr('url_friendly_title');
		} else {
			video = true;
			product_video_preview = $(player).find(".product_player").attr('video_url');
			if (product_video_preview == '.flv' || product_video_preview == undefined) {
				$(player).find(".product_player").hide();
				video = false;
			}
			
			$(player).find(".more_info").html('Close');
			$(player).find(".product_close").show();
			$(player).find(".product_content").hide();
			$(player).find(".product_content_open").show(expand_bottom_style, function() {
				$('html, body').animate({
					scrollTop: $(player).offset().top - 9
				}, toggle_speed);
				
				if(video){
					$(player).find(".product_player").flowplayer(0).play(product_video_preview);
				}
				
				$(player).find(".add_to_cart").click(add_to_cart_click);
				
			}, toggle_speed
			);
		}
	}
	
	function collapse_player(player){
		$(player).find(".more_info").html('More Info');
		
		if (video) {
			$(player).find(".product_player").flowplayer(0).stop();
			$(player).find(".product_player").flowplayer(0).close();
			$(player).find(".product_player").flowplayer(0).unload();
		}
		
		share_area = $(current_player).find(".product_share");
		if ( $(share_area).is(':visible') ) {
			toggle_share_area(player);
		}
		copy_button = $(player).find(".copy_link");
		$(copy_button).css({'background-color' : '#FFFFFF', 'color': '#0E4375'});
		$(copy_button).html("<span class='button_text'>Copy Link</span>");
		
		embed_code = $(player).find(".embed_code");
		$(embed_code).css({'background-color' : '#FFFFFF', 'color': '#0E4375'});
		$(embed_code).html("<span class='button_text'>Embed Code</span>");
		
		$(player).find(".product_close").hide();
		$(player).find(".product_content").show(collapse_top_style, {}, toggle_speed);
		$(player).find(".product_content_open").hide(collapse_bottom_style, function() {
			// Animation complete.
		}, toggle_speed);
		
		if(current_product == $(player).attr('product_id')){
			current_product = null;
			current_player = null;
		}
	}
	
	$('.play_overlay').hover(function () {
		$(this).animate({opacity:0.90},250);
	}, function () {
		$(this).animate({opacity:0},250);
	});
	
	$('.add_to_cart').click(add_to_cart_click);
	
	function add_to_cart_click(object)
	{
		button_text = $(this).html();
		add_to_cart_label = 'Add to Cart';
		checkout_label = 'Checkout';
		
		if (button_text != add_to_cart_label && button_text != checkout_label)
		{
			return;
		}
		
		player = $(this).parent().parent().parent();
		
		if(player.attr('product_id') == undefined){
			player = $(this).parent().parent().parent().parent();
		}
		if(player.attr('product_id') == undefined){
			player = $(this).parent().parent();
		}
		if(player.attr('product_id') == 'content'){
			player = $(this).parent().parent();
		}
		
		product_id = $(player).attr('product_id');
		
		if (button_text == add_to_cart_label){
			if (product_id > 0){
				$(this).html('<img src="http://cache.sermonspice.com/media/default/images/loading.gif" height="15px">');
				$.ajax({
					type: "POST",
					url: "/cart/add_item/" + product_id,
					success: function(msg){
						change_quantity();
						
						$(player).find(".add_to_cart").each(function (i) {
							$(this).css({'background-color' : '#2C6905', 'font-weight' : 'bolder'});
							$(this).addClass('product_button_cart_down');
							$(this).html(checkout_label);
						});
						
						try {_gaq.push(['_trackEvent', "Videos", add_to_cart_label, unique_product_name]);}
						catch (err) {}
					}
				});
			}
		} else {
			try {_gaq.push(['_trackEvent', "Videos", checkout_label, unique_product_name]);}
			catch (err) {}
			
			if($(player).find(".product_player").flowplayer(0)){
				$(player).find(".product_player").flowplayer(0).pause();
			}
			
			window.location = '/cart/';
		}
	}
	
	$('.product_button_share').click(toggle_share_area);
	
	function toggle_share_area(object) 
	{
		share_button = $(current_player).find(".product_button_share");
		share_area = $(current_player).find(".product_share");
		copy_button = $(current_player).find(".copy_link");
		embed_code_button = $(current_player).find(".embed_code");
		share_link = $(current_player).find(".product_share_link");
		embed_code = $(current_player).find(".product_share_embed_code");
		product_title = $(current_player).attr('title');
		cart_url = $(current_player).attr('cart_url');
		
		video_player = $(current_player).find(".product_player").flowplayer(0);
		video_player.embed();
		var embed_code_html = video_player.getEmbedCode(true);
		var html_code = '<div style="width: 540px; padding: 0px; margin: 10px auto; border: 1px solid #9EAFBC; background-color:#F1F4F7; color:black;">';
		html_code += '<div style="background-color:#114575; padding:5px; padding-left:10px; font-size:13px; font-weight:bold; overflow:auto;">';
		html_code += '<div style="font-family:Verdana; float:left; color: #FFFFFF;">'+product_title+'</div>';
		html_code += '</div><div style="padding: 0px; overflow: auto;">'+embed_code_html+'</div>';
		html_code += '<div style="background-color:#E3E7EB; padding:5px; padding-left:10px; font-size:13px; font-weight:bold; overflow:auto;">';
		html_code += '<div style="float:left; line-height:18px; color:#000000; font-family:Verdana;"><a href="http://www.sermonspice.com">Sermonspice.com</a></div>';
		html_code += '<div style="float:right;">';
		html_code += '<span style="font-family:Verdana; width:85px; text-align:center; font-weight:bold; background-color:#D4DBE1; border:1px solid #9EAFBC; padding:3px; font-size:12px; color:#0E4375; cursor:pointer; vertical-align:middle;"><a href="'+share_link.val()+'">See Details</a></span>';
		html_code += '&nbsp;<span style="font-family:Verdana; width:85px; text-align:center; font-weight:bold; background-color:#D4DBE1; border:1px solid #9EAFBC; padding:3px; font-size:12px; color:#0E4375; cursor:pointer; vertical-align:middle;"><a href="'+share_link.val()+'">Buy Now</a></span>';
		html_code += '</div></div></div>';
		
		embed_code.val(html_code);
		
		if ( $(share_area).is(':visible') ) {
			$(share_button).removeClass('product_button_highlight');
			$(share_area).hide(collapse_top_style, {}, toggle_speed);
		} else {
			$(share_button).addClass('product_button_highlight');
			$(share_area).show(collapse_top_style, {}, toggle_speed);
			
			try {_gaq.push(['_trackEvent', "Videos", "Share", unique_product_name]);}
			catch (err) {}
		}
		
		var clip_embed = new ZeroClipboard.Client();
		clip_embed.glue(embed_code_button[0]);
		clip_embed.setText(embed_code.val());
        
		clip_embed.addEventListener('complete', function(client, text) {
			$(embed_code_button).css({'background-color' : '#009933', 'color': '#FFFFFF'});
			$(embed_code_button).effect("highlight", {}, 500);
			$(embed_code_button).html("<span class='button_text'>Copied</span> <img src='http://cache.sermonspice.com/media/default/images/icons/tick.png'>");
        });
		
		var clip = new ZeroClipboard.Client();
        clip.glue(copy_button[0]);
        clip.setText(share_link.val());
		
		var shared_object = SHARETHIS.addEntry({
			title: product_title,
			url: share_link.val()
		}, {
			button: false,
			onmouseover: false
		})
		
		shared_object.attachChicklet('facebook', $(share_area).find(".share_facebook").get(0));
		shared_object.attachChicklet('twitter', $(share_area).find(".share_twitter").get(0));
		shared_object.attachChicklet('yahoo_buzz', $(share_area).find(".share_yahoo").get(0));
		shared_object.attachChicklet('myspace', $(share_area).find(".share_myspace").get(0));
		shared_object.attachChicklet('digg', $(share_area).find(".share_digg").get(0));
		
        clip.addEventListener('complete', function(client, text) {
			$(copy_button).css({'background-color' : '#009933', 'color': '#FFFFFF'});
			$(copy_button).effect("highlight", {}, 500);
			$(copy_button).html("<span class='button_text'>Copied</span> <img src='http://cache.sermonspice.com/media/default/images/icons/tick.png'>");
        });
	};
	
	$('.product_button_reviews').click(toggle_reviews);
	
	function toggle_reviews(object){
		player = $(this).parent().parent().parent();
		product_id = player.attr('product_id');
		review_area = $(this).parent().parent().parent().find(".product_reviews");
		
		if ( $(review_area).is(':visible') ) {
			$(this).removeClass('product_button_highlight');
			$(review_area).hide(collapse_top_style, {}, toggle_speed);
		} else {
			$(this).addClass('product_button_highlight');
			$(review_area).show(collapse_top_style, {}, toggle_speed);
			$(review_area).html('<img src="http://cache.sermonspice.com/media/default/images/loading.gif" height="15px">');
			
			$.getJSON('/products/reviews/'+product_id, function(data) {
				if(data.status == 'success'){
					$(review_area).html('');
				
					$.each(data.reviews, function(i, review){
						review_content = '<div class="product_review"><div class="product_review_title">' + review.customer + ' - <span class="review_date">' + review.date + '</span></div><div class="product_review_content">' + review.review + '</div></div>';
						$(review_content).appendTo(review_area);
					});
				} else {
					$(review_area).html('No Reviews. Write a review!');
				}
			});
		}
	};
	
	if (user_logged_in)
	{
		$('.product_button_like').click(like_product);
	}
	else
	{
		// we remove all the classes to avoid shown any behavior to the user
		$('.star_rating').find('li').find('a').each(function() {
			$(this).removeClass();
		});
		$('.product_button_like, .star_rating').each(function() {
			var action = (($(this).hasClass('product_button_like')) ? ('like') : ('rate'));
			$(this).qtip({
				content: { text: 'Please <a href="/login">login</a> to '+action+' products.' },
				show: 
				{
					event: 'mouseover',
					solo: true
				},
				hide: 
				{
					delay: 500,
					fixed: true,
					when:
					{
						event: 'mouseout'
					}
				},
				position: 
				{
					corner: 
					{
						target: 'topMiddle',
						tooltip: 'bottomMiddle'
					}
				},
				style: 
				{
					border: 
					{
						width: 3,
						radius: 3,
						color: '#CFCFCF'
					},
					padding: 8, 
					textAlign: 'center',
					tip: true, // Give it a speech bubble tip with automatic corner detection
					name: 'light',
					background: '#E8E8E8'
				}
			});
		});
	}
	
	function like_product(object)
	{
		like_button = this;
		player = $(this).parent().parent().parent();
		product_id = $(player).attr('product_id');
		
		if ($(this).hasClass('product_button_cart_down'))
		{
			$(like_button).html('<img src="http://cache.sermonspice.com/media/default/images/loading.gif" height="15px">');
			$.ajax({
				type: "POST",
				url: "/favorites/remove_item/" + product_id,
				success: function(xml){
					$(xml).find('favorite').each(function(){
						var action = $(this).find('action').text();
						
						if (action == 'remove') {
							$(like_button).css({'background-color': '#B5920B'});
							$(like_button).removeClass('product_button_cart_down');
							$(like_button).effect("highlight", {}, 500);
							$(like_button).html("<img src='http://cache.sermonspice.com/media/default/images/icons/star.png'><span class='button_text'>Like</span>");
						}
					});
				}
			});
		} 
		else 
		{
			$(like_button).html('<img src="http://cache.sermonspice.com/media/default/images/loading.gif" height="15px">');
			$.ajax({
				type: "POST",
				url: "/favorites/add_item/" + product_id,
				dataType: "xml",
				success: function(xml)
				{
					$(xml).find('favorite').each(function()
					{
						var action = $(this).find('action').text();
						
						if (action == 'add')
						{
							$(like_button).css({'background-color' : '#2C6905'});
							$(like_button).addClass('product_button_cart_down');
							$(like_button).effect("highlight", {}, 500);
							$(like_button).html("<img src='http://cache.sermonspice.com/media/default/images/icons/star.png'><span class='button_text'>Un-Like</span>");
							
							try {_gaq.push(['_trackEvent', "Videos", "Like", unique_product_name]);}
							catch (err) {}
						}
					});
				}
			});
		}
	}
	
	$('.add_review_button').click(review_product);
	
	function review_product(object){
		review_button = this;
		write_review_area = $(this).parent();
		reviews_button = $(current_player).find(".product_button_reviews");
		review_area = $(current_player).find(".product_reviews");
		
		customer_review = $(write_review_area).find('.product_write_review_box').find('textarea').val();
		
		
		if(customer_review != '' && customer_review != default_review_text){
			$(review_button).html('<img src="http://cache.sermonspice.com/media/default/images/loading.gif" height="15px">');
			$.getJSON('/products/reviews/'+current_product+'/add?review='+customer_review, function(data) {
				if(data.status){
					write_review_area.hide();
					
					$(reviews_button).addClass('product_button_highlight');
					$(review_area).show(collapse_top_style, {}, toggle_speed);
					$(review_area).html('<img src="http://cache.sermonspice.com/media/default/images/loading.gif" height="15px">');
					
					$.getJSON('/products/reviews/'+current_product, function(data) {
						if(data.status == 'success'){
							$(review_area).html('');
						
							$.each(data.reviews, function(i, review){
								review_content = '<div class="product_review"><div class="product_review_title">' + review.customer + ' - <span class="review_date">' + review.date + '</div><div class="product_review_content">' + review.review + '</div></div>';
								$(review_content).appendTo(review_area);
							});
						} else {
							$(review_area).html('No Reviews. Write a review!');
						}
					});
				}
			});
		}
	}
	
	$('.add_review_button_disabled').qtip({
		content: 'Please login to review this product.',
		show: { ready: false },
		hide: 'mouseout',
		position: {
			corner: {
				target: 'topMiddle',
				tooltip: 'bottomMiddle'
			}
		},
		style: {
			border: {
				width: 3,
				radius: 3
			},
			padding: 8, 
			textAlign: 'center',
			tip: true, // Give it a speech bubble tip with automatic corner detection
			name: 'red'
		}
	});
	
	$('.product_write_review_textarea').focus(function() {
		if($(this).val() == default_review_text){
			$(this).val('');
		}
	});
	
	$('.product_write_review_textarea').blur(function() {
		if($(this).val() == ''){
			$(this).val(default_review_text);
		}
	});
	
	$(".similar_product").qtip({
		position: {
			corner: {
				target: 'topMiddle',
				tooltip: 'bottomMiddle'
			}
		},
		style: {
			name: 'cream',
			border: {
				width: 3,
				radius: 3
			},
			padding: 10, 
			textAlign: 'center',
			tip: true
		}
	});
	
	$('textarea').elastic();
	
	$f(".video_player",{
		src: 'http://cache.sermonspice.com/media/lockdown/flash/flowplayer.commercial-3.2.7.swf', 
		version: [9, 115],
		onFail: function(){
			noflash_notice();
			}
		}, 
		{
		
		clip: {
			autoPlay: false,
			autoBuffering: true,
			baseUrl: 'http://downloads.sermonspice.com/flash_previews/',
			scaling: 'fit',
	        
	        onStart: function(clip) { 
				//report start
				try {_gaq.push(['_trackEvent', "Videos", "Start", unique_product_name]);}
				catch (err) {}
				
				$.getJSON('/products/video_view/'+current_product+'/add/json', function(data) {
					$(current_player).find('.video_views').html(data.views);
				});
				
				// bind a function to the window closing
				$(window).bind("beforeunload", function(){
				});
				
				//report playback time and percentage just before user leaves the page
				window.onbeforeunload = function() {
					//get the clip length
					cliptime = clip.duration;
					if(current_player){
						current_video_time = $(current_player).find(".product_player").flowplayer(0).getTime();
					} else {
						current_video_time = "NaN";
					}
					
					if (current_video_time/cliptime == "NaN"){
						//user closed video, playback % was already reported; don't do any more reporting
					} else {
						//get % played
						percentPlayback = (current_video_time/cliptime)*100;
						//report % played
						try {_gaq.push(['_trackEvent', "Videos", "Percentage", unique_product_name, parseInt(percentPlayback)]);}
						catch (err) {}
						//report time played
						try {_gaq.push(['_trackEvent', "Videos", "Playtime", unique_product_name, parseInt(current_video_time)]);}
						catch (err) {}
			        }
				}
	        },
			key: $('body').data('flowplayer_license'),
	        onPause: function(clip) { 
				//report pause
				try {_gaq.push(['_trackEvent', "Videos", "Pause", unique_product_name, parseInt(this.getTime())]);}
				catch (err) {}
	        },
	        onStop: function(clip) {
				cliptime = clip.duration;
				percentPlayback = (this.getTime()/cliptime)*100;
				
				//report stop
				try {_gaq.push(['_trackEvent', "Videos", "Stop", unique_product_name, parseInt(this.getTime())]);}
				catch (err) {}
				
				//report percentage played upon stop
				try {_gaq.push(['_trackEvent', "Videos", "Percentage", unique_product_name, parseInt(percentPlayback)]);}
				catch (err) {}	
				
				//report time played
				try {_gaq.push(['_trackEvent', "Videos", "Playtime", unique_product_name, parseInt(this.getTime())]);}
				catch (err) {}	
	        },
	        onFinish: function(clip) { 
				//report finish
				try {_gaq.push(['_trackEvent', "Videos", "Finish", unique_product_name]);}
				catch (err) {}
	        }
		},
		canvas: {
			backgroundColor: "#000000",
			backgroundGradient: 'none'
		},
		onFullscreen: function() { 
		    //report fullscreen
			try {_gaq.push(['_trackEvent', "Videos", "Fullscreen", unique_product_name]);}
			catch (err) {}
		},
		plugins: {
			controls: {
				autoHide: 'always',
				hideDelay: 1000,
				volumeSliderGradient: 'none',
				volumeSliderColor: '#000000',
				tooltipTextColor: '#ffffff',
				buttonOverColor: '#728B94',
				tooltipColor: '#5F747C',
				sliderColor: '#ffffff',
				durationColor: '#ffffff',
				progressGradient: 'medium',
				sliderGradient: 'none',
				backgroundColor: '#3d3d3d',
				borderRadius: '0px',
				backgroundGradient: 'none',
				bufferGradient: 'none',
				progressColor: '#112233',
				bufferColor: '#445566',
				timeBgColor: '#555555',
				timeColor: '#01DAFF',
				buttonColor: '#375068',
				height: 32,
				opacity: 0.70,
				fullscreen: true,
				tooltips: { 
					buttons: true, 
					fullscreen: 'Enter Fullscreen mode' 
				}
			}
		}
	});

var flash_fail = true;

function noflash_notice()
{	
	if (flash_fail == true)
	{
		$('#flash_fail_notice').dialog();
		flash_fail = false;	
	}
}

	/*$(".product_button_like").corner("5px");
	$(".product_button_share").corner("5px");
	$(".product_button_reviews").corner("5px");
	$(".add_review_button").corner("5px");*/
	//$(".add_to_cart").corner("5px");
	
	var KEYCODE_ESC = 27;
	$(document).keyup(function(e) {
		if (e.keyCode == KEYCODE_ESC) {
			if(current_product != 0){
				collapse_player(current_player);
			}
		} 
	});
	
	$('.product_share_link').focus(function(){
		$(this).select();
	});
	
	/*
     * Change the cart object to reflect the new count of products in the cart.
     * Any significant changes to this function should likely be replicated in
     * shopping_cart.js.  Ultimately it would be best to remove this function
     * to a scope where it is accessible from both shopping_cart and product.js
     * TODO: refactor this out of shopping_cart and product.js into one locaiton.
     */
    function change_quantity(amount) {
        amount = amount || 1;

		var quantity = parseInt($('#cart_quantity_display').html());
		
        quantity += amount;

		if(quantity == 1) {
			$('#items_in_cart_text').html('item in cart');
		} else {
			$('#items_in_cart_text').html('items in cart');
		}
		
		$('#cart_quantity_display').text(parseInt(quantity));
		$('#cart_button').effect("bounce", {}, 250);
	}
});
function save_rating(product_id, rating)
{
	if (user_logged_in)
	{
		$.getJSON("/products/rate_product/"+product_id+"/"+rating, 
			function(data) 
			{
				var new_width = data.result * 31.6;
				$('#current_rating_'+product_id).css('width', new_width);
								
				if (data.ratings != 0)
				{
					$('#ratings_'+product_id).show();
					$('#avg_ratings_'+product_id).show();
					$('#ratings_'+product_id).html(data.ratings);
					$('#avg_ratings_'+product_id).html(data.avg_rate);
				}
			});
	}
}
