// VALIDATING FORM
function formValidate(form, name){
	  
    // Locking buttons
    $(".form_"+name+" .form-buttons input").attr("disabled", "disabled");
  
    // If TinyMCE, save the content
    try
    {
        tinyMCE.triggerSave();	
    }catch(e)
	{
	}
    
    //data for sending
	var send = "";

    // Going through all elements in the form
    var i=0;
    while (i >= 0) {
	    if(!form[i]){
            break;
        }
		// if CHECKBOX or RADIO
        if(form[i].type=="checkbox" || form[i].type=="radio"){
            if(form[i].checked == false){
                i++;
                continue;
            }
        }
		// if SELECT (multiple select upgrade)
		if(form[i].tagName=="SELECT"){
			for (var s = 0; s < form[i].options.length; s++)
			{
				if (form[i].options[s].selected)
				{
					send += form[i].name + "=" + Url.encode(form[i].options[s].value) + "&";
				}
			}
			i++;
			continue;
        }
		
        //adding what to validate to send data
		send += form[i].name + "=" + Url.encode(form[i].value) + "&";
		i++;
	}

	//sending more options
	send += "module=Forms&ajax=SendForm";
	
	// if it doesn't check it -> return false;
	success = false;
	
	// ajax query
	$.ajax({
		type: "POST",
		url: Cyfy.getSourcePath('ajax.php'),
		data: send,
		async: false,
		dataType: "json",
		success: function(data)
		{
			
            if(data.location){
                Cyfy.redirectTo(data.location);
                return false;
            }
			
            if(!data.stay && data.success){
                // empty
                $(".form_"+name+" .form-item input[type=text]").attr("value", "");
                $(".form_"+name+" .form-item input[type=password]").attr("value", "");
                $(".form_"+name+" .form-item textarea").val("");
                // files remove
                $(".form_"+name+" .form-item .inputs").html("");
                $(".form_"+name+" .form-item .form-upload-log").html("");
                // tiny
                $(".form_"+name+" .mceContentBody").html("");
                
            }

            if(data.messages){
				Cyfy.setMessages(data.messages);
            }
            success = data.success;	// returning
			
			// onsubmit
			if(data.onSubmit) eval(data.onSubmit);
            
            // onvalidate
			if(data.onValidate) eval(data.onValidate);
		}
	});
  
    // unlocking buttons
    $(".form_"+name+" .form-buttons input").removeAttr("disabled");
     
	return success;
}
