if (self.parent.frames.length != 0)
	self.parent.location.replace(document.location.href);

function em(box, server, zone) {
	var at = String.fromCharCode(64);
	document.write('<a href="'+'mai'+'lto'+':'+box+at+server+'.'+zone+'">'+box+at+server+'.'+zone+'<'+'/a>');
}

function show_projects() {
	document.getElementById('projects_selector').style.display = "block";
	return false;
}

/*** ADD EQUIPMENT SELECTOR **************************************************/
var add_selector_last = null;
function add_selector_click(type) {
	var obj = document.getElementById("add-selector-"+type);
	if (add_selector_last) {
		document.getElementById("add-selector-"+add_selector_last).className = 'selector';
		document.getElementById("add-selector-data-"+add_selector_last).className = '';
	}
	if (obj) {
		obj.className = 'selector current';
		document.getElementById("add-selector-data-"+type).className = 'current';
		add_selector_last = type;
	}
	document.getElementById("submit-button").style.display = 'block';
	document.getElementById("form-data-type").value = type;
	return false;
}

function check_add_equipment_form(form) {
	var type_tabs = $('.tab-equipment-type > ul').tabs(),
		content_tabs = $('.tab-equipment-content > ul').tabs();
	var tab_type_index = type_tabs.tabs('option', 'selected'),
		tab_content_index = content_tabs.tabs('option', 'selected');

	form['tab-type'].value = tab_type_index;
	form['tab-content'].value = tab_content_index;

	var controls_type = tab_type_index == 0 ? 
		new Array("eq_folder_id") :
		new Array("eq_new_folder");
	var controls_content = tab_content_index == 0 ? 
		new Array("eq_name", "eq_producer", "eq_description", "eq_specification") :
		new Array("eq_www");

	return process_check(form, controls_type.concat(controls_content));
}

function check_eq_folder_id(form) {
	return true;
}

function check_eq_new_folder(form) {
	return check_length(form, "eq_new_folder", 2, -1, "Укажите наименование типа оборудования");
}

function check_eq_name(form) {
	return check_length(form, "eq_name", 2, -1, "Поле наименования оборудования не может быть пустым");
}

function check_eq_producer(form) {
	return check_length(form, "eq_producer", 2, -1, "Производитель оборудования является обязательным для указания");
}

function check_eq_description(form) {
	return check_length(form, "eq_description", 2, -1, "Сообщите нам о назначении оборудования в виде краткого описания");
}

function check_eq_specification(form) {
	return check_length(form, "eq_specification", 2, -1, "Должны быть указаны технические характеристики");
}

function check_eq_www(form) {
	return check_urlformat(form, "eq_www", "Укажите адрес страницы с описанием оборудования");
}

/*** LOGIN *******************************************************************/
function set_login_form_position() {
	var coord, form, icon;
	form = document.getElementById('login-form');
	icon = document.getElementById('icon-login');
	if (icon && form) {
		coord = get_position(icon);
		form.style.top = (coord["y"]+17)+"px";
		form.style.left = (coord["x"]-180)+"px";
	}
}
function toggle_login_form() {
	set_login_form_position();
	if ($('#login-form').is(":visible")) {
		$('#login-form').hide();
	} else {
		$('#login-form').show();
		$('#login-form input[name=login]').focus();
	}

	return false;
}

function toggle_remind_form() {
	$("#remind-password-trigger").hide();
	$("#main-login-form").hide();
	$("#remind-password-form").show();
	$("#remind-password-form input[name=remindlogin]").focus();
	return false;
}

function get_position(obj) {
	var coord = {x:0, y:0};
	do {
		coord["x"] += obj.offsetLeft;
		coord["y"] += obj.offsetTop;
		if (/^div$/i.test(obj.tagName)) {
			if (obj.scrollLeft)	coord["x"] -= obj.scrollLeft;
			if (obj.scrollTop)	coord["y"] -= obj.scrollTop;
		}
		obj = obj.offsetParent;
	} while(obj);
	return coord;
}

/*** FORM SUBMIT **************************************************************/
function check_login_form(form) {
	return process_check(form, new Array("login", "password"));
}

function check_remind_form(form) {
	return process_check(form, new Array("remindlogin"));
}

function check_register_form(form) {
	return process_check(form, new Array("login", "email", "name", "company", "company_type", "geo_id", "address", "phone"));
}

function check_login(form) {
	var re = /^[a-z]([a-z0-9\-\.]{2,15})$/i;
	if (!re.test(form.login.value)) {
		if (!message_present) {
			alert("Укажите желаемый логин, состоящий из латинских символов, цифр, знака подчеркивания или дефиса (3-16 символов)");
			message_present = true;
		}
		highlight_control(form.login, !message_present);
		return false;
	}
	return true;
}

function check_email(form) {
	return check_emailformat(form, "email", "Укажите существующий адрес электронной почты");
}

