/* HTML FUNCTION */

function writeText(divID,text){
	document.getElementById(divID).innerHTML = text;
}

function hideDiv(ID){
	document.getElementById(ID).style.display='none';
}
		
function showDiv(ID){
	document.getElementById(ID).style.display='';
}

function duplicateDivInDiv(idDivToDuplicate,newIdDivToDuplicate,idDivWrapper,data){
	var source=document.getElementById(idDivToDuplicate);
        if(source){
			var obj=source.cloneNode(true);
			obj.setAttribute('id',newIdDivToDuplicate);
		    	obj.getElementsByTagName('div').item(1).innerHTML = data.nickname;
			
			var d = new Date(data.date);
			var curr_date = d.getDate();
			var curr_month = d.getMonth();
			var curr_year = d.getFullYear();
			var formattedDate = (curr_date + "-" + curr_month + "-" + curr_year);
		        obj.getElementsByTagName('div').item(2).innerHTML = formattedDate;
			obj.getElementsByTagName('div').item(3).innerHTML = data.body;
			//obj.style.visibility='visible';
			document.getElementById(idDivWrapper).appendChild(obj);
	}
}

function removeDivInDiv(idDivToRemove,idDivWrapper) {
	var source=document.getElementById(idDivToRemove);
        if(source!=null){
		document.getElementById(idDivWrapper).removeChild(source);	
	}
}

function buildWrapperComments(data) {
        if(data.length>1) {
		for(var i = 0; i < data.length; i++)
        	{
        		duplicateDivInDiv('usercomment','usercomment'+i,'slideWrapper',data[i]);
        	}
            removeDivInDiv('usercomment','slideWrapper');
	}else if(data.length==1){
		writeText('contributename',data[0].nickname);
		writeText('contributedate',data[0].date);
		writeText('contributebody',data[0].body);
	}else {removeDivInDiv('usercomment','slideWrapper');}
	
}

function disableField()
{
        if(document.getElementById('loginradio').checked==true){
                element('nickname').disabled=true;
        	element('email').disabled=true;
	        element('body').disabled=true;
        	element('submitNotRegister').disabled=true;
        }
}

function enableField()
{
	element('nickname').disabled=false;
        element('email').disabled=false;
	element('body').disabled=false;
        element('submitNotRegister').disabled=false;
}

function validateProfileInputField(element)
 {
 
   var id = element.id;
   var value = element.value;
   UserCommentValidatorJS.getInputFieldValidationMessage(id, value, {
           callback:function(dataFromServer) {
                   setInputFieldStatus(element.id, dataFromServer);
           }
   });
 }



 function setInputFieldStatus(elementId, message)
 {
    var id = "" + elementId + "_error";
    document.getElementById(id).innerHTML = message;
 }

function element(elementID){
        var index =  document.getElementsByName(elementID).length;
        index = index - 1;
	return document.getElementsByName(elementID).item(index);
}


/* DWR FUNCTION */

var opened = false;
var loaded = false;
function getUserComments(uri){
       if(opened){
             opened=false;
             hideDiv('slideWrapper');
             hideDiv('writeComment');
       }else{
             opened=true;
             
             if(loaded){
                     showDiv('slideWrapper');
                     showDiv('writeComment');   
             }else{
                    loaded=true;
                    UserContentContributeService.getUserComments(uri,handleGetUserComments);
             }	
               
       }
}

var actualURI;


function writeStatOfVotes(uri) { 
        checkCookieForVote(uri);
        initVoteValue(uri);
}

function initVoteValue(uri){
        UserContentContributeService.getCountOfVote(uri,handleGetCountOfVote);
}

function handleGetCountOfVote(data) {
	if(data!=null){
               writeText('numberOfVote',data);
        }else{
              alert('Internal Server Error');
	}
}


function addVote(uri){
     vote(uri, voteActual);
}

function vote(uri, vote) {
        if(getCookie(uri)!='true'){
            actualURI = uri;
	    UserContentContributeService.saveVote(uri,vote, handleAfterUserVote);
	    setCookie(uri,'true');
        }
        
}

function handleAfterUserVote(data) {
	if(data!=null){
               initVoteValue(actualURI);
               closePopUp('voteWithStar');
               openPopUp('afterVoteWithStar');
               hideDiv('openVotePopUp');
        }else{
              alert('Internal Server Error');
	}
}


