/**
* Book of Odds - Social Functionality Javascript
* 
*
* Contain functions for AJAX and page setup for all social functionality.
**/

var boo = {
	user_id: '',
	num_lists: '',
	anonymous_user_id: '',
	username: '',
	pWidth: 300,
	pHeight: 300,
	deactivate: false
}

function booSetup (user_id, num_lists, username, anonymous_user_id) {
	boo.user_id = user_id;
	boo.num_lists = num_lists;
	boo.username = username;
	boo.anonymous_user_id = anonymous_user_id;
}

function booSetOdd(sentence,odds) {
	boo.odd_sentence=sentence;
	boo.odd_rounded=odds;
}
/* LIKE ME */
function ajaxLikeMe (contentobject_id) {
	if (boo.deactivate) { return false; }
	if ($('#like_button_'+contentobject_id).attr("status") != 'disabled') {
		$.ajax({
			type: "POST",
			url: '/like/toggle',
			data: { 
				user_id: boo.user_id,
				contentobject_id: contentobject_id
			},
			beforeSend: function() {
				$('#like_button_'+contentobject_id).addClass('active');
				$('#like_button_'+contentobject_id).attr("status","disabled");
			},
			success: function(data){
				if (data == 'access_denied') {
					window.location = '/user/login';
				} else {
					$('#like_button_'+contentobject_id).attr("status","enabled");
					if (data.split(',')[0] == true) {
						$('#like_button_'+contentobject_id).addClass('active');
						if ($('#like_count')) {
							$('#like_count').html(data.split(',')[1]);
						}
					} else {
						$('#like_button_'+contentobject_id).removeClass('active');
						if ($('#like_count')) {
							$('#like_count').html(data.split(',')[1]);
						}
					}
					// GA
					pageTracker._trackPageview('/OddsLikeMe');
				}
			}
		});
	}
}

function isLikeMe (contentobject_id) {
	if (boo.deactivate) { return false; }
	$.ajax({
		type: "POST",
		url: '/like/action',
		data: { 
			action: 'is_like_me',
			user_id: boo.user_id,
			contentobject_id: contentobject_id
		},
		beforeSend: function() {
			$('#like_button_'+contentobject_id).attr("status","disabled");
		},
		success: function(data){
			if (data == 'true') {
				$('#like_button_'+contentobject_id).addClass('active');
			} else {
				$('#like_button_'+contentobject_id).removeClass('active');
			}
			$('#like_button_'+contentobject_id).attr("status","enabled");
		}
	});
}

function isLikeMeList (contentobject_ids) {
	if (boo.deactivate) { return false; }
	$.ajax({
		type: "POST",
		url: '/like/action',
		data: { 
			action: 'is_like_me_list',
			user_id: boo.user_id,
			contentobject_ids: contentobject_ids.toString()
		},
		beforeSend: function() {
			contentobject_ids = jQuery(contentobject_ids);
			contentobject_ids.each(function() {
				$('#like_button_'+this).attr("status","disabled");
			});
		},
		success: function(data){
			likeMeIDs = jQuery(data.split(','));
			likeMeIDs.each(function() {
				$('#like_button_'+this).addClass('active');
			});
			contentobject_ids.each(function() {
				$('#like_button_'+this).attr("status","enabled");
			});
		}
	});
}

function numLikes (contentobject_id) {
	$.ajax({
		type: "POST",
		url: '/like/action',
		data: { 
			action: 'num_likes',
			contentobject_id: contentobject_id
		},
		success: function(data){
			$('#like_count').html(data);
		}
	});
}

