jQuery.fn.blog_form = function(){
	return this.each(function(){
		var form = this;
		var cats = $('input.category');
		var subc = $('select.subcategory');
		if ($('input[name=category]:checked').val() != 8) $('#fieldset-for-product').hide();
		if (!$('select.subcategory').val()) $('#fieldset-for-subcategory:visible').hide();
		$(cats).click(function(){
			$('#fieldset-for-subcategory:hidden').fadeIn();			
			parent = $(this).val();
			if (parent == 8) {
				$('#fieldset-for-product:hidden').fadeIn();
			} else {
				$('#fieldset-for-product:visible').fadeOut();				
			}
			$.getJSON('/categories/'+parent, function(data){
				if (data.categories && data.categories.length > 0) {
					str = '';
					$('#fieldset-for-subcategory:hidden').fadeIn();					
					$(subc).attr('disabled', '');
					for(cat in data.categories) str = str + '<option value="'+data.categories[cat].value+'">' + data.categories[cat].label + '</option>';
					$(subc).html(str);
				} else {
					$('#fieldset-for-subcategory').fadeOut();
					$(subc).html('');
					$(subc).attr('disabled', 'disabled');
				}
			});
		});
	});
};

jQuery.fn.form_makes_busy = function(){
	return this.each(function(){
		$(this).submit(function(){
			$('.buttonHolder.action', this).fadeOut('fast');
			make_busy();
		});
	});
};

jQuery.fn.has_simple_dialog = function(csswidth) {
	return this.each(function(){
		var ele = this;
		ele.url = $(this).attr('href');
		$(this).click(function(){
			jQuery.getJSON(ele.url, {}, function(data){
				$('body').block({message:data.html,css:{width:csswidth,cursor:'normal', centeredX:true, centeredY:true}});
				fix_stupid_blockui();
				$('a.end-block-ui').unblock_body();
			});
			return false;
		});
	});
};

jQuery.fn.has_dialog = function(callback) {
	return this.each(function(){
		var ele = this;	
		ele.url = $(this).attr('href');
		$(this).click(function(){
			jQuery.ajax({
				url: ele.url,
				type:'GET',
				dataType:'json',
				success: function(data) {
					var new_ele = $(data.html);
					$.blockUI({message:new_ele,css:{cursor:'normal'}});
					fix_stupid_blockui();
					$('.close-dialog', new_ele).unblockeverything();
					$('input[type=text]:first', new_ele).focus();
					if (callback != false) callback(data, new_ele, ele);
				}
			});
			return false;
		});
	});
};

jQuery.fn.has_dangerous_dialog = function(callback) {
	return this.each(function(){
		var ele = this;	
		ele.url = $(this).attr('href');
		$(this).click(function(){
			jQuery.ajax({
				url: ele.url,
				type:'GET',
				dataType:'json',
				success: function(data){
					var new_ele = $(data.html);
					$.blockUI({message:new_ele,css:{cursor:'normal'}});
					fix_stupid_blockui();
					$('.close-dialog', new_ele).unblockeverything();
					$('.submit-dialog', new_ele).click(function(){
						if (confirm("Are you sure?")) {
							make_busy();
							$('form', new_ele).submit();
						}
					});
				}
			});
			return false;
		});
	});
};

jQuery.fn.form_has_dialog = function(pin, callback) {
	var pin = (pin == null) ? "center" : pin;
	var callback = (callback == null) ? false : callback;
	return this.each(function(){
		var ele = this;
		ele.pin = (pin !='center') ? pin : false;
		var options = {
			dataType:'json',
			success: function(data){
				var new_ele = $(data.html);
				if (callback != false) callback(data, new_ele);
			}
		}
		$(ele).submit(function(){
			jQuery(ele).ajaxSubmit(options);
			return false;		
		});
	});
};


jQuery.fn.form_has_appending = function(callback) {
	return this.each(function(){
		var form = this;
		$(this).submit(function(){
			var options = {
				dataType:'json',
				beforeSubmit: function() {
					make_busy();
				},
				success:function(responseText, statusText){
					var str = '';
					jQuery('ul.messages', form).remove();
					if (responseText.errors !== undefined && responseText.errors.length > 0) {
						jQuery('ul.errorlist',form).remove();		
						for(error in responseText.errors) str += '<li>'+responseText.errors[error]+'</li>';
						if (str.length > 0) 
						{
							if (!responseText.append_errors_to || responseText.append_errors_to == undefined) $('fieldset:first',form).before('<ul class="errorlist">'+str+'</ul>');
							else $(responseText.append_errors_to,form).append('<ul class="errorlist">'+str+'</ul>');
						}
						$.unblockUI();
					} else {
						$.unblockUI();
						if (responseText.html && responseText.append_to) {
							$(responseText.html).css('display', 'none').appendTo(responseText.append_to).slideDown("fast");
						} else if (responseText.html) {
							var new_ele = $(responseText.html);
							$.blockUI({message:new_ele,css:{cursor:'normal'}});
							$('.close-dialog', new_ele).unblockeverything(); 
							$('input[type=text]:first', new_ele).focus();
						}
						jQuery('ul.errorlist', form).remove();
						$(form).clearForm();
						if (callback != undefined) callback(responseText);
					}
				}
			}
			$(form).ajaxSubmit(options);
			return false;
		});
	});
};

