/*This javascript element helps with the app validations

---Version Control Chart----
| Date             |   Author           |         Modification| 

04/09/2007 | Xavier Santiago ?vila| Creation|
22/11/2007 | Xavier Santiago ?vila| Code organization. All form validators are in this file|
*/
/*Util functions*/

/*Trim function*/
String.prototype.trim = function() 
{
	return this.replace(/^\s+|\s+$/g,"");
}

/**
 * DHTML date validation script. Courtesy of SmartWebby.com (http://www.smartwebby.com/dhtml/)
 */
// Declaring valid date character, minimum year and maximum year
var dtCh= "/";
var minYear=1900;
var maxYear=2100;

function isInteger(s){
	var i;
    for (i = 0; i < s.length; i++){   
        // Check that current character is number.
        var c = s.charAt(i);
        if (((c < "0") || (c > "9"))) return false;
    }
    // All characters are numbers.
    return true;
}

function stripCharsInBag(s, bag){
	var i;
    var returnString = "";
    // Search through string's characters one by one.
    // If character is not in bag, append to returnString.
    for (i = 0; i < s.length; i++){   
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }
    return returnString;
}

function daysInFebruary (year){
	// February has 29 days in any year evenly divisible by four,
    // EXCEPT for centurial years which are not also divisible by 400.
    return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );
}
function DaysArray(n) {
	for (var i = 1; i <= n; i++) {
		this[i] = 31
		if (i==4 || i==6 || i==9 || i==11) {this[i] = 30}
		if (i==2) {this[i] = 29}
   } 
   return this;
}

function isDate(dtStr){
	var daysInMonth = DaysArray(12)
	var pos1=dtStr.indexOf(dtCh)
	var pos2=dtStr.indexOf(dtCh,pos1+1)
	var strMonth=dtStr.substring(0,pos1)
	var strDay=dtStr.substring(pos1+1,pos2)
	var strYear=dtStr.substring(pos2+1)
	strYr=strYear
	if (strDay.charAt(0)=="0" && strDay.length>1) strDay=strDay.substring(1)
	if (strMonth.charAt(0)=="0" && strMonth.length>1) strMonth=strMonth.substring(1)
	for (var i = 1; i <= 3; i++) {
		if (strYr.charAt(0)=="0" && strYr.length>1) strYr=strYr.substring(1)
	}
	month=parseInt(strMonth)
	day=parseInt(strDay)
	year=parseInt(strYr)
	if (pos1==-1 || pos2==-1){
		return false
	}
	if (strMonth.length<1 || month<1 || month>12){
		
		return false
	}
	if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month]){
		return false
	}
	if (strYear.length != 4 || year==0 || year<minYear || year>maxYear){
		return false
	}
	if (dtStr.indexOf(dtCh,pos2+1)!=-1 || isInteger(stripCharsInBag(dtStr, dtCh))==false){
		return false
	}
return true
}

function ValidateDate(month,day,year){
	var dt=month.value+'/'+day.value+'/'+year.value;
	
	if (isDate(dt)==false){
		
		return false
	}
    return true
 }

function postMovieComment(form,msg)
{
	var comm=form.newComm.value.trim();
	var idMovie=form.idMovie.value;
	
	if(comm=='' || !isAlphaNumeric(comm))
	{
		alert(msg);
		return false;
	}
	else
	{
		
		doPost('comments', 'php/actions/movie.action.php', {idMovie:idMovie,newComment:comm,method:'addComment'},form.id,'',null,false,'<img src=web/img/other/loading_wheel.gif >');
		return false;
	}
}
function postFilmComment(form,msg)
{
	var comm=form.newComm.value.trim();
	var idMovie=form.idMovie.value;
	
	if(comm=='' || !isAlphaNumeric(comm))
	{
		alert(msg);
		return false;
	}
	else
	{
		
		doPost('comments', 'php/actions/minifilms.action.php', {idMovie:idMovie,newComment:comm,method:'addComment'},form.id,'',null,false,'<img src=web/img/other/loading_wheel.gif >');
		return false;
	}
}