/* INTERESTING */
function ajaxInteresting (contentobject_id,odd_sentence,odd_rounded) {
	if (boo.deactivate) { return false; }
	if ($('#interesting_button_'+contentobject_id).attr("status") != 'disabled') {
		$.ajax({
			type: "POST",
			url: '/interesting/toggle',
			data: { 
				user_id: boo.user_id,
				contentobject_id: contentobject_id,
				sentence: odd_sentence,
				odds_rounded: odd_rounded,
				redirect_uri: location.href
			},
			beforeSend: function() {
				$('#interesting_button_'+contentobject_id).addClass('active');
				$('#interesting_button_'+contentobject_id).attr("status","disabled");
			},
			success: function(data){
				if (data == 'access_denied') {
					window.location = '/user/login';
				} else {
					$('#interesting_button_'+contentobject_id).attr("status","enabled");
					if (data.split(',')[0] == true) {
						$('#interesting_button_'+contentobject_id).addClass('active');
						if ($('#interesting_count')) {
							$('#interesting_count').html(data.split(',')[1]);
						}
					} else {
						$('#interesting_button_'+contentobject_id).removeClass('active');
						if ($('#interesting_count')) {
							$('#interesting_count').html(data.split(',')[1]);
						}
					}
					// GA
					pageTracker._trackPageview('/InterestingOdds');
				}
			}
		});
	}
}

function isInteresting (contentobject_id) {
	if (boo.deactivate) { return false; }
	$.ajax({
		type: "POST",
		url: '/interesting/action',
		data: {
			action: 'is_interesting',
			user_id: boo.user_id,
			contentobject_id: contentobject_id
		},
		beforeSend: function() {
			$('#interesting_button_'+contentobject_id).attr("status","disabled");
		},
		success: function(data){
			if (data == 'true') {
				$('#interesting_button_'+contentobject_id).addClass('active');
			} else {
				$('#interesting_button_'+contentobject_id).removeClass('active');
			}
			$('#interesting_button_'+contentobject_id).attr("status","enabled");
		}
	});
}

function isInterestingList (contentobject_ids) {
	if (boo.deactivate) { return false; }
	$.ajax({
		type: "POST",
		url: '/interesting/action',
		data: { 
			action: 'is_interesting_list',
			user_id: boo.user_id,
			contentobject_ids: contentobject_ids.toString()
		},
		beforeSend: function() {
			contentobject_ids = jQuery(contentobject_ids);
			contentobject_ids.each(function() {
				$('#interesting_button_'+this).attr("status","disabled");
			});
		},
		success: function(data){
			interestingIDs = jQuery(data.split(','));
			interestingIDs.each(function() {
				$('#interesting_button_'+this).addClass('active');
			});
			contentobject_ids.each(function() {
				$('#interesting_button_'+this).attr("status","enabled");
			});
		}
	});
}

function numInterestings (contentobject_id) {
	$.ajax({
		type: "POST",
		url: '/interesting/action',
		data: { 
			action: 'num_interestings',
			contentobject_id: contentobject_id
		},
		success: function(data){
			$('#interesting_count').html(data);
		}
	});
}

/* SAVE */
function ajaxSave (contentobject_id) {
	if (boo.deactivate) { return false; }
	if ($('#save_button_'+contentobject_id).attr("status") != 'disabled') {
		$.ajax({
			type: "POST",
			url: '/save/toggle',
			data: { 
				user_id: boo.user_id,
				contentobject_id: contentobject_id
			},
			beforeSend: function() {
				$('#save_button_'+contentobject_id).addClass('active');
				$('#save_button_'+contentobject_id).attr("status","disabled");
			},
			success: function(data){
				if (data == 'access_denied') {
					window.location = '/user/login';
				} else {
					$('#save_button_'+contentobject_id).attr("status","enabled");
					if (data.split(',')[0] == true) {
						$('#save_button_'+contentobject_id).html('Unsave');
						if ($('#save_count')) {
							$('#save_count').html(data.split(',')[1]);
						}
					} else {
						$('#save_button_'+contentobject_id).html('Save');
						if ($('#save_count')) {
							$('#save_count').html(data.split(',')[1]);
						}
					}
					// GA
					pageTracker._trackPageview('/SaveArticle');
				}
			}
		});
	}
}

