String.prototype.trim = function(){return
(this.replace(/^[\s\xA0]+/, "").replace(/[\s\xA0]+$/, ""))}

String.prototype.startsWith = function(str)
{return (this.match("^"+str)==str)}

String.prototype.endsWith = function(str)
{return (this.match(str+"$")==str)}


/*
 * Initialize the all elements
 * @return nothing
 */
function fivestar_initialize(){

	//Get all div witch id starts with "stars_" -> starify it
	$("div[id^='stars_']").each(function(i) {		
		starify(this.id);
	});
}

/*
 * Convert the given div (it's id) into fivestar area.
 * CONVENTIONS : 
 * 		* The caption span element is id+'_cap'
 * 		* If an id end with 'disabled' then the voting system must be disabled
 * @param id the id of the div
 * @return nothing
 */
function starify(id){
	
	var elementToStarifed = $('#'+id);
	
	if(id.endsWith('_disabled')){
		//transform the div into stars pictures
		elementToStarifed.stars({
		    inputType: "select",
		    disabled: true
		});
	}else{
		//transform the div into stars pictures
		elementToStarifed.stars({
		    inputType: "select",
		    captionEl: $('#'+id+'_cap'),
		    oneVoteOnly: true,
		    cancelShow: false,
		    callback: function(ui, type, value){return commitRate(ui, type, value,id);	}
		});
	}		
}

/*
 * The call back function when commit rate
 * @param ui the 
 * @param type the type of element
 * @param value the value of the element
 * @param id the id element that submit 
 * @return nothing
 */
function  commitRate(ui, type, value, id){
	//alert('ui = '+ui.id+'\ntype = '+type+'\nvalue = '+value+'\nPostURl = '+getPostURL()+'\nid = '+id);
		
	//ajax request to update the mark of the current user
	$.get(getPostURL(), //the post URL
		  { type: 'mark', mark_value: value, content_id: getDocumentUUID(),user_id:getUserID() }, //the list of parameters
		  function (data, textStatus) {
				
		  		if(textStatus == 'success'){
		  		    //alert("textStatus: " + textStatus);
		  			treatResultOfMarkPost(data,id)}
		  		else {
		  			displayNotPostMarkErrorMessage();
		  		}
			},
		'text' //the type of data that will be returned
	);

}	

/*
 * Use the xml file to update the display (vote + number of hits)
 * @param xml the return data
 * @return nothing
 */
function treatResultOfMarkPost(xml,star_id){
	//alert("Data Loaded: " + xml);
	$('#fivestar_ajax_callback_data').html(xml);
	
	//Treat average
	$('#fivestar_ajax_callback_data').find('root').each(function(){
			updateAverage($(this).attr('average'),star_id);
    });
	
	//Treat nbrvote
	$('#fivestar_ajax_callback_data').find('root').each(function(){
		updateNbrVotes($(this).attr('nbrvotes'),star_id);
    });
}

/*
 * Update the display of the average
 * @param value
 * @return
 */
function updateAverage(value,star_id){
	 $('#'+star_id).stars('selectID', value-1);
}

/*
 * Update the nbr of votes
 * @param value
 * @return
 */
function updateNbrVotes(value,star_id){
	$('#'+star_id+'_span_nbrVotes')[0].innerHTML = value+'';
	try{
		$('#'+star_id+'_userMessageForVote')[0].innerHTML = getMessageWhenHasVote();
	}catch(err){
		
	}
}

 
/* ************************************************************************* */
/*                       Form method                                         */
/* ************************************************************************* */ 

var cancelInput = true;//indicate if the user close the windows with a submit or with a cancel
var allParams = null;//the list of params to send with form content
var commentCommitURL = null;//the post url for comment
var allParamsKey = null;//the list of all name of parameters
 
function setNyromodalCancel(){
	cancelInput = true;
}

function setNyromodalSubmit(){
	cancelInput = false;
	validateForm();
}

/*
 * Set the right properties for the popin
 * @return nothing
 */
function setPopinSettings(){
	
	//set setting for popin
	$(function() {
		
		  $.fn.nyroModal.settings.beforeHideContent = function(elts, settings, callback) {
		 
			 //Collect form params/values and store it in global variable
		    var form = $("form[id='commentForm']")[0];
		    commentCommitURL = form.action;
		    allParams = collectAllParams();			    
		    
		    //always to it to perform end of treatment
		    callback();
		  };

		
		  $.fn.nyroModal.settings.endRemove = function(elts, settings) {
			    
			    //alert('endLoadding - cancelInput = '+cancelInput);
			   // alert('params = '+allParams);
			   // alert('url = '+commentCommitURL);

			    //submit the form (ajax request with collected parameters
			    if(!cancelInput){
			    	sendAjaxCommentRequest(allParams,commentCommitURL);
			    }
			  };
	
	});
	
	try{
		var height = getModalHeight();
		var width = getModalWidth();
		
		//set setting for popin
		$(function() {
			 //set nyromodal adapt size to content
			  $.fn.nyroModal.settings.autoSizable=false;
			  
			  //set nyromodal unresizable
			  $.fn.nyroModal.settings.resizable=false;
			  
			  //set nyromdal size
			  $.fn.nyroModal.settings.width=width;
			  
			  //set nyromdal size
			  $.fn.nyroModal.settings.height=height;
		});
	}catch(exception){
		
		//set setting for popin
		$(function() {
			  //set nyromodal adapt size to content
			  $.fn.nyroModal.settings.autoSizable=true;
		});
		
	}
	
		
}
	
 
/*
 * Collect all input of the page (the form and the other of the page)
 * WARNING : Currently collect only input of type 'text', 'password' and 'hidden'; and texterea
 * @return an map containing all input values indexed on it's field name
 */
