// updated: 29.01.2010 23:30

//=========================== Helpers ==========================================

// Determine whether a variable is empty
function empty( mixed_var ) {
     return ( mixed_var === "" || mixed_var === 0 || mixed_var === "0" || mixed_var === null || mixed_var == undefined || mixed_var === false || ( is_array(mixed_var) && mixed_var.length === 0 ) );
}

function is_numeric(mixed_var) {
    return !isNaN(mixed_var);
}

function is_array(mixed_var) {
	return ( (typeof mixed_var == 'object') && (mixed_var instanceof Array) );
}

function is_object( mixed_var ){
    if (mixed_var instanceof Array) {
        return false;
    } else {
        return ( (mixed_var !== null) && (typeof mixed_var == 'object') );
    }
}

function is_empty_object(object) {
     for (var i in object) {
	    return false;
     }
     return true;
}

function in_array(needle, haystack, strict) {
    var found = false;
    strict = !!strict;
    for (var key in haystack) {
        if ((strict && haystack[key] === needle) || (!strict && haystack[key] == needle)) {
            found = true;
            break;
        }
    }
    return found;
}

function checkSelectValue(select_id) {
	select = document.getElementById(select_id);
	if ( (select.value == 0) || (select.value == '') ) {
		window.alert('Ошибка! Значение не выбрано');
		return false;
	} else {
		return true;
	}
}

function addEvent(elm, evType, fn, useCapture) {
	if (elm.addEventListener) {
		elm.addEventListener(evType, fn, useCapture);
        return true;
	} else if (elm.attachEvent) {
		return elm.attachEvent('on' + evType, fn);
	} else {
		elm['on' + evType] = fn;
	}
}

function stopEvent(event, prevent_default) {
	if (typeof prevent_default == 'undefined') {
		prevent_default = true;
	}
	// Отменяем стандартный обработчик событмя
	if (prevent_default) {
		// Для ФФ
		if (event.preventDefault) {
			event.preventDefault();
		// Для ИЕ
		} else {
			event.returnValue = false;
		}
	}
	// Отменяем "всплытие" события
	// Для ФФ
	if (event.stopPropagation) {
		event.stopPropagation();
	// Для ИЕ
	} else {
		event.cancelBubble = true;
	}
}

function toggle(obj) {
	var el = document.getElementById(obj);
	if ( el.style.display != 'none' ) {
		el.style.display = 'none';
	} else {
		el.style.display = '';
	}
}

function extend(child, parent) {
	if (typeof child == 'function') {
		if (typeof parent == 'function') {
			var p = new parent;
			var prototype = child.prototype;
			child.prototype = p;
			if (typeof prototype != 'undefined') {
				for (var i in prototype) {
					if (prototype.hasOwnProperty(i)) {
						child.prototype[i] = prototype[i];
					}
				}
			}
			parent.prototype.constructor = parent;
			child.parent = parent.prototype;
			child.prototype.__parent = child.parent;
		} else {
			throw('Wrong parent constructor set: "' + parent + '"');
		}
	} else {
		throw('Wrong child constructor set: "' + child + '"');
	}
}

function extendByProperty(child) {
	if (typeof child.prototype.__extends != 'undefined') {
		if (child.prototype.__is_extended !== true) {
			extendByProperty(child.prototype.__extends);
			extend(child, child.prototype.__extends);
			child.prototype.__is_extended = true;
		}
	}
}

function compareObjects(obj1, obj2, depth, result) {
    depth = depth || 0;
    result = result || {};
    for (var i in obj1) {
	  if (typeof obj1[i] == 'object') {
		if (typeof obj2[i] == 'object') {
		    if (depth > 0) {
			  compare_objects(obj1, obj2, depth - 1, result);
		    }
		} else {
		    result[i] = {
			  'obj1': obj1[i],
			  'obj2': obj2[i]
		    };
		}
	  } else if  (obj1[i] != obj2[i]) {
		result[i] = {
		    'obj1': obj1[i],
		    'obj2': obj2[i]
		};
	  }
    }
    return result;
}

//=========================== Ajax functions ===================================

var requests_counter = 0;

function ajaxRequest(url, params, handler, handler_params) {
	if (url) {
		url = 'http://' + window.location.host + url;
		var req = new JsHttpRequest();
		req.onreadystatechange = function() {
			if (req.readyState == 4) {
				clearTimeout(timeout_id);
				requests_counter--;
				if ( (req.responseJS) && (!req.responseText) ) {
					if (handler) {
						handler(req.responseJS, handler_params);
					}
					if (requests_counter < 1) {
						loadingOff();
					}
				} else {
					if (requests_counter < 1) {
						loadingOff();
					}
					if (req.responseText) {
						window.alert('Ajax error');
						if (console.log) {
							console.log(req.responseText);
						}
					}
				}
			}
		}
		loadingOn();
		requests_counter++;
		req.open(null, url, true);
		req.send(params);
		var timeout = ( (handler_params) && (handler_params.timeout) )
					  ? (handler_params.timeout)
					  : (10);
		var timeout_id = setTimeout(function() { ajaxAbort(req); }, timeout * 1000);
	}
}