function isSaved (contentobject_id) {
	if (boo.deactivate) { return false; }
	$.ajax({
		type: "POST",
		url: '/save/action',
		data: { 
			action: 'is_saved',
			user_id: boo.user_id,
			contentobject_id: contentobject_id
		},
		beforeSend: function() {
			$('#save_button_'+contentobject_id).attr("status","disabled");
		},
		success: function(data){
			if (data == 'true') {
				$('#save_button_'+contentobject_id).html('Unsave');
			} else {
				$('#save_button_'+contentobject_id).html('Save');
			}
			$('#save_button_'+contentobject_id).attr("status","enabled");
		}
	});
}

function isSavedList (contentobject_ids) {
	if (boo.deactivate) { return false; }
	$.ajax({
		type: "POST",
		url: '/save/action',
		data: { 
			action: 'is_saved_list',
			user_id: boo.user_id,
			contentobject_ids: contentobject_ids.toString()
		},
		beforeSend: function() {
			contentobject_ids = jQuery(contentobject_ids);
			contentobject_ids.each(function() {
				$('#save_button_'+this).attr("status","disabled");
			});
		},
		success: function(data){
			savedIDs = jQuery(data.split(','));
			savedIDs.each(function() {
				$('#save_button_'+this).html('Unsave');
			});
			contentobject_ids.each(function() {
				$('#save_button_'+this).attr("status","enabled");
			});
		}
	});
}

function numSaves (contentobject_id) {
	$.ajax({
		type: "POST",
		url: '/save/action',
		data: { 
			action: 'num_saves',
			contentobject_id: contentobject_id
		},
		success: function(data){
			$('#save_count').html(data);
		}
	});
}

/* VIEW COUNT */
function numViews (node_id) {
	$.ajax({
		type: "POST",
		url: '/mostviewed/action',
		data: { 
			action: 'num_views',
			node_id: node_id
		},
		success: function(data){
			$('#view_count').html(data);
		}
	});
}

/* LISTS */
function ajaxWhiteboard (contentobject_id) {
	if (boo.deactivate) { return false; }
	url = '/lists/listitemaction?height=' + boo.pHeight + '&width=' + boo.pWidth + '&whiteboard=1&user_id=' + boo.user_id + '&contentobject_id=' + contentobject_id;
	tb_show('Add to White Board', url);
}

function ajaxExistingList (contentobject_id) {
	if (boo.deactivate) { return false; }
	url = '/lists/listitemaction?height=' + boo.pHeight + '&width=' + boo.pWidth + '&add_item=1&user_id=' + boo.user_id + '&contentobject_id=' + contentobject_id;
	// tb_show('Add to Existing List', url);
	tb_show('Add to Existing List', url);
	// GA
	pageTracker._trackPageview('/AddExistingStart');
}

function ajaxNewList (contentobject_id) {
	if (boo.deactivate) { return false; }
	url = '/lists/listitemaction?height=' + boo.pHeight + '&width=' + boo.pWidth + '&add_item_new_list=1&user_id=' + boo.user_id + '&contentobject_id=' + contentobject_id;
	tb_show('Add to New List', url);
	// GA
	pageTracker._trackPageview('/AddNewStart');
}

function createNewList (contentobject_id) {
	if (boo.deactivate) { return false; }
	url = '/lists/listaction?height=' + boo.pHeight + '&width=' + boo.pWidth + '&create_list=1&user_id=' + boo.user_id;
	tb_show('Create A List', url);
	// GA
	pageTracker._trackPageview('/NewListStart');
}

function ajaxEcard (node_id) {
	url = '/ecard/send?height=' + (boo.pHeight+170) + '&width=' + (boo.pWidth+140) + '&user_id=' + boo.user_id + '&node_id=' + node_id;
	tb_show('Send E-mail', url);
	// GA
	pageTracker._trackPageview('/SendStart');
}

