// Forums namespace    
$.scforums = {};
$.scforums.history = [];
$.scforums.id = '';
$.scforums.num = '';
$.scforums.thread = '';
$.scforums.action = '';
$.scforums.lang = '';

$(document).ready(function(){
   
    jQuery.fn.log = function (msg) {
		console.log("%s: %o", msg, this);
		return this;
	};
	
	$("div.rating span.detailed").each(function(){
		$(this).hide();
		$(this).css('visibility', 'visible');
    });

	$('body').click(function(e) {
		var $target = $(e.target);
		
		// Click on ajax links
		if ($target.parent().hasClass('ajax')) {
			e.preventDefault();

			var url = $target.parent().attr('href');
			var path = url.substring(0, url.indexOf('?'));
			var postData = url.substring(url.indexOf('?')+1);

			$.scforums.id = $target.parent().parent().attr('id');
			$.scforums.action = url.match(/action=([^&]+)/)[1];
			$.scforums.num = url.match(/num=([^&]+)/)[1];
			$.scforums.thread = url.match(/thread=([^&]+)/)[1];
			$.scforums.lang = path.match(/^\/([^\/]+)\//)[1];
						
			$.ajax({
				type: "POST",
				url: path,
				data: postData,
				success: showResponse,
				dataType: 'json'
			});

		}



		// Click on hide/show for messages below the treshold
		if ($target.parent().hasClass('below_treshold') && 
			$target.parent().is('span') && 
			! $target.hasClass('author')) {

			e.preventDefault();
			// alert('is A in below_treshold');
			$target.parent().parent().toggleClass('below_treshold');
			if ($target.text()=='Покажи') {
				$target.text('Сакриј');
				$target.prev('span.author').hide();
			} else if ($target.text()=='Pokaži') {
				$target.text('Sakrij');
				$target.prev('span.author').hide();
			} else if ($target.text()=='Show') {
				$target.text('Hide');
				$target.prev('span.author').hide();
			} else if ($target.text()=='Сакриј') {
				$target.text('Покажи');
				$target.prev('span.author').show();
			} else if ($target.text()=='Sakrij') {
				$target.text('Pokaži');
				$target.prev('span.author').show();
			} else if ($target.text()=='Hide') {
				$target.text('Show');
				$target.prev('span.author').show();
			}
			
			if ($target.hasClass('disabled')) {
				alert('disabled');
			}
		}

		// Click on sum of +/- votes
		if ($target.parent().hasClass('sum')) {
			e.preventDefault();
			$("div.rating span.detailed").each(function(){
				$(this).show();
			});

			$("div.rating span.sum").each(function(){
				$(this).hide();
			});
		}

		// Click on +/- votes
		if ($target.parent().hasClass('detailed')) {
			e.preventDefault();
			$("div.rating span.detailed").each(function(){
				$(this).hide();
			});

			$("div.rating span.sum").each(function(){
				$(this).show();
			});
		}
		
	});
});

// Function toggles links on hidden buttons
function toggle_link(target) {
}
 
// post-submit callback 
function showResponse(responseText, statusText)  { 
    // for normal html responses, the first argument to the success callback 
    // is the XMLHttpRequest object's responseText property 
 
    // if the ajaxForm method was passed an Options Object with the dataType 
    // property set to 'xml' then the first argument to the success callback 
    // is the XMLHttpRequest object's responseXML property 
 
    // if the ajaxForm method was passed an Options Object with the dataType 
    // property set to 'json' then the first argument to the success callback 
    // is the json data object returned by the server 

	// If voting was really successful and inserted into DB
	
	if (responseText.status) {
		message_insert(responseText.message);
		update_rating();
	} else {
		if (responseText.message == 'cant_vote_for_yourself') {
			message(responseText.additional.translation);
		}

		if (responseText.message == 'bad_name') {
			message(responseText.additional.translation);
		}

		if (responseText.message == 'bad_host') {
			message(responseText.additional.translation);
		}

		if (responseText.additional.error == 'already_voted') {
			message(responseText.message);
		}

		if (responseText.message == 'too_many_votes') {
			message(responseText.additional.translation);
		}

		if (responseText.additional.error == 'invalid_login') {
			ajax_login_form({userid: responseText.additional.userid});
		}

	}
} 


function message_insert(text) {
	$('div#' + $.scforums.id).append('<span>' + text + '</span>');
	$('div#' + $.scforums.id + ' a img').hide();
}

function update_rating() {
	var rating = $('#' + $.scforums.id + ' span.detailed a').html().match(/\+([\d]+) \/ -([\d]+)/i );
	if ($.scforums.action == 'up') {
		rating[1]++;
	} else {
		rating[2]++;
	}
	
	var new_rating = '+' + rating[1] + ' / -' + rating[2];
	var new_sum = rating[1] - rating[2];
	if (new_sum > 0) {
		new_sum = '+' + new_sum;
	}
	
	$('#' + $.scforums.id + ' span.detailed a').html(new_rating);
	$('#' + $.scforums.id + ' span.sum a').html(new_sum);

	// <span class='detailed'><a href='#'> +$thumbs_up / -$thumbs_down</a></span>
	//			<span class='sum'><a href='#'>$summed_rating_print</a></span>
//	var result = $(this).html().match(/\+([\d]+) \/ -([\d]+)/i );

}

function message(text) {
	var dialogOptions = {
		autoOpen: false,
		width: 300,
		buttons: {
			'OK': function() {
				$(this).dialog('destroy'); 
			}
		}
	}

// alert($("<div id='message_dialog'>").length);

//	if ($("<div id='message_dialog'>").length > 0) {
		$("#message_dialog").dialog('close');
		$("#message_dialog").dialog('delete');
		$("#message_dialog").remove();
//	}
	$("<div id='message_dialog'></div>").appendTo('body');
	$("#message_dialog").css('visibility', 'visible');
	$("#message_dialog").html(text);
	$("#message_dialog").dialog(dialogOptions).dialog('open');
}

function test(msg) {
	alert(msg);
	return true;
}

function ajax_vote(options) {
	var defaults = {
		message:	'',
		userid:		'',
		title:		''
	}
		
	var opts = $.extend(defaults, options);
	var ret_value = false;
	
	var value = $('#myFormId :password').fieldValue(); 

	$.ajax({
		type: "POST",
		url: "/" + $.scforums.lang + "/diskusije/new/vote.php",
//		data: "id=" + $.scforums.id + "&num=" + $.url.param("num") + "&thread=" + $.url.param("thread") + "&action=" + $.scforums.action,
		data: "id=" + $.scforums.id + "&num=" + $.scforums.num + "&thread=" + $.scforums.thread + "&action=" + $.scforums.action,
		dataType: 'json',
		timeout: 3000,
//		async: false,
		success: function(msg){
			if (msg.status) {
				message_insert( msg.message );
				update_rating();
				ret_value = true;
			} else {
				if (msg.message == 'cant_vote_for_yourself') {
					message(msg.additional.translation);
					return false;
				}
				if (msg.message == 'bad_name') {
					message(msg.additional.translation);
					return false;
				}
				if (msg.message == 'bad_host') {
					message(msg.additional.translation);
					return false;
				}
				if (msg.additional.error == 'already_voted') {
					message(msg.message);
					return false;
				}
				if (msg.message == 'too_many_votes') {
					message(msg.additional.translation);
					return false;
				}
				if (msg.additional.userid) {
					var $userid = msg.additional.userid;
				} else {
					var userid = '';
				}

				ajax_login_form(opts);

				ret_value = false;
			}
		}
	});
	
	return ret_value;
}

// Loads a login page into a dialog
function ajax_login_form(opts) {


	// Set default parameters
	var opts = $.extend({
		message:	'',
		userid:		''
	}, opts);

	var dialogOptions = {
		autoOpen: false,
		width: 300,
		title: opts.title
	}
	
//	$.ajaxSetup({'async': 'false'});
	
	$("<div id='login_form_dialog'></div>").appendTo('body');
	$("#login_form_dialog").css('visibility', 'visible');

	$.ajax({
		type: "POST",
		url: "/" + $.scforums.lang + "/diskusije/new/views/login.php",
//		data: {err_message: opts.message, userid: opts.userid},
		data: 'err_message=' + opts.message + '&userid=' + opts.userid,
		success: function(msg) {
			$("#login_form_dialog").html(msg);

			var options = { 
				target:        '#output1',   // target element(s) to be updated with server response 
				beforeSubmit: function() {
					$("#login_form_dialog").dialog(dialogOptions).dialog('remove');
				},
				success: function(responseText, statusText) {
					if (responseText.status == true) {
						$("#login_form_dialog").dialog(dialogOptions).dialog('close');
						ajax_vote();
					} else {
						opts.message = responseText.message;
						opts.userid = responseText.additional.userid;
						ajax_login_form(opts);
					}
				},
				dataType: 'json'
			};
		
			$('#login_form').ajaxForm(options);

		}
	});

	$("#login_form_dialog").dialog(dialogOptions).dialog('open');
		

}

$("span.rating").each(function(){
	var result = $(this).html().match(/\+([\d]+) \/ -([\d]+)/i );
});