/**
 This function validates the signup form...
**/
function validateSignUp(form,msg1, msg2, msg3, msg4, msg5, msg6, msg7, msg8,msg9, codeV)
{

	arrayErrors = Array(msg1, msg2, msg3, msg4, msg5, msg6, msg7, msg8,msg9);
	
	
/*Validaci?n inicial (Caracteres v?lidos, campos completos, codigo de seguridad correcto, etc*/
  var name = form.fullName.value;
  var userName =form.userName.value;
  var mail = form.mail.value;
  var rmail = form.mailConfirm.value;  
  var pwd = form.password.value;
  var rpwd = form.rpassword.value;
  var code = form.code.value;
  var country = form.country.value;
  var errors = '';
    
   
  if(form.terms.checked == false)
  {
  	errors+='-'+arrayErrors[7]+'\n';
  
  }
  if(name.length < 3 || name == '' || !isAlphaNumeric(name))
  {
  	errors+='-'+arrayErrors[1]+'\n';
  }
  if(userName.length < 3 || userName == '' || !isAlphaNumeric(userName))
  {
  	errors+='-'+arrayErrors[2]+'\n';
  }
  if(mail.length < 3 || mail == '' || !isValidEmail(mail))
  {
  	errors+='-'+arrayErrors[3]+'\n';
  }
  //if(file.length<3 || file.search(re_text) == -1)
  //{
  //	errors+='-'+arrayErrors[8]+'\n';
  //}
  if( code.length <3  || code == '' || !isAlphaNumeric(code))
  {
  	errors+='-'+arrayErrors[6]+'\n';
  }
  else 
  {
  
  
  	if(mail!=rmail)  	
	  	errors+='-'+arrayErrors[4]+'\n';
	if(pwd!=rpwd || pwd.length<3)
		errors+='-'+arrayErrors[5]+'\n';	  	
	if(code!=codeV)
		errors+='-'+arrayErrors[6]+'\n';	
  }
  if( errors.length >0) 
  {
  	var temp =arrayErrors[0]+'\n';
  	temp=temp+errors;
  	alert(temp);
  	return false;
  }
  else
  {
  	doPost('loading', 'php/actions/user.action.php',{fullName:name,userName:userName,mail:mail,password:pwd,country:country,method:'signUp'}, form.id, '',{hide:'signUpForm'}, false, '<img src=web/img/other/loading_weel.gif>');
  }
  	
}

function forgotPasswd(form,msg,msg2,msg3)
{	
    var mail = form.email.value;
    var errors = false;
    
    if(mail.length < 3 || mail == '' || !isValidEmail(mail) )
		errors = true;
		
	if(errors)
	{
		alert(msg);
	}	
	else{
       // var res = "ERNO"; 
        doPost('loginLoading', 'php/actions/user.action.php',{email:mail,method:'passRecovery'}, form.id, '',{hide:'login'}, false,'<img src=web/img/other/loading_wheel.gif >');
       // alert(res);
        /*if(res=="ok"){
        	alert("ok: "+mail);
	      	alert(msg2);
      	}
      	else{
      		alert("nok: "+mail);
      		alert(msg3);
      	}*/
    }
}

function validateLoginForm(form, msg)
{
		var mail = form.email.value;
		var pwd = form.password.value;
		var remember = form.remember.checked;
		var errors = false;
	if(mail.length < 3 || mail == '' || !isValidEmail(mail) || pwd.length < 3 || pwd == '' || !isAlphaNumeric(pwd))
		errors = true;
	if(errors)
	{
		alert(msg);
		return false;
	}	
	else
	  doPost('loginLoading', 'php/actions/user.action.php',{login:mail,password:pwd,remember:remember,method:'login'}, form.id, '',{hide:'loginForm'}, false,'<img src=web/img/other/loading_wheel.gif >' );
}
function validateLoginAdmin(form, msg)
{
		var mail = form.email.value;
		var pwd = form.password.value;
		var remember = form.remember.checked;
		var errors = false;
		
		
	if(mail.length < 3 || mail == '' || !isValidEmail(mail) || pwd.length < 3 || pwd == '' || !isAlphaNumeric(pwd))
		errors = true;
	if(errors)
	{
		alert(msg);
		return false;
	}	
	else
	  doPost('loginLoading', 'php/actions/user.action.php',{login:mail,password:pwd,remember:remember,method:'login'}, form.id, '',{hide:'loginForm'}, false,'<img src=web/img/other/loading_wheel.gif >' );
}
function doZearch(idForm,msg)
{
	var form=document.getElementById(idForm);
	var param=form.data.value.trim();
	var criteria=form.criteria.value.trim();
	if(param == '')
	{
		alert(msg);
	}
	else
	{
		if(criteria ==1)
			window.open('http://www.zearch360.com?q='+param, '_blank');
		else 
		 form.submit();			
			 
	}
}