function removeItemFromList (list_id, contentobject_id) {
	$.ajax({
		type: "POST",
		url: '/lists/listitemaction',
		data: { 
			remove_item: '1',
			list_id: list_id,
			contentobject_id: contentobject_id
		},
		success: function(data){
			$('#' + list_id + '-' + contentobject_id).slideUp(function() {
				$(this).remove();
				$(".list-full div.item:last").addClass('last');
			});
		}
	});	
}

function removeSelectedFromList (list_id) {
	if ($('.list-full .selector input:checked')) {
		var contentobject_ids = $('.list-full .selector input:checked').map(function() {
			return $(this).val();
		}).get().join(", ");
		$.ajax({
			type: "POST",
			url: '/lists/listitemaction',
			data: { 
				remove_items: '1',
				list_id: list_id,
				contentobject_ids: contentobject_ids
			}
		});
		$('.list-full .selector input:checked').each(function() {
			$('#' + list_id + '-' + $(this).val()).slideUp(function() {
				$(this).remove();
				$(".list-full div.item:last").addClass('last');
			});
		});
	}
}

function deleteList (list_id) {
	$.ajax({
		type: "POST",
		url: '/lists/listaction',
		data: { 
			delete_list: '1',
			list_id: list_id
		},
		success: function(data){
			window.location = '/My-Book-of-Odds/Lists';
			//$('#list-container-' + list_id).slideUp();
		}
	});	
}

function deleteListConfirm (list_id) {
	var answer = confirm("Are you sure you want to delete this list?")
	if (answer){
		deleteList(list_id);
	}
}

/* USER FUNCTIONS */
function ajaxCheckUsername() {
	if(!$('#username')) { return false; }
	$.ajax({
		type: "POST",
		url: '/userprofile/action',
		data: { 
			action: 'check_username',
			username: $('#input-username').attr('value')
		},
		success: function(data){
			if (data == 'true') {
				$('input#username-check').val('Not Available');
				$('input#username-check').addClass('fail');
			} else {
				$('input#username-check').val('Available');
				if ($('input#username-check').hasClass('fail')) {
					$('input#username-check').removeClass('fail');
				}
			}
		}
	});	
}

/* COMMENTS */
function reportAbuse(comment_id) {
	$.ajax({
		type: "POST",
		url: '/comment/flag',
		async: true,
		data: {
			user_id: boo.user_id,
			comment_id: comment_id,
			ezfp_form: 'report-abuse'
		},
		success: function(data){
			$('#flag-' + comment_id).html('flagged');
			$('#flag-' + comment_id).removeAttr('onclick');
		}
	});
}

function getUsername() {
	$.ajax({
		type: "POST",
		url: '/userprofile/profile',
		async: true,
		data: {
			get_user_attribute_value: 1,
			attribute: 'Login',
			user_id: boo.user_id
		},
		success: function(data){
			boo.username = data;
			$('#welcome-username').html(data);
		}
	});
}

/* USER PROFILES */
function profileQuestion() {
	$.ajax({
		type: "POST",
		url: '/userprofile/profile',
		data: { 
			profile_question: 1,
			user_id: boo.user_id
		},
		success: function(data){
			$('#questionaire-area').html(data);
		}
	});	
}

function loadSampleStatement(attr, val) {
	if ($('#sample-odds-statement').length) {
		$.ajax({
			type: "POST",
			url: '/userprofile/profile',
			data: { 
				sample_statement: 1,
				attribute: attr,
				value: val,
				user_id: boo.user_id
			},
			beforeSend: function() {
				$('#sample-odds-statement').show();
				$('#sample-odds-statement').html('<div class="loader"><img src="/design/site/images/loading_animation.gif" alt="Loading..."/></div>');
			},
			success: function(data) {
				if (data != '0') {
					$('#sample-odds-statement').html(data);
				} else {
					$('#sample-odds-statement').hide();
				}
			}
		});	
	}
}