jQuery.fn.online_id_form = function(){
	return this.each(function(){
		var form = $('form', this);
		var disp = $('.user-game-id', this);
		var li = this;
		var ul = $(li).parent();
		var options = {
			dataType:'json',
			beforeSubmit: function(){
				$.blockUI();
			},
			success:function(responseText, statusText){
				var str = '';
				if (responseText.errors.length > 0) {
					jQuery('ul.errors',form).remove();
					for(error in responseText.errors) str += '<li>'+responseText.errors[error]+'</li>';
					if (str.length > 0) jQuery('fieldset:first',form).before('<ul class="errors">'+str+'</ul>');
				} else {
					$(disp).remove();
					$(form).before(responseText.view).before(responseText.editform);
					$(form).remove();
					$(li).online_id_form();
				}
				$.unblockUI();
			}
		}
		$(form).ajaxForm(options);
		$('a.edit-element', disp).click(function(){
			$('.user-game-id', li).hide();
			$(form).fadeIn();
			return false;
		});
		$('select[name=console]', form).change(function(){
			if (consoles[$(this).val()] != 1) $('input[name=game]', form).val('').parent().fadeOut('fast');
			else $('input[name=game]', form).parent().fadeIn('fast');
		});
		$('a.delete', form).click(function(){
			if (confirm('Are you sure you want to delete this ID?')) {
				if ($('input[name=id]', form).length < 1) {
					$(li).fadeOut('fast', function(){
						if ($(li).hasClass('first')) $('li:nth-child(2)', $(this).parent()).addClass('first');
						$('li.none', $(this).parent().parent()).show();				
						$(li).remove();
					});
				} else {
					var ci = $('input[name=id]', form).val();
					$.blockUI();
					$.post("/profile/gamertags/delete/", {'id': ci}, function(data){
						if (data.view !== undefined) $(li).before(data.view);
						$(li).remove();
					}, 'json');
					$.unblockUI();
				}
			}			
			return false;
		});
		$('a.accept', form).click(function(){
			$(form).ajaxSubmit(options);
		});
	});
};

jQuery.fn.add_online_id_form = function(add_to){
	return this.each(function(){
		var li = $(add_to).get(0);
		var prototype = $('.prototype', li);
		$(this).click(function(){
			$('li.none', add_to).hide();
			$('.first', li).removeClass('first');
			$(li).prepend($(prototype).clone().removeClass('prototype').addClass('first').fadeIn().online_id_form());
		});
	});
};

jQuery.fn.playing_form = function(){
	var form = this;
	$('a.accept', form).click(function(){
		var options = {
			dataType:'json',
			beforeSubmit: function() {
				$.blockUI();
			},
			success:function(responseText, statusText){
				jQuery('ul.messages', form).remove();
				$('fieldset:first', form).before('<ul class="messages"><li>Changes saved.</li></ul>');
				$.unblockUI();
			}
		}
		$(form).ajaxSubmit(options);
	});
};

jQuery.fn.status_form = function(){
	return this.each(function(){
		var form = this;
		var origme = jQuery('p.quote-meta').clone();
		var options = {
			dataType: 'json',
			beforeSubmit: function(){
				$.blockUI();
			},
			success: function(responseText, statusText){
				if (responseText.errors !== undefined) {
					var str = '';
					jQuery('ul.errors',form).remove();
					for(error in responseText.errors) str += '<li>'+responseText.errors[error]+'</li>';
					if (str.length > 0) jQuery('p.about',form).before('<ul class="errors">'+str+'</ul>');
					if (str.length < 1) {
						jQuery('#quote-text span span').html(responseText.passthrough.status);
						jQuery('textarea', form).hide();
						jQuery('#quote-text').show();				
						jQuery('p.quote-meta').replaceWith(origme);
						jQuery('p.quote-meta span').html('Just updated');
						form.bind_up();
					} else {
						jQuery('textarea', form).focus();
					}
				}
				$.unblockUI();
			}
		};
		this.bind_up = function(){
			jQuery(this).ajaxForm(options);
			origme = jQuery('p.quote-meta').clone();
			jQuery('a.edit-quote').click(function(){
				jQuery('#quote-text').hide();
				jQuery('textarea', form).fadeIn();
				jQuery('textarea', form).focus();				
				jQuery('p.quote-meta').html('<a href="#" class="save-changes">Save Changes</a>');
				jQuery('p.quote-meta a').click(function(){
					jQuery(form).ajaxSubmit(options);
					return false;
				});
				return false;
			});			
		};
		form.bind_up();		
	});
};

