// Right now, dialogue.js and spinner.gif are in the same directory.
(function(){
	try{
		var s=document.getElementsByTagName('script');
		window.spinner_img_url=/(.*)dialogue\.js$/.exec(s[s.length-1].src)[1]+'spinner.gif';
	}catch(e){
		window.spinner_img_url=undefined;
	}
})();

function external_links($) {
    function clickfun() {
		window.open(this.href);
		return false;
    }
	$('a.external').click(clickfun);
}
jq(external_links);

function dialogue_js($) {
	$('#header').attr('labeledby','dhs');

	var opsuite_rating_lock = 0;
	var busy_spinner = {
		'on':(function(){
			var busy_src = window.spinner_img_url, ul;
			if (busy_src) {
				ul = jq("ul.star-rating");
				ul.before('<img alt="Changing rating in progress" '+
				         'id="add-rating-working" src="'+busy_src+'" />');
			}
		}),
		'off':(function(){jq('#add-rating-working').remove();})
	};
	function opsuite_rate_idea() {
		var url, data, form, stars=this.getAttribute("value");
		if (opsuite_rating_lock) return false;
		opsuite_rating_lock = 1; busy_spinner.on();
		form = jq('ul.star-rating').parent('form');
		jq('#add-rating-alert').remove();
		url = document.getElementsByTagName("base")[0].href+'/@@updateRating';
		data = {'category'     : 'opsuite_rating',
				'rating_class' : 'rate star-'+stars+' submitting'};
		jq.ajax({
			'url':url,
			'data':data,
			'type':'POST',
			'success':function(xml){
				// This innerHTML replace removes add-rating-alert & -working.
				document.getElementById('rating-stars-view-opsuite_rating').innerHTML = jq(xml).find("command[selector='.Rating#rating-stars-view-opsuite_rating'] param[name='html']")[0].firstChild.nodeValue;
				opsuite_bind_star_ratings();
				opsuite_rating_lock = 0;
			},
			'error':function(){
				form.prepend('<p class="portalMessage info" role="alert" id="add-rating-alert">There was a problem adding your rating.</p>');
				busy_spinner.off();
				opsuite_rating_lock = 0;
			},
			'dataType':'xml'
		});
		return false;
	}
	function opsuite_unrate_idea() {
		var url, data, form;
		if (opsuite_rating_lock) return false;
		opsuite_rating_lock = 1; busy_spinner.on();
		form = jq('ul.star-rating').parent('form');
		jq('#add-rating-alert').remove();
		url = document.getElementsByTagName("base")[0].href+'/@@deleteRating';
		data = {'category':'opsuite_rating'};
		jq.ajax({
			'url':url,
			'data':data,
			'type':'POST',
			'success':function(xml){
				// This innerHTML replace removes add-rating-alert & -working.
				document.getElementById('rating-stars-view-opsuite_rating').innerHTML = jq(xml).find("command[selector='.Rating#rating-stars-view-opsuite_rating'] param[name='html']")[0].firstChild.nodeValue;
				opsuite_bind_star_ratings();
				opsuite_rating_lock = 0;
			},
			'error':function(){
				form.prepend('<p class="portalMessage info" role="alert" id="add-rating-alert">There was a problem removing your rating.</p>');
				busy_spinner.off();
				opsuite_rating_lock = 0;
			},
			'dataType':'xml'
		});
		return false;
	}
	function opsuite_bind_star_ratings() {
		jq('ul.star-rating input').each(function(){
			var li = this.parentNode, newi, stars;
			stars = parseInt(this.getAttribute('value'));
			li.innerHTML='<input type="button" '+
				'style="width: '+(20*stars)+'%;'+
				'z-index: '+(6-stars)+';" />';
			newi = li.getElementsByTagName('input')[0];
			newi.setAttribute('title',this.getAttribute('title'));
			newi.setAttribute('class',this.getAttribute('class'));
			newi.setAttribute('value',this.getAttribute('value'));
			jq(newi).click(opsuite_rate_idea);
		});
		jq('input.DeleteRating').each(function(){
			var fs = this.parentNode, title, newi;
			title = this.getAttribute("title");
			fs.innerHTML = '<input type="button" class="DeleteRating" '+
				'value="Remove my rating" />';
			newi = fs.getElementsByTagName('input')[0];
			newi.setAttribute('title',title);
			jq(newi).click(opsuite_unrate_idea);
		});
	}
	jq(opsuite_bind_star_ratings);


	/* COMMENTS */

	$("#add-comment-form").bind("submit", function() { return false; }); // disable form submitting

	var submit = $('#add-comment-form .form-actions input'); // existing submit button
	var submit_value = submit.attr('value');

	submit.replaceWith('<input type="button" value="'+submit_value+'" class="add-comment"/>'); // replace submit with button

	var add_button = $('#add-comment-form .form-actions .add-comment');
	var comment_input = $('#add-comment-form textarea');

	/*
	function ToggleSubmit(){  // disable add button if no input in textarea
		if (!comment_input.val()){
			add_button.attr('disabled', 'disabled')
		} else {
			add_button.attr('disabled', '')
		}
	}

	ToggleSubmit() // set default state - browser may of prefilled content

	comment_input.bind('keyup', function(event){ // check whether there is content to submit
		ToggleSubmit()
	})
	*/
	var ideapath = $('base').attr('href');
	add_button.bind('click', function(event){
		event.preventDefault();
		if (comment_input.val()) {
			// Disable until request finishes.
			add_button.attr('disabled', 'disabled');
			add_button.attr('value','Submitting comment...');
			// Remove any existing alert message.
			jq('#add-comment-alert').remove();
			$.ajax({
				'type':'POST',
					'url':ideapath+'/++conversation++default/@@add-comment_ajax',
				'data':{
					'text':comment_input.val(),
					'____ajax':'ajax',
					'comment-submit':'submit'
				},
				'success': function(data,textStatus,xhr){
					// Add new comment in.
					$('#discussion-viewlet #add-comment-form').before(data);
					comment_input.val(''); // blank input
					$('#submit-idea a').focus(); // fix for ie8
					comment_input.focus(); //
					add_button.attr('disabled','');
					add_button.attr('value','Add comment');
				},
				'dataType':'html',
				'error': function(xhr,textStatus,errorThrown){
					// Add an alert message.
					jq('#add-comment-form').prepend('<p class="portalMessage info" role="alert" id="add-comment-alert">There was a problem adding your comment.</p>');
					add_button.attr('disabled','');
					add_button.attr('value','Add comment');
				}
			});
		} else {
			// please enter a comment
			// disable / enable submit button
		}
	});

	$('input.delete-comment').live('click', function(event){
		event.preventDefault();
		var comment = $(this).closest('div.comment');
		$(this).attr('disabled','disabled');
		comment.fadeTo(500, 0);
		var form = $(this).closest('form');
		function redisplay(data) {
			comment.stop();
			comment.replaceWith(data);
		}
		$.post(form.attr('action')+'_ajax',
		       form.serialize(),
		       redisplay);
	});
	/* END COMMENTS */

	$('#skip a').bind("click", function(event) {
		event.preventDefault();
		document.location.hash = $(this).attr('href').split('#')[1];
	});

	//AJAX updating of ideas counts
	if($("#idea-count").length > 0) //only on the home page
		var ideas_update = setInterval("updateIdeascounts()", 10000);

	//	*****	automatic checking of 'other' option when you enter text in 'if other please specify' boxes	*****
	var arr_inputs = [];
	arr_inputs['practice_area_other'] = ['#practice_area input[value=Other]','checked'];
	arr_inputs['population_represented_other'] = ['#population_represented input[value=Other]','checked'];
	arr_inputs['geographical_region_other'] = ['#geographical_region input[value=Other]','checked'];
	arr_inputs['org_type_other'] = ['#org_type option[value=Other]','selected'];
	arr_inputs['role_in_org_other'] = ['#role_in_org option[value=Other]','selected'];

	for(input in arr_inputs){
		$('#'+input).keyup(//when contents of the text <input> is changed
			function(){
				var this_id = $(this).attr('id');
				if($(this).val() != ''){//if some text has been entered in the 'please specify' box
					$(arr_inputs[this_id][0]).attr(arr_inputs[this_id][1], arr_inputs[this_id][1]);
				}
			}
		);
	}

	// shift key tracking
	var shiftKey = false; // default - not held down
	$(document).keyup(function(event){
		if (event.keyCode == 16) {
			shiftKey = false;
		}
	});

	$(document).keydown(function(event){
		if(event.keyCode == 16){ // shift key pressed
			shiftKey = true;
		}
	});
	// end
}
jQuery(dialogue_js);

function processIdeasCountsData(data){
	var arr_missions = data.split(',');
	for(key in arr_missions){
		var mission = arr_missions[key];
		var arr_path_and_number = mission.split(':');
		var path = arr_path_and_number[0];
		var number = arr_path_and_number[1];
		if(path == 'total'){ //special case for the total
			$('#idea-count .count').text(number);
			continue;
		}
		var mission_name = path.match(/[^\/]+(?=\/ideas)/); //e.g. get 'borders' from '/site/borders/ideas'
		var jquery_str = '#'+ mission_name +' .count';
		$(jquery_str).text(number);
	}
}

function updateIdeascounts(){
	$.get("get_ideas_count", {ajax:"1"}, processIdeasCountsData);
}