function loadFiltersFromProfile() {
	$.ajax({
		type: "POST",
		url: '/userprofile/profile',
		dataType: "json",
		data: { 
			get_profile_data: 1,
			user_id: boo.user_id
		},
		success: function(data){
			filters = $.evalJSON(data);
			jQuery.each(filters, function(i, val) {
				if (val != '') {
					$('#filter-' + i + ' option').each(function () {
						if ($(this).attr('value').indexOf(':"' + val) > 0) {
							$(this).attr('selected', true);
						}
					});
				};
			});
		}
	});	
}

function checkLogin () {
	// Obscure links for non-logged in users
	if (boo.user_id == '' || boo.user_id == boo.anonymous_user_id) {
		boo.deactivate = true;
		
		$('a.logged-in').each(function(){
			
			if($(this).attr('href') != 'javascript:void(0);')
			{
				var redirect_url = $(this).attr('href');
			}
			else
			{
				var redirect_url = location.href;
			}
			if($(this).attr('onClick'))
			{
				var delayed_action = escape($(this).attr('onClick'));
			}

			$(this).removeAttr('onclick');
			$(this).attr('href', 'javascript:void(0);');
			$(this).unbind('click').click(function(){
				loginPopup(redirect_url , delayed_action);
			});

		});

		// Hide welcome
		$('#welcome-user').hide();
		$('#welcome-anonymous').show();
	} else {
		// Get username
		if (boo.username == '') {
			getUsername();
		}
		// Display welcome
		$('#welcome-anonymous').hide();
		$('#welcome-user').show();
	}
	// Show existing lists button if user has at least one list
	if (boo.num_lists > 0) {
		$('.button-existing-list').each(function(){
			$(this).removeClass('hide');
		});
	}
	// Show/hide comments form
	/*
	if ($('#comments-form').length) {
		if (boo.deactivate) {
			$('#comments-login').show();
			$('#comments-form').addClass('hide');
		} else {
			$('#comments-login').hide();
			$('#comments-form').removeClass('hide');
		}
	}
	*/
	// Show/hide comments captcha
        if ($('#comments-form').length) {
                if (boo.deactivate) {
                        $('#comments-form .captcha').show();
                } else {
                        $('#comments-form .captcha').remove();
                }
        }
	// Get polls for logged in users
	$('.poll').each(function(){
		if($(this).attr('id').length)
		{
			var id = $(this).attr('id').split('_')[1];
			var type = $(this).attr('type');
			var closed = $(this).attr('closed');
		
			if(!boo.deactivate || closed)
			{
				if($(this).attr('breakdown'))
				{
					var breakdown_id = $(this).attr('breakdown');
					var flip = $(this).attr('flip');
					getBreakdownPoll(id , breakdown_id , flip, closed);
				}				
				else
				{
					getPoll( id , type, closed);
				}
			}
			$(this).removeClass('hide');
		}
	});
}

function destroySession () {
	$.ajax({
		type: "POST",
		url: '/userprofile/action',
		async: true,
		data: {
			action: 'destroy_session'
		}
	});
}

/* ESP */
function espSubscribe(list_id, email, link) {
	$.ajax({
		type: "POST",
		url: '/esp/action',
		data: { 
			action: 'subscribe_ajax',
			list_id: list_id,
			email: email,
			user_id: boo.user_id
		},
		beforeSend: function() {
			$('#loader').show();
			$('#loader').html('<div class="loader"><img src="/design/site/images/loading_animation.gif" alt="Loading..."/></div>');
		},
		success: function(data){
			$('#loader').hide();
			$(link).parent().find('a.unsub').removeClass('hide');
			$(link).parent().find('a.sub').addClass('hide');
		}
	});
}

function espUnsubscribe(list_id, email, link) {
	$.ajax({
		type: "POST",
		url: '/esp/action',
		data: { 
			action: 'unsubscribe_ajax',
			list_id: list_id,
			email: email,
			user_id: boo.user_id
		},
		beforeSend: function() {
			$('#loader').show();
			$('#loader').html('<div class="loader"><img src="/design/site/images/loading_animation.gif" alt="Loading..."/></div>');
		},
		success: function(data){
			$('#loader').hide();
			$(link).parent().find('a.unsub').addClass('hide');
			$(link).parent().find('a.sub').removeClass('hide');
		}
	});
}