function validateLoginAdmin(form, msg)
{
		var mail = form.email.value;
		var pwd = form.password.value;
		var errors = false;
	if(mail.length < 3 || mail == '' || !isValidEmail(mail) || pwd.length < 3 || pwd == '' || !isAlphaNumeric(pwd))
		errors = true;
	if(errors)
	{
		alert(msg);
		return false;
	}	
	else
	  doPost('loginLoading', '../actions/user.action.php',{admin:true,login:mail,password:pwd,method:'login'}, form.id, '',{hide:'loginForm'}, false,'<img src=../../web/img/other/loading_wheel.gif >');
}
/*No hacking
function validPwd(cadena){

	var valid = Array( "(", ")", "\\", "'", "&", "|");
	var x;

	for(i=0; i<cadena.length; i++)
	{
		for( x in valid ){
			if( cadena.charAt[i] == valid[x] )
				return false;
		}
	}
	return true;	
}*/

function isValidProfileForm(form)
{
   var email = form.mail.value.trim();
   var fullName = form.fullName.value.trim();
   var userName = form.userName.value.trim();
   if(isValidEmail(email) && fullName.length!=0 && userName.length!=0)
	{
		
		return true;
		 
	}
	return false;

}

/*
This function validates if the email is valid

*/
function isValidEmail(email)
{
	if(email.length!=0)
		return email.match(/\b(^(\S+@).+((\.com)|(\.info)|(\.net)|(\.edu)|(\.mil)|(\.gov)|(\.org)|(\..{2,2}))$)\b/gi);
	
	return false;

}

/*This function makes an initial crypt of the password */


function isAlphaNumeric(data)
{

	var regExp = '[A-Za-z0-9_]'; //Alfanum?ricos
	if(data.match(regExp))
		return true;
		
		return false;
}



function cryptPwd(pasword)
{
	var numero = Math.random().toString();
	pasword+=numero;
	return pasword;

}

function validateMails(form)
{
if( (form.email1.value.length >0 && isValidEmail(form.email1.value)) && 
			(form.email2.value.length >0 && isValidEmail(form.email2.value)) && 
			(form.email3.value.length >0 && isValidEmail(form.email3.value)) && 
			(form.email4.value.length >0 && isValidEmail(form.email4.value)) && 
			(form.email5.value.length >0 && isValidEmail(form.email5.value)) && 
			(form.email6.value.length >0 && isValidEmail(form.email6.value)) && 
			(form.email7.value.length >0 && isValidEmail(form.email7.value)) && 
			(form.email8.value.length >0 && isValidEmail(form.email8.value)) && 
			(form.email9.value.length >0 && isValidEmail(form.email9.value)) && 
			(form.email10.value.length >0 && isValidEmail(form.email10.value)))	{
			alert('Some data is invalid. Please, verify your information');}
			
else { form.submit(); }
}

function validateSetPhotoProfile(form,msg)
{
	var filename=form.photo.value;
	var re_text = /\.jpeg|\.gif|\.jpg|\.png/i;
	
	if(filename.length<3 || filename.search(re_text) == -1)
	  {
	    alert(msg);
	    return false;
	  }
	  else
	  {
	  	form.submit();
	  }
}

function validateSearchFriendsForm(form, msg, msg2, friends)
{
	var value = form.friendFilter.value.trim();
	var idUser = form.idUser.value;
	if(value=='')
	{
		alert(msg);
		return false;
	}	
	else
	{
		if(form.toDelete.value == "true")
			doGet(null,'friendsView', 'php/actions/user.action.php', {query:value,userId:idUser,toDelete:"true",method:'searchUserFriends'},'<img src=web/img/other/loading_wheel.gif >');
		else	
			doGet(null,'friendsView', 'php/actions/user.action.php', {query:value,userId:idUser,method:'searchUserFriends'},'<img src=web/img/other/loading_wheel.gif >');
	}		
	return false;

}

/*This functions helps with the users search in the admin settings 

---Version Control Chart----
| Date             |   Author           |         Modification| 

15/01/2008 | Sergio Martinez | Creation|
*/
function validateSearchSettingsForm(form,msg)
{
    var dName = form.param.value.trim();
    var errors = false;
        
    //Verify if none is filled
    if( dName == '' )
    {
        errors = true;
    }   
    if( errors )
    {
        alert(msg);
        return false;
    }
    else{
        doGet(null,'searchDone', '../actions/admin.user.action.php', {name:dName,country:'',filmPrefs:'',queueList:'',isSettings:"1",method:'searchFU',checkBx:0},'<img src=web/img/other/loading_wheel.gif >');

        //doPost('searchDone', '../actions/admin.user.action.php',{name:dName,country:dCountry,filmPrefs:filmPref,queueList:qList,method:'searchFU'}, form.id, '',{hide:'loginForm'}, false,'searching...')
    }
    
    
    return false;
      
}

