// sidebar scroll up n down
//   - Autocomplete
//   - officially here - http://docs.jquery.com/UI/Autocomplete
//   - http://thepursuitofalife.com/jquery-autocomplete-choices/

// Main Document Ready Function, everything inside this block please

$(document).ready(function(){
		
	// simple input clear replacer
	$(".click_clear").click(function(){ $(this).val(""); })
	$(".add_new_link").click(function(){ $('newlink').toggle(); })
	$(".add_new_bin").click(function(){ $('newbin').toggle(); })
	
	// Toggle Blog Folder Folders	
	$(".folderToggle").click(function(){
		$(this).parent().children("#feedlist").toggle();		
		if ($(this).hasClass("iconFolderClose")) {
			$(this).addClass("iconFolderOpen");
			$(this).removeClass("iconFolderClose");			
		}else{
			$(this).addClass("iconFolderClose");
			$(this).removeClass("iconFolderOpen");
		};
	})
	
	// Show/Hide all toggle
	$('.showhide').click(function(){
		$(".toggle_comments").each(function(){
			// $(this).toggle();
					
			// This is here as IE7 doesn't like toggle on table rows or table elements
			if($(this).parents(".message_body_header").children(".toggle_comments").css("display") == 'none')
			{				  
					$(this).parents(".message_body_header").children(".toggle_comments").show();
			}else{
			    $(this).parents(".message_body_header").children(".toggle_comments").hide();                       
			}			
		})
	})
	
	// Click the thead and then open the descendent body
	$(".rss_entry thead").click(function(){
		$(this).parent().children(".toggle_comments").toggle();	
	})
	
	// Click Show Hide Link on a Single Item, eg. post hightlights
	$(".single_hide").click(function(){
		if($(this).parents(".message_body_header").children(".toggle_comments").css("display") == 'none')
		{
			  // console.log("show"); 
				$(this).parents(".message_body_header").children(".toggle_comments").show();
		}else{
			// console.log("hide");
		    $(this).parents(".message_body_header").children(".toggle_comments").hide();                       
		}
		
	})
	
	// Comment Form Submission
	$("#comment_form").submit(function(){	
		if(typeof(tinyMCE) != "undefined"){
			var posted = tinyMCE.get('body').getContent();
		}else{
			var posted = $('#body').val();
		}
		// console.log(posted.length)
		if(posted.length == 0){
			// Lets change this to a nice modal popup before pushing out
			alert('Please enter a message before submitting!');
			return false;
		}else{
			return true;
		}
	})

	// Follow / Unfollow Code
	$(".peering").live("click", function(){	
		clicked = $(this)
		$(this).parents(".ajax_update").children(".cog").show();	
		$.ajax({
		  type: "POST",
		  url: $(this).attr("data-target"),
		  success: function(msg){
				clicked.parents(".ajax_update_hide").hide('slow');
				clicked.parents(".ajax_update").html(msg);
		  }
		});	
		return false;
	})


	
	// Free tag form submission
	$("#free_tag_form").submit(function(){	
		// is it empty
		if($("#free_tag").val().length > 0){			
			$.ajax({
		   type: "POST",
		   url: $(this).attr("action"),
		   data: $(this).serialize(),
		   success: function(msg){
			 	$("#free_tag").val("");
		    $("#tagCloudContainer").html(msg);
		   }
		 });	
		};
		return false;
	})
	
	// Email Signup form
	$("#email_signup_form").submit(function(){	
		// is it empty
		if($("#email_name").val().length > 0){			
			$.ajax({
		   type: "POST",
		   url: $(this).attr("action"),
		   data: $(this).serialize(),
		   success: function(msg){
		    $("#email_signup_update").html(msg);
		   }
		 });	
		};
		return false;
	})
	
	
	
	// 	Votes
	$(".thumb").live("click", function(){
		target = $(this).parent();
		cog = $(this).parents(".floatbox_vote").children(".cog");
		cog.show();
		target.hide();
		
		$.ajax({
	   type: "POST",
	   url: $(this).attr("data-action"),
	   data: $(this).serialize(),
	   success: function(msg){			
			target.parents(".floatbox_vote").html(msg);
	   }
	 });	
	})
	
	// TinyMCE show form	
	$(".show_editor").click(function(){	
		$("#body").val($("#body").val().replace(/\n/g,'<br />'))
		initialise_tinymce();
		$('.show_editor').hide();

		return false;
	})
	
	if($('body').val() != ''){
		initialise_tinymce();
		$('.show_editor').hide();
	}	
	
	// Message Checkbox Changer
	$("#messagetask").change(function(){
		action = $(this).val();
			$('.inbox_row').each(function(obj){
				$(this).attr("checked", false);
				if (action == "all") { $(this).attr('checked', true); };
				if (action == "none") { $(this).attr('checked', false) };				
				if (action == "opened" && $(this).hasClass("opened")){ $(this).attr('checked', true); }
				if (action == "unopened" && $(this).hasClass("unopened")){ $(this).attr('checked', true); }
			});		
	})
	
	// Forum Comment Permalink Popups
	$(".permalink").each(function(){

		$(this).click(function(){ return false;}) // make sure they can't be clicked
		
		$(this).qtip({
	    content: {
	       title: {
	          text: 'this item\'s permalink',
	          button: 'x'
	       },
	       text: "" + $(this).attr("href") + ""
	    },
		  show: 'click',
			hide: true,
			position: {
			   corner: {
			      target: 'bottomMiddle',
			      tooltip: 'topLeft'
			   }
			},
		   style: {
		        padding: '9px',
		        border: {
		            width: 9,
		            radius: 10,
		            color: '#666666'
		         },
	            textAlign: 'left',
	            tip: true, // Give it a speech bubble tip with automatic corner detection		
		        name: 'light'
		      }    
		})		
	})
	
	// Portfolio Quick Adder
	$(".portfolio").each(function(){		
		$(this).click(function(){ return false;}) // make sure they can't be clicked		
		$(this).qtip({
	    content: {
		     title: {
	          text: 'Follow this Stock in your Portfolio(s)',
	          button: 'x'
	       },
			   url: $(this).attr("data-action"),
			   method: 'get'
	    },
		  show: 'click',
			hide: false,
			position: {
			   corner: {
			      target: 'bottomRight',
			      tooltip: 'leftTop'
			   }
			},
		  api:{	
					onContentUpdate: function()
					{						
						$("#portfolio_actions_add_form").submit(function(){
							 $.ajax({
							   type: "POST",
							   url: $(this).attr("action"),
							   data: $(this).serialize(),
							   success: function(msg){
									$("#portfolio_actions_add_update").html(msg)
							   }
							 });
							return false;
						})
					}
	     },
		   style: {
		        padding: '9px',
						width: '200px',
		        border: {
		            width: 9,
		            radius: 10,
		            color: '#666666'
		         },
	            textAlign: 'left',
	            tip: true, // Give it a speech bubble tip with automatic corner detection		
		        name: 'light'
		      }    
		})		
	})
	
	// Forum Comment Moderate Popup
	$(".moderate").each(function(){		
		$(this).click(function(){ return false;}) // make sure they can't be clicked
		
		$(this).qtip({
	    content: {
		     title: {
	          text: 'Please provide a reason',
	          button: 'x'
	       },
			   url: $(this).attr("data-action"),
			   method: 'get'
	    },
		  show: 'click',
			hide: false,
			position: {
			   corner: {
			      target: 'bottomMiddle',
			      tooltip: 'leftTop'
			   }
			},
		  api:{	
					onContentUpdate: function()
					{											
						$(".tooltip_button").click(function(){
							 form = $(this).parents("form");
							 $.ajax({
							   type: "POST",
							   url: form.attr("action"),
							   data: form.serialize(),
							   success: function(msg){
									form.children(".tooltip_update").html(msg)
							   }
							 });
							return false;
						})
					}
	     },
		   style: {
		        padding: '9px',
						width: '260px',
		        border: {
		            width: 9,
		            radius: 10,
		            color: '#666666'
		         },
	            textAlign: 'left',
	            tip: true, // Give it a speech bubble tip with automatic corner detection		
		        name: 'light'
		      }    
		})		
	})
	
	$(".tooltip").each(function(){		
		$(this).click(function(){ return false;}) // make sure they can't be clicked
		
		$(this).qtip({
	    content: {
		     title: {
	          text: $(this).attr("data-title"),
	          button: 'x'
	       },
			   url: $(this).attr("data-target"),
			   method: 'get'
	    },
		  show: 'click',
			hide: false,
			position: {
			   corner: {
			      target: 'bottomMiddle',
			      tooltip: 'rightTop'
			   }
			},
		  api:{	
					onContentUpdate: function()
					{						
						$(".tooltip_button").click(function(){
							 form = $(this).parents("form");
							 $.ajax({
							   type: "POST",
							   url: form.attr("action"),
							   data: form.serialize(),
							   success: function(msg){
									form.children(".tooltip_update").html(msg);
							   }
							 });
							return false;
						})
					}
	     },
		   style: {
		        padding: '9px',
						width: '160px',
		        border: {
		            width: 9,
		            radius: 10,
		            color: '#666666'
		         },
	            textAlign: 'left',
	            tip: true, // Give it a speech bubble tip with automatic corner detection		
		        name: 'light'
		      }    
		})		
	})
	
	
	// Unmoderate link
	$(".unmoderate").click(function(){
		item = $(this)
			$.ajax({
			   type: "GET",
			   url: $(this).attr("data-action"),
			   success: function(msg){
					item.parent().html(msg);
			   }
			 });
	})
		
	// Event and Game Sidebar Stuff
	$(".event_invite").click(function(){
		$.ajax({
		   type: "GET",
		   url: $(this).attr("data-target"),
		   success: function(msg){
				$("#invite_update").html(msg)
		   }
		 });
	})
	
	$(".show_form").click(function(){
		$("#form_to_show").show();
	})
	
	// Ramin-Autocomplete
	$(".autocomplete_users").autocomplete("ajax/autocomplete/user", {
		multiple: ",",
		dataType: "json",
		parse: function(data) {
			return $.map(data, function(row) {
				return {
					data: row,
					result: row.name,
					value: row.name
				}
			});
		},
		formatItem: function(item) {
			return item.name;
		}
	})
	
	$(".autocomplete_tags").autocomplete("ajax/autocomplete/tag", {
		multiple: ",",
		dataType: "json",
		parse: function(data) {
			return $.map(data, function(row) {
				return {
					data: row,
					result: row.name,
					value: row.name
				}
			});
		},
		formatItem: function(item) {
			return item.name;
		}
	})
	
	$(".autocomplete_tickers").autocomplete("ajax/autocomplete/stock", {
		multiple: ",",
		dataType: "json",
		parse: function(data) {
			return $.map(data, function(row) {
				return {
					data: row,
					result: row.ticker,
					value: row.ticker
				}
			});
		},
		formatItem: function(item) {
			return item.company;
		}
	})
	
	$(".autocomplete_stocks").autocomplete("ajax/autocomplete/stock", {
		multiple: false,
		dataType: "json",
		parse: function(data) {
			return $.map(data, function(row) {
				return {
					data: row,
					result: row.name,
					value: row.name
				}
			});
		},
		formatItem: function(item) {		
			return item.company;
		}
	})
	
	// Save Chart Stuff	
	$("#save_chart_form").submit(function(){
		$.ajax({
		   type: "POST",
		   url: 'chart/ajax',
			 data: $("#chart_form").serialize(),
		   success: function(msg){
				// console.log(msg)
				$("#chartResponse").html(msg);
		   }
		 });
		return false;
	})
	
	// // Update Chart Stuff	
	// $("#chart_form").submit(function(){
	//     //we encode the values of all form elements as query parameters
	//     var elements = this.elements;
	// 
	//     var url = "http://www.stockopedia.co.uk/image/stock_technical_chart?";		
	// 	// console.log(" -- ");		
	//     for (var i = 0; i < elements.length; ++i)
	//     {
	//         var e = elements[i];
	//         if (e.type == "checkbox")
	//             url = url + e.id + "=" + (e.checked ? "1" : "0") + "&";
	//         else
	//             url = url + e.id + "=" + escape(e.value) + "&";
	//     }
	//     //Now we update the URL of the image to update the chart
	//     $("#ChartImage").attr('src', url);
	// 	return false;
	// })
	
	
		// Chart Tabs
		$(".chart_tabs").live("click", function(){
			$('#chart_1').attr('src' , $(this).attr('data-src'));
			$(".chart_tabs").removeClass('active');
			$(this).addClass('active');
		})

		// Email Popup Thing
		$("#email_signup_box").qtip({
		   content: {
	     title: {
		          text: '<img src="http://www.stockopedia.co.uk/images/emails/email_preview.png">',
		          button: 'x'
		       }
		    },
		  show: 'click',
			hide: false,
			position: {
			   corner: {
			      target: 'rightMiddle',
			      tooltip: 'leftMiddle'
			   }
			},
		   style: {
		        padding: "9px",
						width: '260',
		        border: {
		            width: 9,
		            radius: 10,
		            color: '#666666'
		         },
            textAlign: 'left',
            tip: true, // Give it a speech bubble tip with automatic corner detection		
		        name: 'light'
		      }    
		})

		// History Page Radio Buttons
		$(".history_radio").click(function(){
			var index = new Array();
			clicked_index = 2;
			clicked_side = "not";
			clicked = $(this);
			count = 0;
		
			$(".history_radio").each(function(){
				if($(this).get(0) == clicked.get(0)){
					clicked_side = clicked.attr("name")
					clicked_index = count; 			
				}
				count++;
			})
		
			count = 0;
			$(".history_radio").each(function(){
				if (clicked_side == "old") {
					if ($(this).attr("name") == "new" && count > (clicked_index)){ 
						$(this).hide();				
					}
					if ($(this).attr("name") == "new" && count < (clicked_index)){ 
						$(this).show();				
					}
				};
				
				if (clicked_side == "new") {
					if ($(this).attr("name") == "old" && count > (clicked_index)){ 
						$(this).show();				
					}
					if ($(this).attr("name") == "old" && count < (clicked_index)){ 
						$(this).hide();				
					}
					
				};
				count++;
			})
		})

		// Ad Reposition - amazing eh?
		// $(".scrollAutoAd").reposition();

		
		// Document View Stuff		
		var current_page = 1;
		var page_max = $('.page_count').attr("data-page-count");
		var image_width = $("#document_container").width() - 35;
		var resized = false;
		$('#document_page').attr("width", image_width);
						
		$(window).resize(function(){
			if (resized == false) {
				var image_width = $("#document_container").width() - 35;
				$('#document_page').attr("width", image_width);
			};			
		})

		$('.page_prev').live("click", function(){	
			if (current_page > 1) {
				current_page--;			
			};
			$("#document_page").attr("src", $('#document_page').attr("data-page-source") + "page_" + current_page + ".png")
			
			$(".page_feedback").each(function(){
				$(this).html("page " + current_page + " of " + page_max);
			})	
			
		})

		$('.page_next').live("click", function(){			
			if (current_page < page_max) {
				current_page++;	
			};
			$("#document_page").attr("src", $('#document_page').attr("data-page-source") + "page_" + current_page + ".png")

			$(".page_feedback").each(function(){
				$(this).html("page " + current_page + " of " + page_max);
			})
		})

		$('.zoom').live("click", function(){
			$('.document_outside').css("max-height", 	$('.document_outside').height());
			$('.document_container').css("max-height", 	$('.document_container').height());
						
			width = $("#document_page").attr("width")			
			resized = true
			
			if ($(this).attr("data-action") == "in") {
				$("#document_page").attr("width", width + 60) 
				$("#document_page").draggable();
				$("#document_page").css("cursor","move");
				width = $("#document_page").attr("width")
			};	

			if ($(this).attr("data-action") == "out" && width >= image_width) {
				$("#document_page").attr("width", image_width - 60);
				width = $("#document_page").attr("width")
			}
			
			if ($(this).attr("data-action") == "out" && width <= image_width) {
				$('#document_page').attr("style", "");
				$('#document_page').attr("width", image_width);
				resized = false
			}
		})				
});