function collectAllParams(){
	 var params = {}; 
	 
	var nbrParams = 0;
	allParamsKey = new Array();
	$("input").each(function(i) {		
		if(this.type != null &&  this.name != null){
			if(this.type == 'text' || this.type == 'password' || this.type == 'hidden'){
				params[this.name] = this.value;
				allParamsKey[nbrParams] = this.name;
				nbrParams++;
			}
		}
			
	});

	$("textarea").each(function(i) {		
		if(this.name != null){
			params[this.name] = this.value;
			allParamsKey[nbrParams] = this.name;
			nbrParams++;
		}
			
	});

	return params;
}

/*
* Post the request of new comment to the controller
*/
function sendAjaxCommentRequest(params,url){
	//alert('url = '+url);
	//alert('params = '+params);
	if(params != null){
		/*$.ajaxSetup({
		    'beforeSend' : function(xhr) {
		        xhr.overrideMimeType('text/html; charset=UTF-8');
		    }
		});*/

				
	     $.post(url, //the post URL
	   		  params, //the list of parameters
	   		  function (data, textStatus) {	   				
	   		  		if(textStatus == 'success'){
	   		  		    //alert("textStatus: " + textStatus);
	   		  			treatAddCommentSuccessMessage(data,params['content_id']);
	   		  		}
	   		  		else {
	   		  			displayNotPostCommentErrorMessage();
	   		  		}
	   			},
	   		'text' //the type of data that will be returned
	   	);

	}else{
		alert('params =  null');
	}
	
}
	


/*
* Store then display the html fragment corresponding to the comments table
*/
function treatAddCommentSuccessMessage(htmlFragment,docUUID){
	//alert(htmlFragment);
	//alert('#fivestar_comment_area_'+docUUID);
	var id = 'fivestar_comment_area_'+docUUID;
	//$('#fivestar_comment_area_'+docUUID).html(htmlFragment);
	if(htmlFragment == 'Error:captcha'){
		treatCaptchaError();
	}else{
		updateComment(htmlFragment,id)
	}
}

/*
 * Update the list of comments
 */
function updateComment(htmlFragment,divid){
	document.getElementById(divid).innerHTML = htmlFragment;
	setTimeout('fivestar_initialize()', 400);
}

//store the url
var old_url = null;
 
/*
 * Treat an error of captcha
 */ 
function treatCaptchaError(){
	 //alert('captcha error');
	 
 	//add error message
	var my_error_message = getCaptchaErrorMessage();
 	allParams['error_message'] = my_error_message;
 	allParamsKey.push('error_message');
	
	//get old link for the popin
	var oldURL = $('#nyromodalLink')[0].href;	
	old_url =oldURL;
	
	//update the url with parameter (form content)
	var newURL = oldURL+formatListOfParameter();
	
	//alert('newURL = '+newURL);
	
	//set the new link for the popin (add parameters)
	$('#nyromodalLink')[0].href=newURL;
	
	//reopen the modale
	$('#nyromodalLink').nyroModalManual({
	      bgColor: '#cc3333'	    	  
	});
	
	//reset the link
	setTimeout('resetPopinURL()', 400);

}

/*
 * Generate a list of parameter from the list of collected parameter
 * 
 */
function formatListOfParameter(){
	var urlFragment = '';
	
	//alert('allParamsKey = '+allParamsKey);
	
	for(var i=0; i<allParamsKey.length; i++){
		urlFragment+='&'+allParamsKey[i]+'='+escape(allParams[allParamsKey[i]]);
	}
	
	//alert(urlFragment);
	return urlFragment;
}


/*
 * Reset the link of the popin after a error message
 */ 
function resetPopinURL(){
	if(old_url != null && old_url!=''){
		$('#nyromodalLink')[0].href = old_url;
		old_url = null;
	}
}

/*
 * Check if the given type is right
 * @param input the input value
 * @param waitedType the waited type of input
 * @param errordiv the div where display message
 * @param errormessage the error message to diplay
 * @return nothing
 */ 
function validateInput(input,waitedType,errordiv,errormessage){
	
	 var validated = false;
	 
	//alert('input = '+input);
	if(input != null){	
	
		//Check value
		if(waitedType=='text'){
			validated = checkTextInput(input);
		}
		if(waitedType=='mail'){
			validated = checkEmailFormat(input);
		}
		if(waitedType=='url'){
			validated = checkUrlFormat(input);
		}
		
		//display error message
		if(!validated){
			document.getElementById(errordiv).innerHTML = errormessage;
		}else{
			document.getElementById(errordiv).innerHTML = '';
		}
	}
	
	return validated;
		
}

//check if the given string correspond to a valid url
//@param value the url to test the validity
//@return true if the value is a valid url, false otherwise
function checkUrlFormat(url) {
	var v = new RegExp();
	v.compile("^(http|https|ftp)://[\\w\\d-_]+\\.[\\w\\d-_]+(\\.[\\w\\d-_]+)*\\.[\\w\\d]{2,}(/[\\w\\d-_%&?/.=]+)*$","gi"); 
	return v.test(url);
}

//check if the given string correspond to a valid email address
//@param value the email address to test the validity
//@return true if the value is a valid email address, false otherwise
function checkEmailFormat(value){
	var filter = /^([a-zA-Z0-9_\.\-+])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
	return filter.test(value);
}

//check that the input is not empty
function checkTextInput(input){	
	return input !=null && input !='';
}

	

		 
