/**
* Возвращает значения из элементов ввода, содержащихся
* @param String container_id идентификатор контейнера, в рамках которого определяются значения элементов ввода.
* @return Array
*/
function get_input_values(container_id)
{
    var params = new Array();

    var container = document.getElementById( container_id );


    var collection = container.getElementsByTagName('select');
    if (collection) {
        for (i = 0; i < collection.length; i++) {
            params[collection[i].name] = collection[i].value;
        }
    }


    var validate_ok = true;
	
	
	var collection = container.getElementsByTagName('input');
	if (collection) {
            for (i = 0; i < collection.length; i++) {
			
		if (!form_validator.validate( collection[i] )) {
                    validate_ok = false;
                    var error_container_id = form_validator.get_error_container_id();
                    var error_container = document.getElementById( error_container_id );
                    if (error_container)
                        error_container.innerHTML = form_validator.get_message();

		}
                else{
                    var error_container = document.getElementById(form_validator.get_error_container_id());
                    if (error_container)
                        error_container.innerHTML = form_validator.get_message();

                }


                // обработка чекбоксов
                if (collection[i].type == 'checkbox')  {
                    var c = collection[i].getAttribute('confirm');

                    if (collection[i].getAttribute('confirm')==null)  {
                        if (collection[i].checked) {
                            params[collection[i].name] = 1;
                        }
                        else {
                            if (collection[i].type=='checkbox') {
                                params[collection[i].name] = 0;
                            }
                        }
                    }
                }


                if (collection[i].type == 'radio')  {
                    if (collection[i].checked)  {
                        params[collection[i].name] = collection[i].value;
                    }
                }

                if (collection[i].type == 'text')  {
                    if ( !is_elem_disabled( collection[i] ) ) {
                        params[collection[i].name] = collection[i].value;
                    }
                }

                if (collection[i].type == 'hidden')  {
                    params[collection[i].name] = collection[i].value;
                }
			

                if ((collection[i].type == 'password') && (!collection[i].disabled))  {
                    params[collection[i].name] = collection[i].value;

                    var confirm_elem_id = collection[i].getAttribute('confirm');
                    if (confirm_elem_id) {
                        var pass_value = collection[i].value;
                        var confirm_elem = document.getElementById(confirm_elem_id);
                        if (confirm_elem) {
                            var confirm_value = confirm_elem.value; // getAttribute('value');
                            if (confirm_value) {
                                if (pass_value != confirm_value) {
                                    validate_ok = false;
                                    alert('Введенные пароли не совпадают.');
                                }
                            }
                        }
                    }
                }


            } // of for

	} // of input collection

	var collection = container.getElementsByTagName('textarea');
	for (i = 0; i < collection.length; i++)  {
            if (!is_elem_disabled(collection[i])) {
                params[collection[i].name] = collection[i].value;
            }
	}

        var collection = container.getElementsByTagName('div');
	for (i = 0; i < collection.length; i++)  {
            if (collection[i].getAttribute('contentEditable')) {
                params[collection[i].getAttribute('name')] = collection[i].innerHTML;
            }
	}

	if (!validate_ok) {
            return false;
	}

	/*for (var HashKey in params)
	{ 
	   param_name  = HashKey; 
	   param_value = params[HashKey];
	   alert('name = '+param_name+' value '+param_value);
    }*/
    return params;
}

function setup_checkboxes(container_id)
{
    var container = hydra.get(container_id);
    if (!container) {
        return false;
    }
    var collection = container.getElementsByTagName('input');
    for (i = 0; i < collection.length; i++)
    {
        if (collection[i].type == "checkbox") {
            if (collection[i].value == 1) {
                collection[i].setAttribute("checked", "true");
            }
        }
    }
}

function is_elem_disabled(elem)
{
	//alert('try to check '+elem.name);
	var dis = elem.getAttribute('disabled');
	if (dis==true)
	{
		return true;
	}

// this is checking for firefox
	if (dis=='true')
	{
		return true;
	}

	return false;
	//alert('check disabled attribute in function '+dis);
/*	alert('check '+elem.name+' like bool for '+dis);
	if (dis==false)
	{
		alert('like bool is enabled');
	}
	else 
	{
		alert('like bool is disabled');
	}
*/
	if (elem.getAttribute('disabled')==null || elem.getAttribute('disabled')=='false')
	{
		alert('found like enabled');
		return false;
	}
	alert('found like disabled');
	return true;
}

function set_conatiner_elements_disabled_value(container_id, disabled)
{
  
 
	var container = document.getElementById( container_id );
    if (!container)
        return false;
        
    var collection = container.getElementsByTagName('input');
    if (!collection)
        return false;
        
    for (i = 0; i < collection.length; i++) 
    {
        collection[i].disabled = disabled;
        
        if (disabled)
          collection[i].setAttribute('disabled', 'true');
        else   
          collection[i].removeAttribute('disabled');
    }        

	var collection = container.getElementsByTagName('textarea');
    if (!collection)
        return false;
        
    for (i = 0; i < collection.length; i++) 
    {
        collection[i].disabled = disabled;
        
        if (disabled)
          collection[i].setAttribute('disabled', 'true');
        else   
          collection[i].removeAttribute('disabled');
    }        
    
    return true;	
}

function clear_content()
{
	return clear_element_content('content');
}

function clear_element_content(elem_id)
{
	var elem = document.getElementById( elem_id );
	if (elem)
	{
		elem.innerHTML = '';
		return true;
	}
	return false;
}