/* GENERAL FUNCTIONS */
function submitForm(url, formID, injectID, inject, disable) {
	if (typeof(inject) == 'undefined') { inject = true; }
	if (typeof(disable) == 'undefined') { disable = true; }
	if (disable) {
		if ($(formID).find('div.button input')) {
			$(formID).find('div.button input').attr('onclick','');
		}
	}
	$.post(url, $(formID).serialize(), function(data){
		if ($(injectID).hasClass('hide')) {
			$(injectID).show();
		}
		if (inject) {
			$(injectID).html(data);
		}
	});
}
/**
* Book of Odds - Social Functionality Javascript
* 
* Contain functions for AJAX and page setup for all social functionality.
**/

function changeMainItem(selected_element , iterator_id) {
	
	if( selected_element == undefined)
	{
		var current_selection = $('#side_section_' + iterator_id).children('.selected-item');
		if(current_selection != undefined)
		{			
			selected_element = current_selection.next('.iterator-item-small');
			
			if(selected_element.html() == null)
			{
				selected_element = $('#side_section_' + iterator_id).children('.iterator-item-small:first');
			}
		}
	}
	else
	{
		eval('clearInterval(window.iterator_interval_' + iterator_id + ');');
	}
	
	$('#side_section_' + iterator_id).children('.selected-item').removeClass('selected-item')
;
	var id = selected_element.attr("id").split('_')[2];
	selected_element.addClass('selected-item');
	$('#main_section_' + iterator_id).children('.main-iterator-content').hide();
	$('#iterator_' + iterator_id + '_main_' + id).show();

}

function getIteratorContent(iterator_id , offset, view_type) {
        $.ajax({                
		type: "POST",
                url: '/ajax/getIteratorContent',
                dataType: 'html',
                beforeSend: function() {
                        $('#main_section_' + iterator_id).html('<div class="loader"><img src="/design/site/images/loading_animation.gif" alt="Loading..."/></div>');
                },
                data: {
                        iterator_id: iterator_id ,
                        offset: offset,
			view_type: view_type

                },
                success: function(data){
                        $('#iterator_' + iterator_id).replaceWith(data);
			if(view_type != 'block')
			{
				changeMainItem($('#side_section_' + iterator_id).children('.iterator-item-small:first') , iterator_id);
			}

                }

	});
}


function loadInteractions(node_id , interaction_types) {
        if ($('.interaction-stream').length) {
                $.ajax({
                        type: "POST",
                        url: '/content/view/interactionstream/' + node_id,
                        beforeSend: function() {
                                $('.interaction-stream').html('<div class="loader"><img src="/design/site/images/loading_animation.gif" alt="Loading..."/></div>');
                        },
                        success: function(data){
                                $('.interaction-stream').html(data);
				updateStream();
				var interaction_timer = setTimeout("getInteractions('" + interaction_types + "', 'update' , 10);" , 10000);
                        }
                });
        }
}


function getInteractions(interaction_types , display_method , limit) {
        var time = 0;
	if(display_method =='update')
	{
		time = $('.interaction-item:first').attr('time');
	}
	$.ajax({                
		type: "POST",
                url: '/interactionstream/getInteractions',
                dataType: 'html',
                data: {
                        interaction_types: interaction_types,
			limit: limit,
			time: time 

                },
                success: function(data){
			if(display_method == 'full')
			{
				$('.interaction-stream').html(data);
				$('.interaction-stream').children('.hide').show();
				$('.interaction-stream').children('.hide').removeClass('hide');
				updateStream();
			}
			else
			{
	                        $('.interaction-stream').prepend(data);
			}

			var interaction_timer = setTimeout("getInteractions('" + interaction_types + "', 'update' , 10);" , 5000);
                }

	});
}