/*This functions helps with the search app validations

---Version Control Chart----
| Date             |   Author           |         Modification| 

14/12/2007 | Daniel Rojas | Creation|
*/
function validateSearchForm(form,msg)
{   
	var data = document.getElementById("data").value.trim();
	var criteria = document.getElementById("criteria").value;
	var check = document.getElementById("chkEmailer").value.trim();
	var country = document.getElementById("paises").value.trim();

	if(data=="" && criteria != '2')
	{
		alert(msg);
	}
	else
		doGet(null,'searchDone', '../actions/admin.user.action.php', {criteria:criteria,data:data,method:'searchFU',country:country,checkBx:check},'<img src=../../web/img/other/loading_wheel.gif>');
	return false;
	  
}


function addFilter(){
	
	var newFilters = Array();

	var newFilter = prompt("Add new filter");
	if( newFilter != null ){
		document.getElementById("newFilter").style.display = 'block';
		document.getElementById("newFilter").innerHTML='<label>'+newFilter+'&nbsp;: <input type="text" name="newFilter" value=""</label>';
	}
	
}

/*this function validates the basic info form in show account*/
function validateBasicInfoForm(form,errors, dateInv, loading)
{
    var name=form.fullName.value.trim();
    var nick=form.userName.value.trim();
    var country=form.country.value.trim();
    var ddate=form.dDate.value.trim();
    var mdate=form.mDate.value.trim();
    var ydate=form.yDate.value.trim();
    var date=mdate+"/"+ddate+"/"+ydate;
    
    if(name=='')
    {
        alert(errors);
        return false;
    }
    else if(nick=='')
    {
        alert(msg2);
        return false;
    }
    else if(country=='')
    {
        alert(msg3);
        return false;
    }
    else if(date=='' || !isDate(date))
    {
        alert(dateInv);
        return false;
    }
    else
    {
        date=ddate+"/"+mdate+"/"+ydate;//format change after validation
        doPost('loadingBasic', 'php/actions/user.action.php',{name:name,country:country,nick:nick,bDate:date,method:'editBasicInfo'}, form.id,'', null, false,loading);
    }
}

/*this function validates the basic info form in show account*/
function validatePersonalInfoForm(form,msg)
{
    var gender='male';
    if(form.genFe.checked)
        gender='female';
    var homeTown=form.homeTown.value;
    var sexualO=form.sexualO.value;
    var status=form.status.value;
    var language=form.language.value;
    var ocupation=form.ocupation.value;
    var workPlace=form.workPlace.value;
    var school=form.school.value;
    
    var sGender=form.sGender.checked;
    if(sGender)
       sGender=1;
    else
       sGender=0;
       
   var sHomeTown=form.sHomeTown.checked;
    if(sHomeTown)
       sHomeTown=1;
    else
       sHomeTown=0;
       
   var sSexualOrientation=form.sSexualOrientation.checked;
    if(sSexualOrientation)
       sSexualOrientation=1;
    else
       sSexualOrientation=0;
   
   var sStatus=form.sStatus.checked;
    if(sStatus)
       sStatus=1;
    else
       sStatus=0;
       
   
   var sLanguage=form.sLanguage.checked;
    if(sLanguage)
       sLanguage=1;
    else
       sLanguage=0;
   
   var sOcupation=form.sOcupation.checked;
    if(sOcupation)
       sOcupation=1;
    else
       sOcupation=0;
   
   
   var sWorkPlace=form.sWorkPlace.checked;
    if(sWorkPlace)
       sWorkPlace=1;
    else
       sWorkPlace=0;
   
   var sSchool=form.sSchool.checked;
    if(sSchool)
       sSchool=1;
    else
       sSchool=0;
   
    doPost('loadingPersonal', 'php/actions/user.action.php',{sGender:sGender,sHomeTown:sHomeTown,sSexualOrientation:sSexualOrientation,language:language,sStatus:sStatus,sLanguage:sLanguage,sOcupation:sOcupation,sWorkPlace:sWorkPlace,sSchool:sSchool,language:language,school:school,workPlace:workPlace,ocupation:ocupation,gender:gender,homeTown:homeTown,sexualO:sexualO,status:status,method:'editPersonalInfo'}, form.id,'saved', {hide:'editPersonalInfo'}, false,msg);
}