function saveCommentForLoggedProfile(){
      var body = element('body').value;
      var path = element('path').value;
      UserContentContributeService.saveCommentForLoggedProfile(body,path,handleAfterUserCommentLogged);   
}

function saveCommentForNotLoggedProfile(form){
      var body = element('body').value;
      var path = element('path').value;
      var nickname = element('nickname').value;
      var email = element('email').value;
      UserContentContributeService.saveCommentForNotLoggedProfile(body,path,nickname,email,handleAfterUserCommentNotLogged);   
}

/* DWR CALLBACK FUNCTION */

function handleAfterUserCommentLogged(data){
      if(data!=null){
              if(data==false) {
                       validateProfileInputField(element('body'));
              }else{
                       validateProfileInputField(element('body')); 
                       hideDiv('writeComment');
                       showDiv('afterComment');
                   }
      }else{
              alert('Internal Server Error');
      }
}

function handleAfterUserCommentNotLogged(data){
      if(data!=null){
              if(data==false) {
                       validateProfileInputField(element('nickname'));
                       validateProfileInputField(element('email'));
                       validateProfileInputField(element('body'));
              }else{
                       validateProfileInputField(element('nickname'));
                       validateProfileInputField(element('email'));
                       validateProfileInputField(element('body')); 
                       hideDiv('writeComment');
                       showDiv('afterComment');
                   }
      }else{
              alert('Internal Server Error');
      }
}



function handleGetUserComments(data) {
        
	if(data!=null){
		buildWrapperComments(data);
                showDiv('slideWrapper');          
                showDiv('writeComment');          
                
	}else{
		alert('Internal Server Error');
	}
}



/* COOKIE FUNCTION */

function setCookie(key,value) {
	try {
	Cookie.set(key, value, {duration: 10000}); // save this for 10000 day
	} catch(err){}
}

function getCookie(key) {
	try  {
	return Cookie.get(key);
	} catch(err){}
}

function checkCookieForVote(uri){
        if(getCookie(uri)=='true'){
               if(document.getElementById('openVotePopUp')){
                 hideDiv('openVotePopUp');
                }
  
        }
}


/* AGGREGATOR FUNCTIONS */

 function isEmail(string) {
		if (string.search(/^\w+((-\w+)|(\.\w+))*\@\w+((\.|-)\w+)*\.\w+$/) != -1)
			return 1;
		else
			return 0;
	}

	function toggleSendToFriend(){
		var div = document.getElementById('sendToFriendDiv');
		if(div.style.display=='none'){
			div.style.display='';
		}else{
			div.style.display='none';
		}	
	}

	function sendCommunityEmailToFriends(){
		var recipientName = document.getElementById('recipientName').value;
                var recipientEmail = document.getElementById('recipientEmail').value;
                var recipientMessage = document.getElementById('recipientMessage').value;
                var senderGender = document.getElementById('senderGender').value;
                var senderName = document.getElementById('senderName').value;
                var senderNickname = document.getElementById('senderNickname').value;
                
                if(validateFieldsForSendEmailCommunity(recipientName,recipientEmail)){
		       sendCommunityToFriendsService.sendEmailQuizToFriends(recipientName, recipientEmail, recipientMessage, senderGender, senderName, senderNickname,sendCommunityEmailToFriendsCallBack);
                }

	}
         
        function validateFieldsForSendEmailCommunity(recipientName,recipientEmail){
               var flagName = validateRecipientName(recipientName);
               var flagEmail = validateRecipientEmail(recipientEmail);
               if(flagEmail){
                      var flagEmailCorrect = validateRecipientEmailCorrect(recipientEmail);
               }
               if(flagName && flagEmail && flagEmailCorrect){
                       return true;
               }
               return false;
        }


        function validateRecipientName(field){
              if(validateField(field)){
                       document.getElementById('nameRequired').style.display = 'none';
                       return true;
              }else{
                       document.getElementById('nameRequired').style.display = '';
                       return false;
              }
        }
 
        function validateRecipientEmail(field){
              if(validateField(field)){
                       document.getElementById('emailRequired').style.display = 'none';
                       return true;
              }else{
                       document.getElementById('emailRequired').style.display = '';
                       return false;
              }
        }

        function validateRecipientEmailCorrect(field){
              if(isEmail(field)){
                       document.getElementById('emailInvalid').style.display = 'none';
                       return true;
              }else{
                       document.getElementById('emailInvalid').style.display = '';
                       return false;
              }
        }        
        

        function validateField(field){
              if(field==null || field==''){
                     return false;
              } else {
                     return true;
              }
        }
	
	function sendCommunityEmailToFriendsCallBack(data){
		if(data!=null){
			if(data==true){
                                closePopUp('sendToFriend');
                                openPopUp('sendToFriendAfter');
                                
			}else{
				alert('Error during send emails');
			}
		}else{
			alert('Server Error');
		}
	}

	function setValue(val)
		{
			
			if(val.checked)
			  document.getElementById(val.id).value=true;
			else
			{
			  document.getElementById(val.id).value=false;
			}
		}
		function submitForm()
		{
			document.getElementById("formSearch").submit();
		}