// This is the reposition thing in plug in format
(function(f){
	jQuery.fn.reposition = function() { 
 		return this.each(function() { 
			var original_position = 0;
			var original_left = 0;
			var new_position = 0	
			var target = $(this);
			var endPlace = 0;

	
			// Set up the details and the scroll event
			$(document).ready(function(){
				original_position = $(target).offset()["top"];
				original_left = $(target).offset()["left"];
				height = $(target).height();
				overflow_bottom = $("#bottom").offset()['top'] - 15;
				bottom_offset = overflow_bottom - (height);
												
				// Start tracking and registering the scroll
				$(window).scroll(function(){ 
					trackPosition(target, original_position);
				})	
				
				// Stop it sliding left and right if you resize the window
				$(window).resize(function(){ 					

					original_left = $(target).offset()["left"];
					height = $(target).height();
					overflow_bottom = $("#bottom").offset()['top'] - 5;
					bottom_offset = overflow_bottom - (height);

					// Start tracking and registering the scroll
					$(window).scroll(function(){ 
						trackPosition(target, original_position);
					})	

					// Stop it sliding left and right if you resize the window
					$(window).resize(function(){ 					
						original_left = $(target).offset()["left"];
					})
				})

			})
			
			function trackPosition(element, old_position){	

				if ((original_position + height) < bottom_offset) { // this condition will stop page getting stuck
					if (($(window).scrollTop() > old_position)){ 				
						element.css({
								"top": '0px',
								"position" : "fixed",
								"width": element.width(),
								"paddingTop": '5px'
						})
					}

					if (($(window).scrollTop() < old_position)){ 				
						element.css({
								"position" : "static",
								"width": element.width(),
								"paddingTop": '5px',
								"top": 'auto'
						})
					}					
				};
													
				if ((element.offset()['top'] + height) > (overflow_bottom)){ 												
					$(element).css({
							"position" : "relative",
							"padding-top" : (overflow_bottom - height) - original_position,	
							"padding-bottom" : "0px"							
					})
				}
			}	
		})
	}	
})(jQuery);




function reply(username, post_number)
{	
	var quote = "<p>In reply to " + username + " " + "<a href=\"http://" + window.location.host +  window.location.pathname +"?comment=" + post_number + "#"+post_number+"\">(post #" + post_number + ")</a></p>\n";

	if(typeof(tinyMCE) !== "undefined"){
		tinyMCE.get('body').execCommand('mceSetContent', false,  quote);
	}else{
		initialise_tinymce();
		try
		{
			$('#body').val(quote);
		}
		catch(ex)
		{			
			var t = setTimeout("reply('" + username + "', '" + post_number + "');", 1000);		
		}
	}
}



(function($)
{
	$.fn.blink = function(options)
	{
		var defaults = { delay:500 };
		var options = $.extend(defaults, options);

		return this.each(function()
		{
			var obj = $(this);
			setInterval(function()
			{
				if($(obj).css("visibility") == "visible")
				{
					$(obj).css('visibility','hidden');
				}
				else
				{
					$(obj).css('visibility','visible');
				}
			}, options.delay);
		});
	}
}(jQuery))