$(function(){
	current_product = null;
	current_product_id = null;
	product_name = null;
	unique_product_name = null;
	video = false;
	current_flag_id = 0;
	original_height = 0;
	
	toggle_style = 'blind';
	toggle_speed = 500;

	default_review_text = 'Write your review here...';
	
	function expand_product(product)
	{
		if($(product).attr('product_type') == 'Bundle'){
			window.location.href = '/bundle/'+$(product).attr('product_id')+'/'+$(product).attr('url_friendly_title');
		} else {
			video = true;
			player = $(product).find(".product_player");
			product_video_preview = $(player).attr('video_url');
			product_video_cdn = $(player).attr('cdn');
			if (product_video_preview == '.flv' || product_video_preview == undefined) {
				$(product).find(".product_player").hide();
				video = false;
			}

			$(product).find(".product_toggle").html('close');
			$(product).find(".product_closed").hide(toggle_style, {}, toggle_speed);
			$(product).find(".product_open").show(toggle_style, function() {
				scroll_to_product(product);
				if(product_video_cdn == 'false')
				{
					$(product).find(".product_player").flowplayer(0).getClip(0).update({
						provider:'http'
					});
				}
				if(video)
				{
					$(product).find(".product_player").flowplayer(0).play(product_video_preview);
				}

				$(product).find(".add_to_cart").click(add_to_cart_click);
			}, toggle_speed);
			load_sharing();
			load_reviews();
			load_recommendations();
		}
	}
	
	function set_product_attributes(product)
	{
		current_product = product;
		current_product_id = $(product).attr('product_id');
		original_height = product.height();
		product_name = $(product).attr('product_title');
		unique_product_name = product_name +' - '+current_product;
	}
	
	$f(".product_player", {
		src: 'http://cache.sermonspice.com/media/lockdown/flash/flowplayer.commercial-3.2.7.swf', 
		version: [9, 115],
		onFail: function(){
			noflash_notice();
		}
	},
	{
		key: $('body').data('flowplayer_license'),
		canvas: {
			backgroundColor: "#000000",
			backgroundGradient: 'none'
		},
		clip: {
			autoPlay: false,
			autoBuffering: true,
			provider: 'rtmp',
			scaling: 'fit',
			onStart: function(clip)
			{
				//report start
				try {_gaq.push(['_trackEvent', "Videos", "Start", unique_product_name]);}
				catch (err) {}
				$.getJSON('/products/video_view/'+current_product_id+'/add/json', function(data) {
					$(current_product).find('.video_views').html(data.views);
				});
				load_embed();
				// 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_product) {
						current_video_time = $(current_product).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) {}
					}
				}
			},
		        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) {}
		        }
		},
		onFullscreen: function() {
		    // report fullscreen
			try {_gaq.push(['_trackEvent', "Videos", "Fullscreen", unique_product_name]);}
			catch (err) {}
		},
		plugins: {
			rtmp: {
				url: 'http://cache.sermonspice.com/media/lockdown/flash/flowplayer.rtmp-3.2.3.swf',
				netConnectionUrl: 'rtmp://flash.sermonspice.com/cfx/st'
			},
			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' 
				}
			}
		}
	});
	
	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, .add_review_button_disabled, .flag_reason, .flag_submit').each(function() {
			var action = '';
			if ($(this).hasClass('product_button_like'))
			{
				action = 'favorite'
			}
			if ($(this).hasClass('add_review_button_disabled'))
			{
				action = 'review'
			}
			if ($(this).hasClass('star_rating'))
			{
				action = 'rate'
			}
			if ($(this).hasClass('flag_reason'))
			{
				action = 'flag'
			}
			if ($(this).hasClass('flag_submit'))
			{
				action = 'flag'
			}
			
			$(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 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 load_sharing()
    {
    	share_button = $(current_product).find(".product_button_share");
		share_area = $(current_product).find(".tab_share");
		product_title = $(current_product).attr('product_title');
		share_link = $(current_product).find(".product_share_link");
		copy_button = $(current_product).find(".copy_link");
		
    	var clip = new ZeroClipboard.Client();
    	clip.glue('copy_link_button_'+current_product_id);
    	clip.setText(share_link.val());
        
        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'>");
        });
    }
    
    $('.add_review_button').click(review_product);
    
    $('.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);
		}
	});
	
	function review_product(object){
		review_button = this;
		reviews_button = $(current_product).find(".product_button_reviews");
		review_area = $(current_product).find(".product_reviews");
		review_box = $(current_product).find('.product_write_review_box').find('textarea');

		customer_review = $(review_box).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_id+'/add?review='+customer_review, function(data) {
				if(data.status){
					$(review_box).hide();
					$(review_button).hide();
					load_reviews();
				}
			});
		}
	}
    
	function load_reviews(){
		review_area = $(current_product).children().find(".product_reviews");
		$(review_area).html('<img src="http://cache.sermonspice.com/media/default/images/loading.gif" height="15px">');

		$.getJSON('/products/reviews/'+current_product_id, function(data) {
			if(data.status == 'success')
			{
				$(review_area).html('');
				$.each(data.reviews, function(i, review){
					review_content = '<div class="product_review">';
					review_content+= '<div class="product_review_title">'+review.customer+' - '; 
					review_content+= '<span class="review_date">'+review.date+'</span>';
					review_content+= '</div>';
					review_content+= '<div class="product_review_content">'+review.review+'</div>';
					review_content+= '</div>';
					$(review_content).appendTo(review_area);
				});
			} else {
				$(review_area).html('<div class="product_review_title">No Reviews. Write a review!</div>');
			}
		});
	};
	
	function load_recommendations(){
		recommendations_area = $(current_product).children().find(".product_recommendations");
		
		$(recommendations_area).html('<img src="http://cache.sermonspice.com/media/default/images/loading.gif" height="15px">');
		
		var recommendation_url = '/recommendations/get_recommendations_xml/viewed/'+current_product_id;
		var recommendations_found = false;
		
		$.ajax({
			url: recommendation_url,
			dataType: "xml",
			success: function(xml) {
			$(recommendations_area).html('');
				$(xml).find('easyrec').each(function(){
					$(this).find('recommendeditems').each(function(){
						$(this).find('item').each(function(){
							if (recommendations_found == false) {
								$(recommendations_area).html('<div class="product_recommendations_header">Other users also viewed</div>');
								recommendations_found = true;
								
							}						
							var recommended_product_id = $(this).find('id').text();
							var recommended_product_url = $(this).find('url').text();
							
							recommended_product_url = recommended_product_url.replace('://ip-10-114-118-137.ec2.internal:','://recommendations.sermonspice.com:');
							
							$.ajax({
								url: '/products/product/'+recommended_product_id+'/false/xml',
								dataType: "xml",
								success: function(xml){
									$(xml).find('root').each(function(){
										$(this).find('product').each(function(){
											var product_title = $(this).find('product_title').text();
											var image_url = $(this).find('image_url').text();
											
											var product_title_link = '<div class="top_product_label">'+product_title+'</div>';
											var product_thumbnail = '<div class="product_thumbnail"><img src="'+image_url+'" class="thumbnail"></div>';
											
											var recommended_product = '<div class="float_left recommended_product">';
											recommended_product+= '<a href="'+recommended_product_url+'" >';
											recommended_product+= product_thumbnail+product_title;
											recommended_product+= '</a>';
											recommended_product+= '</div>';
											
											$(recommended_product).appendTo(recommendations_area);
										});
									});
								}
							});
							
						});
					});
				});
			},
			error : function(xhr, stat){
			}
		});
	}
	
	function load_embed()
	{
		embed_code = $(current_product).find(".product_share_embed_code");
		embed_code_button = $(current_product).find(".embed_code");
		product_title = $(current_product).attr('product_title');
		share_link = $(current_product).find(".product_share_link");
		video_player = $(current_product).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.text(html_code);
		
		clip = new ZeroClipboard.Client();
		clip.glue('embed_button_'+current_product_id, 'embed_button_container_'+current_product_id);
		clip.setText(embed_code.val());
		
		clip.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'>");
		});
	}
	
	function like_product()
	{
		like_button = this;
		
		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/" + current_product_id,
				success: function(xml){
					$(xml).find('favorite').each(function(){
						var action = $(this).find('action').text();
						
						if (action == 'remove') {
							$(like_button).removeClass('product_button_cart_down');
							$(like_button).effect("highlight", {}, 500);
							$(like_button).html("<img src='http://cache.sermonspice.com/media/lockdown/images/icons/favorite/favorite2_add.png'>&nbsp;<span class='button_text'>Add to favorites</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/" + current_product_id,
				dataType: "xml",
				success: function(xml)
				{
					$(xml).find('favorite').each(function()
					{
						var action = $(this).find('action').text();
						
						if (action == 'add')
						{
							$(like_button).addClass('product_button_cart_down');
							$(like_button).effect("highlight", {}, 500);
							$(like_button).html("<img src='http://cache.sermonspice.com/media/lockdown/images/icons/favorite/favorite2_del.png'>&nbsp;<span class='button_text'>Remove from favorites</span>");
							
							try {_gaq.push(['_trackEvent', "Videos", "Like", unique_product_name]);}
							catch (err) {}
						}
					});
				}
			});
		}
	}
	
	$('.product_share_link').focus(function(){
		$(this).select();
	});
	
	$('.stars').click(function () {
		rating = $(this).attr('stars');
		product_id = $(this).parents('.product').attr('product_id');
		rating_loading = $(this).parents('.product_rating_stats').find(".rating_loading");
		rating_loading.show();
		
		save_rating(product_id, rating);
		return false;
	});
	
	function save_rating(product_id, rating)
	{
		if (user_logged_in)
		{
			$.getJSON("/products/rate_product/"+product_id+"/"+rating, 
				function(data) 
				{
					var new_width = data.result * 17.2;
					$('.current_rating_'+product_id).css('width', new_width);
									
					if (data.ratings != 0)
					{
						// success
						rating_loading = $("#product_"+product_id).find(".rating_loading");
						rating_loading.hide();
					}
				});
		}
	}
	
	$('.flag_description').hide();
	$('[id^="flag_reason_"]').click(function(){
		$('.flag_description').show(toggle_style, {}, toggle_speed);
		
        var selected_product_id = $(this).attr("product_id");
        var selected_reason_id = $(this).val();
        
        $('[id^="flag_desc_'+ selected_product_id + '_"]').hide();
        if ($(this).attr("checked") == true)
        {
            $("#flag_desc_"+ selected_product_id + "_" + selected_reason_id).val("");
            $("#flag_desc_"+ selected_product_id + "_" + selected_reason_id).show();
        }
    });
	
	$('.flag_submit').click(function(){
		if (user_logged_in)
		{
			report_flag(current_product_id);
		}
	});
	
	function report_flag(product_id)
	{
	    var reason_id = $('input[name=flag_reason_'+product_id+']:checked').val();
	    var desc = $("#flag_desc_"+ product_id).val();
	    if (desc.length > 0)
	    {
	        data = create_flag_data(product_id, reason_id, desc);
	        $.ajax({
	              type: 'POST',
	              url: "/products/flag_product",
	              data: data,
	              dataType: "json",
	              success: function()
	              {
	            	  $("#flag_form_"+product_id).hide(toggle_style, {}, toggle_speed);
	            	  $("#flag_message_"+product_id).html("Thank you for reporting this problem, we will review your reported issue.");
	              }
	        });
	    }
	    else
	    {
	         $("#flag_message_"+product_id).html("A description is required to flag the video.");
	    }
	}
	function create_flag_data(product_id, reason_id, desc)
	{
	    var data = "product_id=" + product_id + "&reason_id=" + reason_id + "&description='" + desc +"'";
	    return data;
	}
	
	var flash_fail = true;

	function noflash_notice()
	{	
		if (flash_fail == true)
		{
			$('#flash_fail_notice').dialog();
			flash_fail = false;	
		}
	}
});

