/**
* Позволяет переместить выбранные элементы <select> element наверх
* 
* @param   object    объект, в котором нужно осуществить перемещение
* @param   integer   значение объекта который всегда находтся наверху
*/
                function moveSelectedUp(control_object, always_top) {
					
                   var new_select; //временно хранится select который меняется местами
                   var selected = new Array(); //хранятся страны, которые выделены
                   var not_selected = new Array(); //хранятся страны, которые еще не выделены
					
         
                   for (i=0,j=0,k=0; i < control_object.options.length; i++) {  
						if (control_object.options[i].selected||control_object.options[i].value==always_top) {
                			selected[k] = control_object.options[i];
                            k++;
						} else {
                	        not_selected[j] = control_object.options[i];
                            j++;
						};
                   };
                
                   for (i=0; i < not_selected.length; i++) {
                		control_object.appendChild(not_selected[i]);
                   }; 
                
                };  
					
	/**
	  * Checks/unchecks all options of a <select> element or group of checkboxes
	  *
	  * @param   string   'checkbox' or 'select'
	  * @param   string   the element name or id for select
	  * @param   boolean  whether to check or to uncheck the element
	  *
	  * @return  boolean  always true
	  */
	function setSelectOptions(control_type, name_id, do_check)
	{
		if (control_type == 'select') {
			var selectObject = document.getElementById(name_id);
		} else {
			var selectObject = document.getElementsByName(name_id);
		}
	    var selectCount  = selectObject.length;
		
	    for (var i = 0; i < selectCount; i++) {
			if (control_type == 'select') {
	        	selectObject[i].selected = do_check;
			} else {
			    selectObject[i].checked = do_check;
			}			
	    } // end for
	
	    return true;
	} // end of the 'setSelectOptions()' function
	
	function getCheckedElements(object_name) {
	
		var selectObject = document.getElementsByName(object_name);
		var selectCount  = selectObject.length;
		var checkedElements = new Array();
		var j = 0;

		if (selectObject != null) {
		    for (var i = 0; i < selectCount; i++) {
				if (selectObject[i].checked == true) {
	        		checkedElements[j] = selectObject[i];
					j++;
				} 		
		    } // end for	
		}	

		return checkedElements;
	}
	
	function getCheckedElementsText(object_name) {
	
		var selectObject = document.getElementsByName(object_name);
		var selectCount  = selectObject.length;
		var text = '';

		if (selectObject != null) {
		    for (var i = 0; i < selectCount; i++) {
				if (selectObject[i].checked == true) {
					text = text + '&'+object_name+'=' + selectObject[i].value;
				} 		
		    } // end for	
		}	

		return text;
	}	
	
	function getSelectedLabelsText(select_id) {
		countryControl = document.getElementById(select_id);
		var text = '';
		if (countryControl != null)
		  for (i=0; i < countryControl.options.length; i++) {  
		    if (countryControl.options[i].selected) {
				if (text != '') text = text + ', ';
				text = text + countryControl.options[i].text;
		    } 
		  }
		return text;
	}	
	
	function getSelectedValuesText(select_id) {
		countryControl = document.getElementById(select_id);
		var text = '';
		if (countryControl != null)
		  for (i=0; i < countryControl.options.length; i++) {  
		    if (countryControl.options[i].selected) {
				text = text + '&'+select_id+'[]=' + countryControl.options[i].value;
		    } 
		  }
		return text;
	}
	
	/*
	* Вохвращает для get-строки 2 массива - из всех значений контрола + массив выделенных
	*/
	function getValuesAndSelectedValuesText(select_id) {
		countryControl = document.getElementById(select_id);
		var text = '';
		if (countryControl != null)
		  for (i=0; i < countryControl.options.length; i++) {  
		  	text = text + '&'+select_id+'_values[]=' + countryControl.options[i].value;
		    if (countryControl.options[i].selected) {
				text = text + '&'+select_id+'[]=' + countryControl.options[i].value;
		    } 
		  }
		return text;
	}

	function countSelectedValues(select_id) {
		selectControl = document.getElementById(select_id);
		var c = 0;
		if (selectControl != null)
		  for (i=0; i < selectControl.options.length; i++) {  
		    if (selectControl.options[i].selected) {
				c++;
		    } 
		  }
		return c;
	}



/* $Id: features.js,v 1.1.1.1 2007/02/05 18:11:49 fslava Exp $ */

/**
* Позволяет пометить столбец в таблице
* 
* @param   object    объект таблицы, в которой все это происходит
* @param   integer   номер столбца по порядку слева направо, начиная с 0
* @param   string    the action calling this script (over, out or click)
* @param   string    the default background color
* @param   string    the color to use for mouseover
* @param   string    the color to use for marking a row
*/
function setColPointer(theTable, theColNum, theDefaultColor, theMarkColor) {

	//установить цвет на текущую колонку
    for (i=0; i < theTable.rows.length; i++) {

    	theRow = theTable.rows[i];
	if (typeof(document.getElementsByTagName) != 'undefined') {
        	theCells = theRow.getElementsByTagName('td');
    	}
    	else if (typeof(theRow.cells) != 'undefined') {
       		theCells = theRow.cells;
    	}
    	else {
        	return false;
    	}
	theCells[theColNum].setAttribute('bgcolor', theMarkColor, 0);
	if (marked_col != null && marked_col != theColNum && !marked_row[i]) {
		theCells[marked_col].setAttribute('bgcolor', theDefaultColor, 0);
	}
    }

    marked_col = theColNum; 
}

