
/**
 * Возвращает DOM-элемент по идентификатору
 * @param id
 * @return
 */
function $(id){
	return document.getElementById(id);
}

/**
 * Возвращает количество дочерних элементов определённого типа
 * @param parent id родительского DOM-элемента
 * @param child name дочерних DOM-элементов
 */
function count_child_elements(parent, child){
	var parent = $(parent);
	var childCount = parent.getElementsByTagName(child).length;
	return childCount;
}

/**
 * Переключает видимость DOM-элемента 
 * @param id
 * @return
 */
function toggle_display_block(id){
	if($(id).style.display == 'none'){
		 $(id).style.display = 'block';
	}else{
		 $(id).style.display = 'none';
	}
}

/**
 * Добавляет файл в качестве закачанного в поле с виджетом htmlupload
 *
 * @param string field_name имя поля
 * @param integer file_id идентификатор закачанного файла
 * @param string file_url URL, по которому доступен файл
 * @param string icon_url URL иконки
 */

function htmlupload_add_file(field_name,file_id,file_name,file_url,icon_url){
	files_container=parent.document.getElementById('field_'+field_name+'_uploaded_files');
	var element=parent.document.createElement('li');
	if(file_url!=""){
		element.innerHTML='<input type="hidden" name="'+field_name+'[]" value="'+file_id+'">\n\
							<img src="'+icon_url+'" class="icon16px replace-bullet">\n\
							<a href="'+file_url+'">'+file_name+'</a>\n\
							<img class="icon16px hotspot" onclick="this.parentNode.parentNode.removeChild(this.parentNode);" src="/img/cancel.png">';
	}else{
		element.innerHTML=file_name;
	}
	
	files_container.appendChild(element);
}

/**
 * Выполняет JS-код, полученный по указанному URL
 *
 * @param string script_url URL js скрипта, который необходимо выполнить
 */

function js_execute(script_url) {
    var html_doc = document.getElementsByTagName('head').item(0);
    var js = document.createElement('script');
    js.setAttribute('language', 'javascript');
    js.setAttribute('type', 'text/javascript');
    js.setAttribute('src', script_url);
    html_doc.appendChild(js);
	return false;
}

/**
 * Функция проверяет htmlupload поле на присутствие закачанных файлов
 *
 * @param string field_name имя поля
 * @return bool - true если поле пустое, false если поле содержит файлы
 */

function htmlupload_is_field_empty(field_name){
	if(count_child_elements('field_'+field_name+'_uploaded_files','li')){
		return false;
	}else{
		return true;
	}
}

/**
 * Возвращает объект XMLHTTP для AJAX-вызовов к серверу
 */

function get_xmlhttp(){
	var xmlhttp;
	try {
		xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
	}catch (e){
		try {
			xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
		}catch (E){
			xmlhttp = false;
		}
	}
	if (!xmlhttp && typeof XMLHttpRequest!='undefined') {
		xmlhttp = new XMLHttpRequest();
	}
	return xmlhttp;
}



function base64decode(input) {
	var keyStr = "ABCDEFGHIJKLMNOP" +
	"QRSTUVWXYZabcdef" +
	"ghijklmnopqrstuv" +
	"wxyz0123456789+/" +
	"=";

	var output = "";
	var chr1, chr2, chr3 = "";
	var enc1, enc2, enc3, enc4 = "";
	var i = 0;
	
	// remove all characters that are not A-Z, a-z, 0-9, +, /, or =
	var base64test = /[^A-Za-z0-9\+\/\=]/g;
	if (base64test.exec(input)) {
	alert("There were invalid base64 characters in the input text.\n" +
	"Valid base64 characters are A-Z, a-z, 0-9, '+', '/',and '='\n" +
	"Expect errors in decoding.");
	}
	input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
	
	do {
	enc1 = keyStr.indexOf(input.charAt(i++));
	enc2 = keyStr.indexOf(input.charAt(i++));
	enc3 = keyStr.indexOf(input.charAt(i++));
	enc4 = keyStr.indexOf(input.charAt(i++));
	
	chr1 = (enc1 << 2) | (enc2 >> 4);
	chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
	chr3 = ((enc3 & 3) << 6) | enc4;
	
	output = output + String.fromCharCode(chr1);
	
	if (enc3 != 64) {
	output = output + String.fromCharCode(chr2);
	}
	if (enc4 != 64) {
	output = output + String.fromCharCode(chr3);
	}
	
	chr1 = chr2 = chr3 = "";
	enc1 = enc2 = enc3 = enc4 = "";
	
	} while (i < input.length);
	
	return unescape(output);
}