var validate_json                   =   null;
var validate_error_prefix           =   "_validation_error";
var validation_config               =   null;
var validate_window                 =   null;

var validate_submit_button_id       =   null;

var custom_client_validate_handler  =   null;

function set_custom_client_validate_handler(name) {
    custom_client_validate_handler = name;
}

function get_custom_client_validate_handler() {
    var handler = custom_client_validate_handler;
        custom_client_validate_handler = null;
    return handler;
}

function restore_submit_button()
{
    if (validate_submit_button_id != null ) $(validate_submit_button_id).disabled=false;
}

function fill_color_field( element, action )
{
    if ( action ) element.style.backgroundColor = "#FFF58F";
    else element.style.backgroundColor = "#FFFFFF";
}

function my_field_error(element, errorMessage)
{
    if ( errorMessage )
    {
        fill_color_field( element, true );
        validate_json.validate.errors.msg.push(errorMessage);
    }
    else
    {
        fill_color_field( element, false );
    }
}

function submit_button(id, form)
{
    validate_submit_button_id = id;
    $(validate_submit_button_id).disabled=true;
    $(form).onsubmit(); return false;

    //if (navigator.appName == "Microsoft Internet Explorer" || navigator.appName == "Opera" || navigator.appName == "Netscape") {
    //     $(form).onsubmit();
    //     return false;
    //} else return true;
}

function show_alert_message( message )
{
    Dialog.alert(message, 
               {windowParameters: {className: "alphacube", width:300}, okLabel: "Close", 
                ok:function(win) {debug("validate alert panel"); return true;}, cancel:function(win) {debug("validate cancel panel"); return true;}});
}

/*
function validate_shutdown()
{
    if ( top.error_fields.length )   
    {
        
        Dialog.alert(top.error_fields.join("<br>"), 
               {windowParameters: {className: "alphacube", width:300}, okLabel: "Close", 
                ok:function(win) {debug("validate alert panel"); return true;}, cancel:function(win) {debug("validate cancel panel"); return true;}});
        //alert(top.error_fields.join("\n"));
        top.error_fields = new Array();
        restore_submit_button();
    }
}
*/

function check_element_for_validation(element)
{
    var alt = element.getAttribute('alt')
	if((alt != null) && (alt != undefined) && (alt != '') || (alt == "validated"))
	   top.all_elements.push(element.id);
}

function clear_form(form)
{
        var elements = new Array();
        
    	if(form.tagName.toString().toLowerCase() == 'form') {
    		var elements = form.getElementsByTagName('*');
    	} else {
    		elements[0] = form;
    		while((form.tagName.toString().toLowerCase() != 'form') && (form.parentNode != null)) {
    			form = form.parentNode;
    		}
    		if(form.tagName.toString().toLowerCase() != 'form') {
    			elements = new Array();
    		}
    	}
    	
    	for(var eCounter = 0; eCounter < elements.length; eCounter++)
    	{
        		check_element_for_validation(elements[eCounter]);
    	}
    
        for (i=0; i <= top.all_elements.length-1; i++)
        {
            id = top.all_elements[i] + validate_error_prefix;
            try {
                $(id).remove();
                //$(top.all_elements[i]).style.backgroundColor = "#FFFFFF";
                fill_color_field( $(top.all_elements[i]), false );
            } catch(e) {
                
            }
        }
        top.all_elements = new Array();
        form.reset();
}

function show_message(field, text, message_type)
{
    var validation_class = "validation-advice";
        if (message_type) validation_class = "validation-good";
    for (i=0; i <= top.all_elements.length-1; i++)
    {
        id = top.all_elements[i] + validate_error_prefix;
        try {
            $(id).remove();
        } catch(e) {
        }
    }

     id = field + validate_error_prefix;
     try {
        $(id).remove();
     } catch(e) {
     }
       var error_string = "<div class='"+validation_class+"' id='"+id+"' style=\"display:none\">"+text+"</div>";
     try {
        $(id).innerHTML = error_string;
     } catch(e) {
        new Insertion.After(field, error_string);
        new Effect.Appear(id, {duration : 1 });
     }
     restore_submit_button();
     //validate_message_fadeout( new Array( field) ); // Auto Hide Validation Messages
}

function clear_validate_json()
{
    validate_json.validate.errors.id = new Array();
    validate_json.validate.errors.msg = new Array();
    validate_json.validate.good.id = new Array();
}

// VALIDATION HANDLERS
//=============================================================================================================================================
function standard_handler()
{
    var validation_class = "validation-advice";
    for(i=0; i <= validate_json.validate.errors.id.length-1; i++)
    {
        id = validate_json.validate.errors.id[i] + validate_error_prefix;
        if (validate_json.validate.good.id.indexOf(validate_json.validate.errors.id[i]) > -1) validation_class = "validation-good";
        var error_string = "<div class='"+validation_class+"' id='"+id+"' style=\"display:none\">"+validate_json.validate.errors.msg[i]+"</div>";
        try {
            $(id).innerHTML = error_string;
        } catch(e) {
                new Insertion.After(validate_json.validate.errors.id[i], error_string);
                new Effect.Appear(id, {duration : 1 });
                fill_color_field( $(validate_json.validate.errors.id[i]), true );
        }
        
    }
}

function old_handler()
{
    try {
        validate_window.close();
    } catch(e) {
        
    }
    
    Dialog.alert(validate_json.validate.errors.msg.join("<br/>"),
               {windowParameters: {className: "alphacube", width:300}, okLabel: "Закрыть", 
                ok:function(win) {debug("validate alert panel"); return true;}, cancel:function(win) {debug("validate cancel panel"); return true;}});
}
//=============================================================================================================================================

function validate_shutdown( from_server )
{
    validation_config = validate_json.validate.config;

    if ( validate_json.validate.errors.id.length )
    {
        for (i=0; i <= top.all_elements.length-1; i++)
        {
            id = top.all_elements[i] + validate_error_prefix;
                try {
                    $(id).remove();
                } catch(e) {
                }
        }
        for(i=0; i <= validate_json.validate.errors.id.length-1; i++)
        {
            try {
                $(validate_json.validate.errors.id[i] + validate_error_prefix).remove();
            } catch(e) {
                
            }
        }
        
        // CALL VALIDATION HANDLER
        if ( from_server ) eval (validation_config.handler+"()");
        else {
            var handler = get_custom_client_validate_handler();
            if ( handler != null) {
                eval (handler+"()");
            } else {
                standard_handler();
            }
        }
        
        
        // Execute Callback function if exists
        if (from_server) {
            var callbackFunction = top.validate_json.validate.callback;
            if (callbackFunction != "") eval(callbackFunction);
        }
        
        //validate_message_fadeout ( top.error_ids ); // Auto Hide Validation Messages
        clear_validate_json();
        top.all_elements = new Array();
        restore_submit_button();
    }
}

function validate_message_fadeout( ids )
{
    top.fadeout_error_ids = ids;
    setTimeout( "do_fadeout();", 1000 );
}

function do_fadeout()
{
    for( i=0; i <= top.fadeout_error_ids.length-1; i++ ) {
        var element_id = top.fadeout_error_ids[i] + validate_error_prefix;
        new Effect.Fade(element_id, {duration : 1 });
    }

    top.fadeout_error_ids = new Array();
}