/*this function validates the basic info form in show account*/
function validateInterestInfoForm(form,msg)
{
	var hobbies=form.hobbies.value;
	var fTV=form.fTV.value;
	var fMovies=form.fMovies.value;
	var fBooks=form.fBooks.value;
	var fGenres=form.fGenres.value;
	var fActors=form.fActors.value;
	
    var sHobbies=form.sHobbies.checked;
    if(sHobbies)
       sHobbies=1;
    else
       sHobbies=0;
    var sFtv=form.sFTV.checked;
    if(sFtv)
       sFtv=1;
    else
       sFtv=0;
    var sFMovies=form.sFMovies.checked;
    if(sFMovies)
       sFMovies=1;
    else
       sFMovies=0;
    var sFBooks=form.sFBooks.checked;
    if(sFBooks)
       sFBooks=1;
    else
       sFBooks=0;
    var sFGenres=form.sFGenres.checked;
    if(sFGenres)
       sFGenres=1;
    else
       sFGenres=0;
    var sFActors=form.sFActors.checked;
    if(sFActors)
       sFActors=1;
    else
       sFActors=0;
	
	doPost('loadingInterests', 'php/actions/user.action.php',{sFActors:sFActors,sFGenres:sFGenres,sFBooks:sFBooks,sFMovies:sFMovies,sFtv:sFtv,sHobbies:sHobbies,fActors:fActors,fGenres:fGenres,fBooks:fBooks,fMovies:fMovies,fTV:fTV,hobbies:hobbies,method:'editInterestInfo'}, form.id,'', {hide:'editInterestInfo'}, false, msg);

}
function validatePostComments(form, msg)
{

	var msag=form.comment.value;
	var idTo=form.idTo.value;
	
	if(msag == "")
	{
		alert(msg);
		return false;
	}	
	else
		doPost('postComments', 'php/mvc/postComment.php',{msg:msag,idTo:idTo,method:'addPost'}, form.id,'', {}, false, '<img src=web/img/other/loading_wheel.gif >');
		
		
}

/*Footer forms*/
function validateSuggestMovie(form, msg, msg2, loading)
{
	var movieName = form.movieName.value.trim();
	var movieDescription = form.movieDescription.value.trim();
	var userName = form.userName.value.trim();
	var emailAdress = form.emailAdress.value.trim();
	var addComments = form.addComments.value.trim();
	var subject = form.subject.value.trim();
	
	if(movieName == "")
	{
		alert(msg);
		return false;
	}
	else if(!isValidEmail(emailAdress))
	{
		alert(msg2);
		form.emailAddress.focus();
		return false;
	}
	else
	{
		doPost('loading', 'php/actions/extra.action.php',{method:'suggestMovie',subject:subject,movieName:movieName,movieDescription:movieDescription,userName:userName,emailAddres:emailAdress,comments:addComments}, form.id,'', {}, false, loading);
		
	}
	

}

function validateContact(form, msg, msg2, loading)
{
	var userName = form.userName.value.trim();
	var emailAdress = form.emailAdress.value.trim();
	var addComments = form.addComments.value.trim();
	var subject = form.subject.value.trim();
	
	
	
	if(userName == "" || emailAdress == "" || addComments=="" || subject =="")
	{
		alert(msg);
		return false;
	}
	else if(!isValidEmail(emailAdress))
	{
		alert(msg2);
		form.emailAddress.focus();
		return false;
	}
	else
	{
		doPost('loading', 'php/actions/extra.action.php',{method:'contactUs',subject:subject,userName:userName,emailAddres:emailAdress,comments:addComments}, form.id,'', {}, false, loading);
		
	}
	

}
function validateSearchPeopleForm(form, msg)
{
	var data = form.data.value.trim();
	if(data == "")
	{
		alert(msg);
		return false;
	}
	else 
		doGet(null, 'searchPeople', 'php/actions/user.action.php', {method:'findUsers',data:data}, '<img src=web/img/other/loading_wheel.gif >');
		
	
	

}

function validateSendInviteMail(form, msg)
{
	 var i=0;
	 var cCheck=0;
	 var objInput = form.getElementsByTagName("input");
	 var lObj = (objInput!=null)? objInput.length : 0;
 	 var mails = "";
 	
 	for(i=0;i<lObj;i++)
	 {   
    	if ((objInput[i].type=="checkbox")&&(objInput[i].checked)) 
    	{
    		mails+=objInput[i].name+",";
    		cCheck++;  
    	}	
	 }
	 if(cCheck == 0 )
	 {
	 	alert(msg);
	 	return false;
	 }
	 else
	 	doPost('sending', 'php/actions/user.action.php',{method:'invite',mails:mails}, form.id,'', {}, false, '<img src=web/img/other/loading_wheel.gif >');
	
	  
}
/*finish*/