/**
 * Sets/unsets the pointer and marker in browse mode
 *
 * @param   object    the table row
 * @param   interger  the row number
 * @param   string    the action calling this script (over, out or click)
 * @param   string    the default background color
 * @param   string    the color to use for mouseover
 * @param   string    the color to use for marking a row
 *
 * @return  boolean  whether pointer is set or not
 */
function setPointer(theRow, theRowNum, theAction, theDefaultColor, thePointerColor, theMarkColor)
{
    var theCells = null;
	theRowNum = theRow.rowIndex;

	
    // 1. Pointer and mark feature are disabled or the browser can't get the
    //    row -> exits
    if ((thePointerColor == '' && theMarkColor == '')
        || typeof(theRow.style) == 'undefined') {
        return false;
    }

    // 2. Gets the current row and exits if the browser can't get it
    if (typeof(document.getElementsByTagName) != 'undefined') {
        theCells = theRow.getElementsByTagName('td');
    }
    else if (typeof(theRow.cells) != 'undefined') {
        theCells = theRow.cells;
    }
    else {
        return false;
    }

    // 3. Gets the current color...
    var rowCellsCnt  = theCells.length;
    var domDetect    = null;
    var currentColor = null;
    var newColor     = null;
    // 3.1 ... with DOM compatible browsers except Opera that does not return
    //         valid values with "getAttribute"
    
/*    if (typeof(window.opera) == 'undefined'&& typeof(theCells[0].getAttribute) != 'undefined') {
        currentColor = theCells[0].getAttribute('bgcolor');
        domDetect    = true;
    }
    // 3.2 ... with other browsers
    else {
        currentColor = theCells[0].style.backgroundColor;
        domDetect    = false;
    } // end 3 */

    currentColor = theCells[0].style.backgroundColor;
    domDetect    = false;

    // 3.3 ... Opera changes colors set via HTML to rgb(r,g,b) format so fix it
    if (currentColor.indexOf("rgb") >= 0) 
    {
        var rgbStr = currentColor.slice(currentColor.indexOf('(') + 1,
                                     currentColor.indexOf(')'));
        var rgbValues = rgbStr.split(",");
        currentColor = "#";
        var hexChars = "0123456789ABCDEF";
        for (var i = 0; i < 3; i++)
        {
            var v = rgbValues[i].valueOf();
            currentColor += hexChars.charAt(v/16) + hexChars.charAt(v%16);
        }
    }

    // 4. Defines the new color
    // 4.1 Current color is the default one
    if (currentColor == ''
        || currentColor.toLowerCase() == theDefaultColor.toLowerCase()) {
        if (theAction == 'over' && thePointerColor != '') {
            newColor              = thePointerColor;
        }
        else if (theAction == 'click' && theMarkColor != '') {
            newColor              = theMarkColor;
            marked_row[theRowNum] = true;
        }
    }
    // 4.1.2 Current color is the pointer one
    else if (currentColor.toLowerCase() == thePointerColor.toLowerCase()
             && (typeof(marked_row[theRowNum]) == 'undefined' || !marked_row[theRowNum])) {
        if (theAction == 'out') {
            newColor              = theDefaultColor;
        }
        else if (theAction == 'click' && theMarkColor != '') {
            newColor              = theMarkColor;
            marked_row[theRowNum] = true;
        }
    }
    // 4.1.3 Current color is the marker one
    else if (currentColor.toLowerCase() == theMarkColor.toLowerCase()) {
        if (theAction == 'click') {
            newColor              = (thePointerColor != '')
                                  ? thePointerColor
                                  : theDefaultColor;
            marked_row[theRowNum] = (typeof(marked_row[theRowNum]) == 'undefined' || !marked_row[theRowNum])
                                  ? true
                                  : null;
        }
    } // end 4

    // 5. Sets the new color...
    if (newColor) {
        var c = null;
        // 5.1 ... with DOM compatible browsers except Opera
        if (domDetect) {
            for (c = 0; c < rowCellsCnt; c++) {
                if (c != marked_col) { 
					theCells[c].setAttribute('bgcolor', newColor, 0);
				}	
            } // end for
        }
        // 5.2 ... with other browsers
        else {
            for (c = 0; c < rowCellsCnt; c++) {
                theCells[c].style.backgroundColor = newColor;
            }
        }
    } // end 5

    return true;
} // end of the 'setPointer()' function

