/**
* Возвращает значения из элементов ввода, содержащихся
* @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
                        //alert('Немогу найти контейнер '+form_validator.get_error_container_id());
		}
                else{
                    var error_container = document.getElementById(form_validator.get_error_container_id());
                    if (error_container)
                        error_container.innerHTML = form_validator.get_message();
                   // else
                        //alert('Немогу найти контейнер '+form_validator.get_error_container_id());
                }

			//alert('name='+collection[i].name+'type='+collection[i].type);	
			// обработка чекбоксов
			if (collection[i].type == 'checkbox')
			{
				var c = collection[i].getAttribute('confirm');
				//alert('c is '+c+' for type'+collection[i].type+' and name '+collection[i].name);
				if (collection[i].getAttribute('confirm')==null)
				{
					if (collection[i].checked) 
					{
						params[collection[i].name] = 1;
					}
					else 
					{
						
						if (collection[i].type=='checkbox')
						{
							//alert('set for name '+collection[i].name+' and type'+collection[i].type+' to zero');
							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') 
			{
				/* debug
				*/
				//var dis = collection[i].getAttribute('disabled');
				//alert('ff disabled for : '+collection[i].name+' is '+dis);


				//if (collection[i].getAttribute('disabled')==null || collection[i].getAttribute('disabled')=='false')
				//alert('check :'+collection[i].name);
				if ( !is_elem_disabled( collection[i] ) )
				{
					//alert('ff value is '+collection[i].value);
					//var val = collection[i].getAttribute('value');
					//alert('for stupid ie value may be like '+val);
					
					params[collection[i].name] = collection[i].value;
					//alert('put to params name '+collection[i].name+' value '+collection[i].value);
				}
			}

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

			//  && (collection[i].getAttribute('confirm')==null)
			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('Введенные пароли не совпадают.');
							}
						}
					}
				}
			}


		}

	}
	
	
	
	
	
	
	
	
	
	
	

	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;
		}
	}

	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 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) {
    var elem = document.getElementById(container_id);
    if (elem) {
        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_id) {
    var elem = get_element(elem_id);
    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', 'Изменения применены.');
}