function ajaxRequestByUrlParts(url_parts, params, handler, handler_params) {
	if (url_parts) {
		url_parts.type = 'ajax';
		var url = makeLink(url_parts);
		if (url) {
			ajaxRequest(url, params, handler, handler_params);
		}
	}
}

function ajaxPostRequestByUrlParts(url_parts, commit_name, params, handler, handler_params) {
	if (commit_name) {
		new_params = {commit: [], data: params};
		new_params.commit[commit_name] = true;
		ajaxRequestByUrlParts(url_parts, new_params, handler, handler_params);
	} else {
		window.alert('Empty commit_name');
	}
}

function ajaxAbort(request) {
     if (request) {
	    requests_counter--;
	    request.abort();
	    window.alert('Превышено время ожидания ответа от сервера. Попробуйте еще раз.');
     }
    if (requests_counter < 1) {
	   loadingOff();
    }
}

function ajaxIsResponeErrors(response) {
     return (
	    (typeof response.errors != 'undefined')
	    &&
	    (response.errors !== null)
	    &&
	    ( (typeof response.errors != 'array') || (response.errors.length > 0) )
     )
}

//=========================== Ajax loading functions ===========================

function loadingOn() {
	createLoadingBlocks();
	document.getElementById('loading_image').style.display = 'block';
	document.getElementById('loading_lock').style.display = 'block';
	document.body.style.cursor='wait';
}

function loadingOff() {
	createLoadingBlocks();
	document.getElementById('loading_image').style.display = 'none';
	document.getElementById('loading_lock').style.display = 'none';
	document.body.style.cursor='auto';
}

function toggleLoading() {
	createLoadingBlocks();
	if (document.getElementById('loading_image').style.display == 'none') {
		loadingOn();
	} else {
		loadingOff();
	}
}

function createLoadingBlocks() {
	createLoadingImageDiv();
	createLoadingLockDiv();
}

function createLoadingImageDiv() {
	var divElement = document.getElementById('loading_image');
	if (!divElement) {
		divElement = document.createElement('DIV');
		divElement.setAttribute('id', 'loading_image');
		divElement.innerHTML = '<img src="/img/loading.gif" width="100" height="100" style="border: 1px solid black;" />';
		divElement.style.position = 'absolute';
		divElement.style.overflow = 'hidden';
		divElement.style.zIndex = 999;
		divElement.style.display = 'none';
		document.body.appendChild(divElement);
	}
	var divTop = Math.round((document.body.clientHeight - divElement.offsetHeight)/2) + document.body.scrollTop;
	var divLeft = Math.round((document.body.clientWidth - divElement.offsetWidth)/2) + document.body.scrollLeft;
	divElement.style.top = divTop + 'px';
	divElement.style.left = divLeft + 'px';
	return divElement;
}

function createLoadingLockDiv() {
	var divElement = document.getElementById('loading_lock');
	if (!divElement) {
		divElement = document.createElement('DIV');
		divElement.setAttribute('id', 'loading_lock');
		divElement.style.position = 'absolute';
		divElement.style.overflow = 'hidden';
		divElement.style.top = '0px';
		divElement.style.left = '0px';
		divElement.style.opacity = '0.2';
		divElement.style.filter = 'alpha(opacity=20)';
		divElement.style.backgroundColor = '#000000';
		divElement.style.zIndex = 998;
		divElement.style.display = 'none';
		if ( (navigator.userAgent.indexOf("MSIE 5") != -1) || (navigator.userAgent.indexOf("MSIE 6") != -1) ) {
			var iframeElement = document.createElement('IFRAME');
			iframeElement.style.display = 'block';
			iframeElement.style.position = 'absolute';
			iframeElement.style.top = 0;
			iframeElement.style.left = 0;
			iframeElement.style.zIndex = -1;
			iframeElement.style.filter = 'mask()';
			iframeElement.style.width = '3000px';
			iframeElement.style.height = '3000px';
			divElement.appendChild(iframeElement);
		}
		document.body.appendChild(divElement);
	}
	divElement.style.width = document.body.scrollWidth + 'px';
	divElement.style.height = document.body.scrollHeight + 'px';
	return divElement;
}

//==============================================================================
//=========================== XT functions =====================================
//==============================================================================

//=========================== Links functions ==================================

function makeLink(params) {
	if ( (!empty(params.module)) || (!empty(params.controller)) && (!empty(params.action)) ) {
		var link = [];
		if (!empty(params.controller)) {
			link.push(params.controller);
		}
		if (!empty(params.module)) {
			link.push(params.module);
		}
		if ( (!empty(params.id)) && (is_numeric(params.id)) ) {
			link.push(params.id);
		} else if ( (!empty(params.alias)) && (!is_numeric(params.alias)) ) {
			link.push(params.alias);
		}
		if ( (!empty(params.action)) && (!in_array(params.action, ['index', '__default', 'view'])) ) {
			link.push(params.action);
		}
		if (!empty(params.param1)) {
			link.push(params.param1);
		}
		if (!empty(params.param2)) {
			link.push(params.param2);
		}
		if (empty(params.dir_only)) {
			var type = params.type || 'html';
			if ( (empty(params.page_number)) || (params.page_number == 1) ) {
				if (type != 'html') {
					link.push('index.' + type);
				}
			} else {
				link.push('page' + params.page_number + '.' + type);
			}
		}
		// Проверяем, явялется ли последняя часть именем файла
		if (link[link.length - 1].indexOf('.') > 0) {
			return '/' + link.join('/');
		} else {
			return '/' + link.join('/') + '/';
		}
	} else {
		window.alert('Not enough params to make a link');
		return false;
	}
}