function trim(inputString) {
	// Removes leading and trailing spaces from the passed string. Also removes
	// consecutive spaces and replaces it with one space. If something besides
	// a string is passed in (null, custom object, etc.) then return the input.
	if (typeof inputString != "string") { return inputString; }
	var retValue = inputString;
	var ch = retValue.substring(0, 1);
	while (ch == " ") { // Check for spaces at the beginning of the string
		retValue = retValue.substring(1, retValue.length);
		ch = retValue.substring(0, 1);
	}
	ch = retValue.substring(retValue.length-1, retValue.length);
	while (ch == " ") { // Check for spaces at the end of the string
		retValue = retValue.substring(0, retValue.length-1);
		ch = retValue.substring(retValue.length-1, retValue.length);
	}
	
	return retValue; // Return the trimmed string back to the user
} // Ends the "trim" function

/*
Добавляет обработчик события для указанного элемента. Используется 
addEventListener для Мозиллы или attachEvent для эксплорера. Это значит, что можно
добавлять различные обработчики для одного и того же элемента, одного и того же события
и они будут вызваны по порядку.
Для очень старых броузеров, которые не поддерживают функции addEventListener и attachEvent
используется старый метод, который просто перекрывает старое событие.
@param object [HTMLElement] ссылка на элемент
@param evname [string] название события, без префикса 'on'
@param func функция обработки события

пример вызова: addEvent(window.document,'mouseup',div1handler)
*/
function addEvent(object, evname, func) {
	if (object.attachEvent) { // IE
		object.attachEvent("on" + evname, func);
	} else if (object.addEventListener) { // Gecko / W3C
		object.addEventListener(evname, func, true);
	} else {
		object["on" + evname] = func;
	}
};	

// Выдает код нажатой клавиши 
function GetKeyCode (e) {
	var key;
	e = e || event;
	key	= e.charCode || e.keyCode;
	return key;
}

function switchCursor (object,direction) {
	var bodyCursor; //вид курсора для body
	var hrefCursor; //вид курсора для ссылок
	var disable; //скрывать или показывать div
	var pos; 
	
	if (direction == 'wait') {
		bodyCursor = 'wait'; 
		hrefCursor = 'wait'; 
		disable = true;
	} else {
		bodyCursor = 'default'; 
		hrefCursor = 'pointer'; 	
		disable = false;
	}

	/* У нас 2 типа объектов, у которых меняется курсор. Это страница целиком
	и подгружаемые части страницы. Согда мы поменяли курсор у подгруженного содержимого,
	а в самом конце вернули курсор в исходное состояние у всей страницы, измененные 
	искуственно курсоры не возвращаются на место. Поэтому нужно запомнить те элементы,
	у которых сурсоры менялись при подгрузке и при окончательном снятии курсора
	вручную изменть и их.
	*/	
	if (object == document.body) {
		if (bodyCursor == 'default'&&window.cursorSwitchedDivs != null) {
			for (i=0; i < window.cursorSwitchedDivs.length; i++) { 
				window.cursorSwitchedDivs[i].style.cursor = bodyCursor;
			}
			window.cursorSwitchedDivs = null;
		}
	} else {
		if (window.cursorSwitchedDivs == null)
			window.cursorSwitchedDivs = new Array();
		pos = window.cursorSwitchedDivs.length;
		window.cursorSwitchedDivs[pos] = object;
	}
	//переключаем курсок основного объекта
	object.style.cursor = bodyCursor;
	//переключение селектов
	arrayCollection = object.getElementsByTagName('select');
	for (i=0; i < arrayCollection.length; i++) {  
		if (disable&&arrayCollection[i].disabled) {
			arrayCollection[i].disabledBeforeWait = true; 
		}	
		if (!disable&&arrayCollection[i].disabledBeforeWait) 
			arrayCollection[i].disabledBeforeWait = false;
		else arrayCollection[i].disabled = disable;

	};
	//переключение линков
	arrayCollection = object.getElementsByTagName('a');
	for (i=0; i < arrayCollection.length; i++) {  
		arrayCollection[i].style.cursor = hrefCursor;
	};	

}

/* Используется для отмены обработки события по Enter */
function cancelEnter(e) {
	var key;
	key= e.charCode || e.keyCode;	

	if (key == 13) {
		e.returnValue = false;
		return false;
	} else {
		return true;
	}
	
}

/* Функция находит среди дочерних элементов любой элемент формы и возвращает его
Она рекурсивная.
oColl - коллекция дочерних элементов
возвращает элемент формы, либо null если не найдено
*/
function getFormElementChild(oColl) {

	for(x=0;x<oColl.length;x++){
		if (oColl[x].tagName == 'SELECT'||oColl[x].tagName == 'INPUT') {
			//alert(oColl[x].tagName);
			return oColl[x];
		} else {
			if (oColl.children != null) {
				$tempRes = getFormElementChild(oColl.children);
				if ($tempRes != null) {
					return $tempRes;
				} 
			}
		}
	}
	
	return null;
}