function updateStream(){
	var next_interaction = $('.interaction-stream').children('.hide:last');
	next_interaction.css( {height:0});
	next_interaction.animate( { height : 50} , {duration: 2000})
	next_interaction.removeClass('hide');
	var nextUpdate = setTimeout('updateStream();' , Math.random()*3000 + 2000);


}

function changeIterator(collection_id){
	var id = $('#iterator_' + collection_id + '_select').val();
	getIteratorContent(id, 0, 'callout');
	$('#collection_' + collection_id).children('.content-iterator-callout').addClass('hide');
	$('#iterator_' + id).removeClass('hide');

}

function ajaxLogin(){
        $.ajax({
                type: "POST",
                url: '/userprofile/login',
                dataType: 'html',
                data: {
                        UserLogin:  $('#id1').val(),
			UserPassword: $('#id2').val(),
			DelayedAction: $('#action').val(), 
			RedirectURL: $('#redirect').val()

                },
                success: function(data){
			$('#TB_ajaxContent').html(data);
                }

        });
}

function ajaxRegister(){
        $.ajax({
                type: "POST",
                url: '/userprofile/register',
                dataType: 'html',
		beforeSend: function() {
                        $('#TB_ajaxContent').html('<div class="loader"><img src="/design/site/images/loading_animation.gif" alt="Loading..."/></div>');
                },
                data: {
			action: 'register',
			ezfp_form: 'register',
			ezfp_to_address: 'registration@bookofodds.com',
			ezfp_from_address: 'registration@bookofodds.com',
			ezfp_email_subject: 'BookOfOdds.com New User Registration',
			ajax: 1,
                        first_name:  $('#first_name').val(),
			last_name: $('#last_name').val(),
			username: $('#input-username').val(), 
			email: $('#email').val(),
			email_verify: $('#email_verify').val(),
			password: $('#password').val(),
			password_verify: $('#password_verify').val(),
			age_verify: $('#age_verify').val(),
			opt_in: $('#opt_in').val(),
			opt_in_list: $('#opt_in_list').val(),
                        DelayedAction: $('#action').val(),
                        RedirectURL: $('#redirect').val()

                },
                success: function(data){
			$('#TB_ajaxContent').html(data);
                }

        });
}
function loginPopup(redirect_url , delayed_action){
	url = '/userprofile/popup?action=login' + '&height=' + boo.pHeight + '&width=' + boo.pWidth ;
	if(redirect_url)
	{
		url = url + '&redirectURL=' + escape(redirect_url) ;
	}	
	if(delayed_action)
	{
		url = url + '&delayedAction=' + delayed_action;
	}
	tb_show('Login', url);

}

function forgotPassword(){
	url = '/userprofile/forgotpassword?height=300&width=300';
        tb_show('Forgot Password', url);
}

function showRegistration(redirect_url , delayed_action){
	url = '/userprofile/popup?action=register&height=500&width=500&ajax=true&redirectURL=' + redirect_url + '&delayedAction=' + delayed_action;
        tb_show('Register', url);
}



function getPoll(poll_id , view_type, closed){
	$.ajax({
                type: "POST",
                url: '/Polls/poll',
                dataType: 'html',
                beforeSend: function() {
                        $('#poll_' + poll_id).html('<div class="loader"><img src="/design/site/images/loading_animation.gif" alt="Loading..."/></div>');
		},
                data: {
			action: 'get_poll',
                        poll_id: poll_id ,
			view_type: view_type,
			closed: closed

                },
                success: function(data){
                	$('#poll_' + poll_id).html(data);
		}
	});
}

function getBreakdownPoll(poll_id , breakdown_id , flip, closed){
	$.ajax({
                type: "POST",
                url: '/Polls/poll',
                dataType: 'html',
                beforeSend: function() {
                        $('#poll_' + poll_id).html('<div class="loader"><img src="/design/site/images/loading_animation.gif" alt="Loading..."/></div>');
		},
                data: {
			action: 'get_breakdown_poll',
                        poll_id: poll_id ,
			breakdown_id: breakdown_id,
			flip: flip,
			closed: closed

                },
                success: function(data){
                	$('#poll_' + poll_id).html(data);
		}
	});
}