//=========================== Actions functions ================================

function showActions(event, module, id, current_action) {
	event = event || window.event;
	var target = event.target || event.srcElement;
	if (module) {
		var list = null;
		var list_name = (id) ? ('act_' + module + '_' + id) : ('act_' + module);
		if (!((list = $('#' + list_name)).length)) {
			list = $("<ul/>")
					.hide()
					.attr("id", list_name)
					.addClass("actions_list")
					.bind('mouseleave', function() { $(this).hide('normal'); });
			var not_loaded = true;
		}
		var offset = $(target).offset();
		list.css('top', offset.top + target.offsetHeight + 5);
		list.css('left', offset.left);
		if (not_loaded) {
			hideAllActionsLists();
			loadActions(list, module, id, current_action);
		} else if (list.is(':visible')) {
			list.hide('normal');
		} else {
			hideAllActionsLists();
			list.show('normal');
		}
	}
}

function hideAllActionsLists() {
	$('.actions_list', $('body')).hide();
}

function loadActions(list, module, id, current_action) {
	if (list && module) {
		var params = { controller: 'admin', module: module };
		if (id) {
			params.id = id;
			params.action = 'entity_actions';
		} else {
			params.action = 'module_actions';
		}
		ajaxRequestByUrlParts(params, null, function(result) { setActions(list, result, current_action); });
	}
}

function setActions(list, result, current_actions) {
	if (list && result.actions) {
		if (result.actions.length !== 0) {
			var in_admin = null;
			for (key in result.actions) {
				var action = result.actions[key];
				action.title = action.title || action.menu_text;
				var onclick_code = '';
				if (action.ask) {
					onclick_code = 'onclick="confirmAction(\'' + action.url + '\', \'' + action.menu_text + '\');"';
					action.url = 'javascript:void(0);';
				}
				if (in_admin != action.in_admin) {
					if (in_admin !== null) {
						list.append('<li><hr></li>');
					}
					in_admin = action.in_admin;
				}
				list.append('<li><a href="' + action.url + '" title="' + action.title + '" ' + onclick_code + '>' + action.menu_text + '</a></li>');
			}
		} else {
			list.append('<li>Нет доступных действий</li>');
		}
		list.appendTo('body');
		list.show('normal');
	}
}

function confirmAction(url, menu_text) {
	var confirm_text = 'Вы действительно хотите выполнить ' + menu_text + ' для этого элемента?';
	if (window.confirm(confirm_text)) {
		location.href = url;
	} else {
		return false;
	}
}

function processActionsLinks(container, module_name) {
	if (container) {
		var links = $('*[data-module], *[data-id]', container).not('[data-processed]');
		links.click(function(event) {
			module_name = $(this).attr('data-module') || module_name;
			var id = $(this).attr('data-id') || null;
			if (module_name) {
				showActions(event, module_name, id)
			}
			return false;
		});
		links.filter('a').attr('href', 'javascript:void(0);');
		links.filter('a').attr('title', 'Показать доступные действия для данного объекта');
		links.attr('data-processed', true);
	}
}

//=========================== Maps functions ===================================

function mapsGetCenter(center_lat, center_lng) {
	return new GLatLng(center_lat||50.000000, center_lng||36.260000);
}

function mapsGetApi(map_element_id, map_center, map_zoom) {
	var map = new GMap2(document.getElementById(map_element_id));
	map.setCenter(map_center || mapsGetCenter(), map_zoom || 13);
	map.setUIToDefault();
	$('body').unload(GUnload);
	return map;
}

function mapAddKs(map, ks) {
	if ( (ks.lat != '0.000000') && (ks.lng != '0.000000') ) {
		var marker = new GMarker(new GLatLng(ks.lat, ks.lng));
		GEvent.addListener(marker, "click", function() {
			marker.openInfoWindowHtml('<strong>' + ks.name + '</strong><br /><a href="' + ks.url + '">Подробнее...</a>');
		});
		map.addOverlay(marker);
	}
}

function mapAddBusSuburbanStop(map, stop) {
	if ( (ks.lat != '0.000000') && (ks.lng != '0.000000') ) {
		var marker = new GMarker(new GLatLng(ks.lat, ks.lng));
		GEvent.addListener(marker, "click", function() {
			marker.openInfoWindowHtml('<strong>' + ks.name + '</strong><br /><a href="' + ks.url + '">Подробнее...</a>');
		});
		map.addOverlay(marker);
	}
}

//==============================================================================