function check_name(form) {
	return check_length(form, "name", 4, 64, "Заполните поле с именем");
}

function check_company(form) {
	return check_length(form, "company", 4, 64, "Заполните поле наименования организации");
}

function check_company_type(form) {
	if (!(form.type_producer.checked || form.type_seller.checked || form.type_buyer.checked || form.type_service.checked)) {
		if (!message_present) {
			alert("Укажите одно или несколько направлений деятельности организации");
			message_present = true;
		}
		highlight_control(form.company_type, !message_present);
		return false;
	}
	return true;
}

function check_geo_id(form) {
	if (form.geo_id.value==0) {
		if (!message_present) {
			alert("Выберите город");
			message_present = true;
		}
		highlight_control(form.geo_id, !message_present);
		return false;
	}
	return true;
}

function check_phone(form) {
	return check_length(form, "phone", 4, 64, "Укажите контактный телефон");
}

function check_address(form) {
	return check_length(form, "address", 4, -1, "Заполните поле с адресом");
}

function check_password(form) {
	return check_length(form, "password", 3, 16, "Введите пароль");
}

function check_remindlogin(form) {
	var re = /^[a-z]([a-z0-9\-\.]{2,15})$/i;
	if (!(is_valid_email(form.remindlogin.value) || re.test(form.remindlogin.value))) {
		if (!message_present) {
			alert("Укажите зарегистрированный логин или соответствующий логину электронный адрес");
			message_present = true;
		}
		highlight_control(form.remindlogin, !message_present);
		return false;
	}
	return true;
}

/*** GEO *********************************************************************/
var geoClickedIndex = 0;

function RequestGeoList(type, id) {
	ToggleGeoLoading(true);
	geoClickedIndex = type;
	DropSelectsAfter(geoClickedIndex);
	$.get('/ajax/geo/', {id: id}, function(data){ParseResponceGeo(data);}, "text");
}

function ParseResponceGeo(data) {
	ToggleGeoLoading(false);
	if (data.length > 0) {
		var select, pair, list;

		if (!$('#geo'+geoClickedIndex).length)
			$('#geo-container').append('<select id="geo'+geoClickedIndex+'" size="12" onchange="javascript:RequestGeoList('+(geoClickedIndex+1)+', this.options[this.selectedIndex].value)"></select>');

		list = data.split(";");
		for (var i=0; i<list.length; i++) {
			pair = list[i].split(":");
			$('#geo'+geoClickedIndex).append('<option value="'+pair[0]+'">'+pair[1]+'</option>');
		}
	} else {
		$('#selected-geo-popup').text($('#geo'+(geoClickedIndex-1)+' option:selected').text());
		$('#geo-submit').removeAttr('disabled');
		var select = $('#geo'+geoClickedIndex);
   	    if (select)
   	    	select.remove();
	}
}

function GeoSelectorOk() {
	select = $('#geo'+(geoClickedIndex-1)+' option:selected');
	SetGeoSelection(select.val(), select.text());
	GeoSelectorHide();
}

function DropSelectsAfter(type) {
	var select;
    for (var i=10; i>type; i--){
        select = $('#geo'+i);
        if (select)
	        select.remove();
    }
	$('select#geo'+type+' option').remove();
}

function ToggleGeoLoading(in_progress) {
	if (in_progress)
		$('#geo-loading').show();
	else
		$('#geo-loading').hide();
	$('#geo-submit').attr('disabled', 'disabled')
	$('#selected-geo-popup').html('&nbsp;');
}

function RequestGeoCurrentRegion(ip) {
	$.get('/ajax/geo/', {ip: ip}, function(data){ParseResponceGeoCurrentRegion(data);}, "text");
}

function ParseResponceGeoCurrentRegion(data) {
	var pair = data.split(";");
	if (pair.length == 2) {
		SetGeoSelection(pair[0], pair[1]);
		$('#geo-current-region-control').innerText = 'изменить';		
	}
}

function SetGeoSelection(id, name) {
	$('#geo-current-region-id-input').attr('value', id);
	$('#geo-current-region-name-input').attr('value', name);
	$('#geo-current-region').text(name);
}

/*** EVENTS ******************************************************************/
function add_event_listener_element(element, event, func) {
	if (element.addEventListener)
		element.addEventListener(event, func, false);
	else if (element.attachEvent)
		element.attachEvent("on"+event, func);
	else
		return false;
	return true;
}

function add_event_listener(event, func) {
	var root_listener = window.addEventListener || window.attachEvent ? window : document.addEventListener ? document : null;
	if (!root_listener)
		return false;
	return add_event_listener_element(root_listener, event, func);
}

add_event_listener("resize", set_login_form_position);

$(document).ready( function() {
	if ($('input:password').length)
		$('input:password').each(function(){$(this).dPassword();});
});