function submitPoll(poll_id , drop_down , view_type){
	if(!drop_down)
	{
		var selected_item = $("input[name='poll_value']:checked");
	}
	else
	{
		var selected_item = $("select[name='poll_value'] option:selected");
	}

	if(selected_item.val())
	{
		$.ajax({
	                type: "POST",
	                url: '/Polls/submit',
	                dataType: 'html',
	                beforeSend: function() {
	                                $('#poll_' + poll_id).html('<div class="loader"><img src="/design/site/images/loading_animation.gif" alt="Loading..."/></div>');
	                },
	                data: {
				action: 'submit_vote',
	                        poll_id: poll_id,
				poll_value : selected_item.val(),
				view_type: view_type
	
	                },
	                success: function(data){
	                	$('#poll_' + poll_id).html(data);
				pageTracker._trackPageview('/AnswerPoll');
			}
		});
	}
	else
        {
                $('#errors').html('Please select an option.');
        }
}
function removeReponse(poll_id){
	$.ajax({
                type: "POST",
                url: '/Polls/remove',
                dataType: 'html',
                data: {
			action: 'remove_response',
                        poll_id: poll_id
                }
	});
}
function submitBreakdownPoll(breakdownpoll_id , poll_id , drop_down){
        if(!drop_down)
        {
                var selected_item = $("input[name='poll_value']:checked");
        }
        else
        {
                var selected_item = $("select[name='poll_value'] option:selected");
        }

        $.ajax({
                type: "POST",
                url: '/Polls/submit',
                dataType: 'html',
                beforeSend: function() {
                                $('#poll_' + breakdownpoll_id).html('<div class="loader"><img src="/design/site/images/loading_animation.gif" alt="Loading..."/></div>');
                },
                data: {
                        action: 'submit_vote',
                        poll_id: breakdownpoll_id,
                        poll_value : selected_item.val()

                },
                success: function(data){
                      	getBreakdownPoll(poll_id , breakdownpoll_id , 'false');
			pageTracker._trackPageview('/AnswerPoll');

                }
        });
}



function flagPoll(poll_id){
        $.ajax({
                type: "POST",
                url: '/Polls/flag',
                dataType: 'html',
                data: {
                        action: 'flag_poll',
                        poll_id: poll_id 

                },
                success: function(data){
			$('#report_abuse').html('This poll has been marked for review.');
                }
        });
}

function addPollOption(template){
	var id = $('#' + template + '_options').children('.poll-option').size() + 1;

	$('<div class="poll-option">'+id+'. <input id="option_'+template + '_' +id+'" onchange="createOS_'+template+'($(this));" name="option[]" class="poll-option" type="text"/> <input id="os_'+template + '_' +id+'" name="os[]" class="poll-os" type="text"/></div>').appendTo('#' + template + '_options');
}

function cycle(iterator_id) {
	eval('var iterator_interval_' + iterator_id  + '  = setInterval("changeMainItem(null , " + iterator_id + ");" , 5000);');	
	
}

function changePollTemplate()
{
	$('.poll-template').addClass('hide');
	$('#'+$('#template-selection').val()).removeClass('hide');
}

function validatePoll()
{
	var valid = false;
	if(!$("input[name='drop_down']").val())
        {
                var selected_item = $("input[name='poll_value']:checked");
        }
        else
        {
                var selected_item = $("select[name='poll_value'] option:selected");
        }
	if(selected_item.val())
	{
		valid = true;
		pageTracker._trackPageview('/AnswerPoll');
	}
	else
	{
		$('#errors').html('Please select an option.');
	}

	return valid;

}

function getLatestDiscussions(forum_node_id , tags){
        $.ajax({
                type: "POST",
                url: '/forum/list',
                data: {
                        forum_node_id: forum_node_id,
			tags: tags

                },
                success: function(data){
                        $('#forum_' + forum_node_id + '_content').html(data);
                }
        });
}

