var submitForm = function () {
	var save_and_close_id = this.id;
	var popup_id = save_and_close_id.substring("popup_closebox_".length);
	var form_id = "form_" + popup_id;
	var form = document.getElementById(form_id);
	var url = '/ratings/set_rating/';
	var article_rating = true;
	if (form.primaryRating) {
		// Get selected primary rating
		var primaryRating = "";
		var primaryRatingChecked = false;
		for (var i = 0; i < form.primaryRating.length ; i++) {
			if (form.primaryRating[i].checked) {
				primaryRating = form.primaryRating[i].value;
				primaryRatingChecked = true;
			}
		}
	}
	else {
		var primaryRating = 1; // Set the primary rating to 1, mainly used for rating pubco's as they don't have a primary rating
		primaryRatingChecked = true; // Set it to checked for validation purposes as it is not required to be checked
		article_rating = false;
		url = '/ratings/set_recommendation/';
	}
	// Check if the form included the secondary ratings
	if (form.secondaryRating) {
		// Get selected secondary rating(s)
		var secondaryRating = "";
		var secondaryRatingChecked = false;
		for (var i = 0; i < form.secondaryRating.length ; i++) {
			if (form.secondaryRating[i].checked) {
				secondaryRating += form.secondaryRating[i].value + ",";
				secondaryRatingChecked = true;
			}
		}
		// Remove trailing comma from comma seperated secondaryRating list
		secondaryRating = (secondaryRating.charAt(secondaryRating.length - 1) === ',') ? secondaryRating.substring(0,secondaryRating.length - 1) : secondaryRating;
		if (!primaryRatingChecked || !secondaryRatingChecked) {
		}
	} else {
		var secondaryRating = '0';	
	}
	//if (primaryRatingChecked && secondaryRatingChecked) 
	if (primaryRatingChecked) {
		var url = encodeURI(url + form.company_id.value + '/' + form.table_name.value + '/' + form.table_id.value + '/' + primaryRating + '/' + secondaryRating + '/' + form.comments.value);
		
		new Ajax.Request(url, {
			onSuccess: function(transport) {
				if (transport.responseText !== 'false') {
					if (article_rating) {
						Event.stopObserving(form.rate_button_id.value, 'click');
						var getRatingUrl='/news_item/get_rating/'+form.table_id.value;
							new Ajax.Request(getRatingUrl,{ method: 'get',
										 onSuccess: function(transport){
											 response=transport.responseText.evalJSON();
											 the_current_rating = parseFloat(response.jsonRatingInfo.current_rating);
											   if(the_current_rating == 0) {
													rating_bg = ' grey';
												}
												
												else if ((the_current_rating > 0) && (Math.abs(the_current_rating) <= 50)) {
													rating_bg = ' lowgreen';
												}
												
												else if ((the_current_rating > 0) && (Math.abs(the_current_rating) > 50)) {
													rating_bg = ' highgreen';
												}
												
												else if ((the_current_rating < 0) && (Math.abs(the_current_rating) <= 50)) {
													rating_bg = ' lowred';
												}
												
												else if ((the_current_rating < 0) && (Math.abs(the_current_rating) > 50)) { 
													rating_bg = ' highred';
												}
												else {
													rating_bg = ' grey';	
												}
												
												if(response.jsonRatingInfo.example_rating) {
                        							other_ratings = '<a href="/related_ratings/view_rating/'+response.jsonRatingInfo.example_rating+'">Ratings</a>';
												}
                    							else {
                    							    other_ratings = 'Ratings';
                    							}
												var rHTML='<div class="news_article_rating'+rating_bg+'" id="ncurrating">';
												
												if(response.jsonRatingInfo.current_rating == 'N/A') {
													rHTML=rHTML+'<div class="current_rating_percentage'+rating_bg+'" id="currentrating">N/A</div>';
												}
												else {
													rHTML=rHTML+'<div class="current_rating_percentage'+rating_bg+'" id="currentrating">'+Math.round(the_current_rating)+'%</div>';
												}
												
                            					
                            					rHTML=rHTML+'<div class="number_ratings" id="numrating"><b>'+response.jsonRatingInfo.num_ratings+'</b><br/>'+other_ratings+'</div>';
												rHTML=rHTML+'<div class="rate_here"><div id="rated">Rated</div></div></div>';
												$('rinfo').innerHTML=rHTML;
											 //$('ncurrating').setAttribute('class','news_article_rating'+rating_bg);
											// $('currentrating').setAttribute('class','current_rating_percentage'+rating_bg);
											// $('currentrating').innerHTML=response.jsonRatingInfo.current_rating+'% '; 
											 //$('numrating').innerHTML='<b>'+response.jsonRatingInfo.num_ratings+'</b>'+'<br>Ratings'; 
											 }
										 }
										 );
					} else {
						var removeRecommendationId = 'remove_recommendation_' + popup_id;					
						//document.getElementById(form.rate_button_id.value).innerHTML = '<a class="grey-btn">End Recommendation</a>';
						Event.stopObserving("rating_trigger", 'click');
						
						
						var n = document.getElementById("rating_trigger").childNodes[0];
						n.parentNode.removeChild(n);						
						var newA = document.createElement('a');						
						newA.setAttribute('class','grey-btn');
						newA.setAttribute('className','grey-btn');		
						newA.onclick = new Function("removeRecommendation('" + transport.responseText + "')");
						newA.innerHTML = 'End Recommendation';		
											
						document.getElementById(form.rate_button_id.value).appendChild(newA);
						// Check if the 'remove recommendation' link is already there
						/*if (!document.getElementById(removeRecommendationId))
						{					
							var spanTag = document.createElement('a');
							spanTag.className = 'remove_recommendation';				
							spanTag.id = removeRecommendationId;
							spanTag.innerHTML = 'Remove Recommendation';
							form.appendChild(spanTag);
							//Event.observe(removeRecommendationId, "click", removeRecommendation);
						}*/
					}
					// Update the rating id 
					if (transport.responseText != 0) {
						form.rating_id.value = transport.responseText;	
					}
				}
				else {
					alert('We\'re sorry.  There was an error.\nYour rating was not saved.  Please try again later.');					
				}
			},
			onFailure: function(transport) {
				alert('We\'re sorry.  There was an error.\nYour rating was not saved.  Please try again later.');
			}
		}); 			
	}
};

var removeRecommendation = function (rating_id) {
	var url = encodeURI('/ratings/remove_recommendation/' + rating_id);
		new Ajax.Request(url, {
			onSuccess: function(transport) {
				var n = document.getElementById("rating_trigger").childNodes[0];
				n.parentNode.removeChild(n);
				var newA = document.createElement('a');
				newA.setAttribute('class','grey-btn');
				newA.setAttribute('className','grey-btn');				
				newA.innerHTML = 'Recommend';

				Event.stopObserving("rating_trigger", 'click');
				document.getElementById("rating_trigger").onclick = "";
				
				new Popup("popup_container","rating_trigger",{position:"below",trigger:"click"});
				Event.observe("popup_closebox_popup_container", "click", submitForm);
				
				document.getElementById("rating_trigger").appendChild(newA);
				//document.getElementById(form.rate_button_id.value).innerHTML = "<a class='grey-btn'>Recommend</a>";
				/*var recommendationLink = document.getElementById(remove_recommendation_id);
				form.removeChild(recommendationLink);*/
			},
			onFailure: function(transport) {
				alert('We\'re sorry.  There was an error.\nYour recommendation was not deleted.  Please try again later.');
			}
		}); 		
};