var voteActual = 5;

function $(v,o) { return((typeof(o)=='object'?o:document).getElementById(v)); }
				function $S(o) { return((typeof(o)=='object'?o:$(o)).style); }
				function agent(v) { return(Math.max(navigator.userAgent.toLowerCase().indexOf(v),0)); }
				function abPos(o) { var o=(typeof(o)=='object'?o:$(o)), z={X:0,Y:0}; while(o!=null) { z.X+=o.offsetLeft; z.Y+=o.offsetTop; o=o.offsetParent; }; return(z); }
				function XY(e,v) { var o=agent('msie')?{'X':event.clientX+document.documentElement.scrollLeft,'Y':event.clientY+document.documentElement.scrollTop}:{'X':e.pageX,'Y':e.pageY}; return(v?o[v]:o); }
				
				star={};
				
				star.mouse=function(e,o) { if(star.stop || isNaN(star.stop)) { star.stop=0;
				
				    document.onmousemove=function(e) { var n=star.num;
				    
				        var p=abPos($('star'+n)), x=XY(e), oX=x.X-p.X, oY=x.Y-p.Y; star.num=o.id.substr(4);
				
				        if(oX<1 || oX>205 || oY<0 || oY>40) { star.stop=1; star.revert(); }
				        
				        else {
				
				            $S('starCur'+n).width=oX+'px';
				            //$S('starUser'+n).color='#111';
				            if (Math.round(oX/205*100) > 0 && Math.round(oX/205*100) <= 20) {
				            	$('starUser'+n).innerHTML='così così';
                                                voteActual = 1;
				            }
				            else if (Math.round(oX/205*100) > 20 && Math.round(oX/205*100) <= 40) {
				            	$('starUser'+n).innerHTML='niente di speciale';
                                                voteActual = 2;
				            }
				            else if (Math.round(oX/205*100) > 40 && Math.round(oX/205*100) <= 60) {
				            	$('starUser'+n).innerHTML='degno di nota';
                                                voteActual = 3;
				            }
				            else if (Math.round(oX/205*100) > 60 && Math.round(oX/205*100) <= 80) {
				            	$('starUser'+n).innerHTML='bello';
                                                voteActual = 4;
				            }
				            else if (Math.round(oX/205*100) > 80 && Math.round(oX/205*100) <= 100) {
				            	$('starUser'+n).innerHTML='strepitoso';
                                                voteActual = 5;
				            }

				            //$('starUser'+n).innerHTML=Math.round(oX/205*100)+'%';
				        }
				    };
				} };
				
				star.update=function(e,o) { var n=star.num, v=parseInt($('starUser'+n).innerHTML);
				
				    n=o.id.substr(4); $('starCur'+n).title=v;
				
				    req=new XMLHttpRequest(); req.open('GET','?vote='+(v/100),false); req.send(null);    
				
				};
				
				star.revert=function() { var n=star.num, v=parseInt($('starCur'+n).title);
				
				    $S('starCur'+n).width=Math.round(v*205/100)+'px';
				    //$('starUser'+n).innerHTML=(v>0?Math.round(v)+'%':'');
				    //$('starUser'+n).style.color='#888';
				    
				    document.onmousemove='';
				
				};
				
				star.num=0;