jQuery.fn.registration_form = function(){
	return this.each(function(){
		var form = this;
		var hasErrors = false;
		var options = {
			dataType: 'json',
			beforeSubmit: function(){
				make_busy();
			},
			success: function(responseText, statusText){
				if (responseText.errors !== undefined) {
					var str = '';
					jQuery('ul.errorlist',form).remove();
					for(error in responseText.errors) str += '<li>&rarr;&nbsp;&nbsp;'+responseText.errors[error]+'</li>';
					if (str.length > 0) 
					{
						jQuery('fieldset:first',form).before('<ul class="errorlist"><li class="first">Oops, we had a few problems registering you:</li>'+str+'</ul>');
					}
					else 
					{
						window.location = "/accounts/confirmation/";
					}
				}
				$.unblockUI();
			}
		};
		jQuery(this).ajaxForm(options);
	});
};

jQuery.fn.enable_attachment_forms = function(){
	return this.each(function(){
		$('.youTube', this).click(function(){
			if ($('.youtube-attachment:visible').length < 1) {
				if ($('.photo-attachment:visible').length > 0) $('.photo-attachment').hide();				
				$('.youtube-attachment').show();
				$('.attachment').removeClass('photo-active').addClass('youtube-active');
			} else {
				$('.attachment').removeClass('youtube-active');
				$('.youtube-attachment').hide();
			}
			return false;			
		});
		$('.photo', this).click(function(){
			if ($('.photo-attachment:visible').length < 1) {
				if ($('.youtube-attachment:visible').length > 0) $('.youtube-attachment').hide();
				$('.photo-attachment').show();
				$('.attachment').addClass('photo-active').removeClass('youtube-active');				
			} else {
				$('.attachment').removeClass('photo-active');				
				$('.photo-attachment').hide();
			}
			return false;
		});
		$('.attachment-actions .cancel').click(function(){
			$('.attachment').removeClass('photo-active');
			$('.attachment').removeClass('youtube-active');			
			$('.photo-attachment').hide();
			$('.youtube-attachment').hide();			
		});
	});
};

jQuery.fn.enable_youtube_form_for_message = function(){
	return this.each(function(){
		var ele = this;
		var parent = $('#id_body').get(0);
		var input = $('.youtube-url', ele).get(0);
		var buttn = $('.btn', ele).get(0);
		$(input).defaultValue("Paste your URL or video ID here...");
		$(buttn).click(function(){
			$(buttn).unbind();
			ele.submit();
			$(buttn).click(function() {
				ele.submit();
			});
		});
		$(input).keypress(function(e){
			if (e.which == 13) {
				ele.submit();
				return false;
			}
		});
		ele.submit = function(){
			var data = {};
			data['url'] = $(input).val();
			$.post('/wall/attach_youtube/', data, function(newData, textStatus){
				$(parent).after(newData['html']);
				$('.youtube-attachment').hide();
				$('.attachment').removeClass('youtube-active');								
				$('.detach').click(function(){
					var par = $(this).parent().parent();
					$(par).fadeOut('normal', function(){
						$(par).remove();
					});
				});
				$(input).val('').blur();
				if ($('#id_body').val() == 'Speak your mind here...') {
					$('#id_body').val('');
				}
			}, "json");
		};
	});
};