function clean_input_values(container_id)
{
    var container = document.getElementById( container_id );

	var collection = container.getElementsByTagName('select');
	if (collection)
	{
		for (i = 0; i < collection.length; i++)
		{
			collection[i].selectedIndex = 0;
		}
	}

	var collection = container.getElementsByTagName('input');
	if (collection)
	{
		for (i = 0; i < collection.length; i++)
		{

			// обработка чекбоксов
			if (collection[i].type == 'checkbox')
			{
                //collection[i].value = 0;
                collection[i].checked = false;
			}


			if (collection[i].type == 'radio')
			{
                collection[i].checked = false;
            }

			if (collection[i].type == 'text')
			{
                collection[i].value = '';
			}

			if (collection[i].type == 'hidden')
			{
                //наверно с ними ничего не делаем
				//collection[i].value;
			}


			if ((collection[i].type == 'password') && (!collection[i].disabled))
			{
				collection[i].value = '';

			}


		}

	}

	var collection = container.getElementsByTagName('textarea');
	for (i = 0; i < collection.length; i++)
    {
		collection[i].value = '';
	}

    return true;
}

/**
 *  Возвращает кож нажатой клавиши.
 */
function get_pressed_key_code(evt)
{
    var e = (window.event) ? window.event : evt;
    return e.keyCode;
}

function draw_message(container_id, message, css_class) {
    var elem = document.getElementById(container_id);
    if (elem) {
        if (css_class) {
            elem.setAttribute('class', css_class);
        }
        elem.innerHTML = message;
    }
}

function draw_message_success(container_id, message)
{
    draw_message(container_id, message, 'm-success');
}

function display_message(container_id, message) {
    var elem = document.getElementById(container_id);
    if (elem) {
        elem.setAttribute('class', 'message');
        elem.innerHTML = message;
    }
}


function enable_element(elem_id) {
    var elem = document.getElementById(elem_id);
    if (elem) {
        elem.disabled = false;
    }
}

/**
 *  Дизейблит заданный элемент.
 *
 *  @param String elem_id идентификатор элемента.
 */
function disable_element(elem) {
    

    if (typeof(elem) == "string") {
        elem = get_element(elem);
    }
    
    if (elem) {
        elem.disabled = true;
    }
}

function get_element(elem_id) {
    var elem = document.getElementById(elem_id);
    return elem;
}

function hydra_get_elems_by_tag(container_id, tag_name) {
    var container = document.getElementById( container_id );
    if (container) {
        return container.getElementsByTagName(tag_name);
    }

    return false;
}


function hydra_create_span(caption, attr) {
    var span = document.createElement('span');
    span.appendChild(document.createTextNode(caption));
    

    // Обработка аттрибутов
    for (var attrName in attr) {
       span.setAttribute(attrName, attr[attrName]);
    }

    return span;
}

/**
 * Создает элемент.
 *
 * @param string tagName имя тега элемента
 * @param array attr атрибуты элемента
 *
 * @return Element || false
 */
function hydra_create_element(tagName, attr) {
    //debugger;
    var elem = document.createElement(tagName);
    if (!elem) {
        return false;
    }

    // Обработка аттрибутов
    for (var attrName in attr) {
       elem.setAttribute(attrName, attr[attrName]);
    }

    return elem;
}

function hydra_create_br() {
    return document.createElement('br');
}

function str_replace(search, replace, subject) {
    return subject.split(search).join(replace);
}

function hydra_elem_offset_x(obj) {
    var curleft = 0;
    if (obj.offsetParent) {
        while (1) {
            curleft+=obj.offsetLeft;
            if (!obj.offsetParent) {
                break;
            }
            obj=obj.offsetParent;
        }
    } else if (obj.x) {
        curleft+=obj.x;
    }
    return curleft;
}

function hydra_elem_offset_y(obj) {
    var curtop = 0;
    if (obj.offsetParent) {
        while (1) {
            curtop+=obj.offsetTop;
            if (!obj.offsetParent) {
                break;
            }
            obj=obj.offsetParent;
        }
    } else if (obj.y) {
        curtop+=obj.y;
    }
    return curtop;
}

function confirm_delete()
{
    return confirm("Вы уверены, что хотите удалить?");
}

/**
 * Функция применения изменений на формах.
 *
 * @param object btn кнопка применения изменений
 * @param string container_id контейнер формы
 * @param string plugin_name имя плагина стейта, который будет вызваться через ajax
 */
function apply_changes(btn, container_id, plugin_name)
{
    btn.disabled = true;
    draw_message(container_id+'.message', 'Изменения применяются');
    var params = get_input_values(container_id);

    call_ajax(plugin_name, container_id, params);
    btn.disabled = false;
    draw_message(container_id+'.message', 'Изменения применены.');
}

function hydra_refresh_page()
{
    location.reload();
}

/**
 * Применение действия
 * 
 * @param Object btn кнопка по которой щелкаем
 * @param string container_id идентификатор контейнера с элементами
 * @param string plugin_name имя плагина контроллера
 * @param string action имя экшена для контроллера
 * @param function json_callback каллбек функция обработчик
 */
function apply_action(btn, container_id, plugin_name, action, json_callback)
{
    btn.disabled = true; 
    draw_message(container_id + '.message', 'Изменения применяются');
    var params = get_input_values(container_id);
    if (!params) {
        btn.disabled = false;
        return;
    }
//debugger;
    params['s_action'] = action;
    
    if (json_callback) {
        return call_json(plugin_name, container_id, params, json_callback);
    }

    call_ajax(plugin_name, container_id + '.message', params);
}

function json_action(command)
{
    command.btn.disabled = true; 
    display_message(command.container_id + '.message', 'Изменения применяются');
    var params = get_input_values(command.container_id);
    if (!params) {
        command.btn.disabled = false;
        return;
    }

    params['s_action'] = command.action;
    
    return call_json(command.plugin_name, false, params, command.callback);
    
}