jQuery.fn.enable_search_form = function(){
	return this.each(function(){		
		ele = this;
		ele.ols = 0;
		ele.has_results = false;
		ele.highlighted = -1;
		ele.form_options = {
			dataType: 'json',
			cache:false,
			success: function(responseText, statusText){
				if (responseText.html != undefined) {
					ele.has_results = true;
					var newnode = resultview = $(responseText.html);
					ele.ols = $('ol li', newnode).length;
					if ($('#search-results').length > 0) $('#search-results', ele).html($('.search-results-view', newnode).get(0));
					else $(ele).append(newnode);
					$('#search-results').fadeIn('fast');
					$('body').unbind('click').click(function(ev){
						if ($(ev.target).parents('#id_q').length > 0) return true;
						if ($(ev.target).parents('#search-results').length > 0) return true;
						if ($(ev.target).attr('id') == 'id_q') return true;
						ele.reset();
						return false;
					});
					$('#search-results li').unbind('hover').hover(function(){
						$(this).addClass('hover');
					}, function(){
						$(this).removeClass('hover');
					});
				} else {
					ele.ols = 0;
					ele.highlighted = -1;
					ele.has_results = false;
					ele.reset();
				}
			}
		}
		$('input#id_q').keyup(function(event){
			if (event.keyCode == 40) {
				ele.down();
				return false;
			} else if (event.keyCode == 38) {
				ele.up();
				return false;
			} else if (event.keyCode == 13) {
				if ($('ol li.hover a').length > 0) {
					ele.load();
					return false;
				}
			} else {
				jQuery(ele).ajaxSubmit(ele.form_options);
			}
		});
		
		ele.reset = function(){
			$('#search-results').hide();
			$('body').unbind('click');			
		};
		
		ele.load = function(){
			window.location = $('ol li.hover a').attr('href');
		};
		ele.up = function(){
			if (ele.highlighted < 1) ele.highlighted = ele.ols;
			$('#search-results ol li.hover').removeClass('hover');
			$('#search-results ol li:eq('+(--ele.highlighted)+')', ele).addClass('hover');
		};
		ele.down = function(){
			if (ele.highlighted >= (ele.ols-1)) ele.highlighted = -1;
			$('#search-results ol li.hover').removeClass('hover');
			$('#search-results ol li:eq('+(++ele.highlighted)+')', ele).addClass('hover');
		};
	});
};

jQuery.fn.enable_photo_form_for_message = function() { 
	return this.each(function(){
		var ele = this;
		var parent = $('#id_body').get(0);
		var input = $('#id_photo.youtube-url', ele);
		var buttn = $('.btn', ele).get(0);
		$(buttn).click(function(){
			$(buttn).unbind();
			ele.submit();
			$(buttn).click(function() 
			{
				ele.submit();
			});
		});
		$(input).keypress(function(e){
			if (e.which == 13){
				ele.submit();
				return false;
			}
		});
		ele.submit = function()	{
			var data = {};
			data['Filedata'] = $(input).val();
			$.post('/messages/upload_temporary_photo_to_message/', data, function(newData, textStatus) {
				$(parent).after(newData['html']);
				$('.photo-attachment').hide();
				$('.attachment').removeClass('photo-active');
				$('.detach').click(function()
				{
					var par = $(this).parent().parent();
					$(par).fadeOut('normal', function() {
						$(par).remove();
					});
				});
				$(input).val('').blur();
			}, "json");
		};
	});
}

jQuery.fn.enable_youtube_form = function(callback){
	return this.each(function(){
		var ele = this;
		var parent = $('#wall_body').get(0);
		var input = $('.youtube-url', ele).get(0);
		var buttn = $('.btn', ele).get(0);
		$(input).defaultValue("Paste your URL or video ID here...");
		$(buttn).click(function(){
			$(buttn).unbind();
			ele.submit();
			$(buttn).click(function() {
				ele.submit();
			});
		});
		$(input).keypress(function(e){
			if (e.which == 13) {
				ele.submit();
				return false;
			}
		});
		ele.submit = function(){
			var data = {};
			data['url'] = $(input).val();
			$.post('/attach/youtube/', data, function(newData, textStatus){
				$('.attached-videos').append(newData['html']);
				$('.youtube-attachment').hide();
				$('.attachment').removeClass('youtube-active');								
				$('.detach').click(function(){
					var par = $(this).parent();
					$(par).fadeOut('normal', function(){
						$(par).remove();
					});
				});
				$(input).val('').blur();
				if ($('#id_body').hasClass('allow-insert-code') && newData['insert_code']) $('#id_body').val($('#id_body').val() + newData['insert_code']);
				if ($('#wall_body').val() == 'Speak your mind here...'){
					$('#wall_body').val('');
				}
				if (callback != undefined) callback(newData);
			}, "json");
		};
	});
};

function make_busy()
{
	var new_ele = $('.server-busy').html();
	$.blockUI({message:new_ele,css:{cursor:'normal'}});
	fix_stupid_blockui();
	$('.close-dialog').unblockeverything();
};

function make_sure_dialog_is_in_view()
{
	var dialog = $('.blockMsg').get(0);
	var pageoffset = $('body').scrollTop();
	var windowheight = $(window).height();
	var dialogoff = $(dialog).offset();
	var dialogheight = $(dialog).height();
	if (pageoffset > dialogoff.top) $('html, body').scrollTop((dialogoff.top/2)+dialogheight);
	if ((dialogoff.top+dialogheight) > (windowheight+pageoffset)) $('html, body').scrollTop((dialogoff.top/2)+dialogheight);
};

function fix_stupid_blockui()
{
	var height = $(window).height();
	var width = $(window).width();	
	var heightof = $('.blockMsg').height();
	var widthof = $('.blockMsg').width();
	$('.blockMsg').css('left', (width/2)-(widthof/2));
	$('.blockMsg').css('top', (height/2)-(heightof/2));	
};

