﻿function _g_init(){
	document.onclick=_mnuHide;
	window.onresize=_mnuHide;
	document.onkeydown = _global_key_check;
	_g_extend_prototype();
	_l_page_onload();
	ie6_png();
	g_el.call();

	if (readCookie('trans_mode')=='on') _trans_attach();
	
}

function _trans_toggle() {
	s = readCookie('trans_mode');
	if (s == null || s == 'off')
		createCookie('trans_mode', 'on', 10);
	else
		createCookie('trans_mode', 'off', 10);
	reload();
}

function _trans_attach() {
	$$('font.trans', 'font.trans_x').each(function(el) {
	el.observe('mouseover', _trans_show_hint);
	el.observe('mouseout', _trans_hide_hint);
	}
	);
}
function _trans_show_hint(event) {
	var element = Event.element(event);
	var id = element.id.replace('tr', '');
	_trans_hide_hint();
	setTimeout(function() { element.addClassName('trans_selected') }, 200);
	_hint(event, element, 'bottom', '<a href="javascript:_g_al_lang_edit('+id+');">редактировать перевод</a>', null, 200, 10000, 10, 5)
}
function _trans_hide_hint() {
	$$('font.trans_selected').each(function(el) { el.removeClassName('trans_selected'); });
}

var _t_copy_lang = '';
var _t_copy_text = '';
function _t_copy(lang, id) {_t_copy_lang = lang;_t_copy_text = $(id).value;}
function _t_paste(lang, id) {
	if (_t_copy_text != '') {
		google.language.translate(_t_copy_text, _t_copy_lang, lang, function(result) {
			if (!result.error) {
				var s = result.translation;
				s = s.replace('% 1', ' %1');
				s = s.replace('% 2', ' %2');
				s = s.replace('% 3', ' %3');
				s = s.replace('% 4', ' %4');
				s = s.replace('% 5', ' %5');
				$(id).value = s;
			}
		});	
	}
}

var g_lj = new LJS(); // language collection
var g_el = new eLoad(); //body on load events
function jlang(s) {return g_lj.get(s);}
function _g_set_lang(sLang){createCookie(USER_LANG_COOKIE, sLang, 365);reload();}

function reload() {location.reload();}
function gohome() {location.href='/';}
function go(s) {location.href=s;}
function goback(s) {location.href=(g_prev_link!='')?g_prev_link:s;}
function p(o) {return o.parentNode;}
function cr(tag){return document.createElement(tag);}
function ap(par,el){return par.appendChild(el);}
function crap(tag, par){return par.appendChild(cr(tag));}

function ap_list(par,el)
{
	var li = ap(par,new Element('li'));
	return ap(li,el);
}
function ap_list_text(par,sText)
{
	var li = ap(par,new Element('li'));
	li.innerHTML = sText;
	return li;
}

function ins(par,el){return par.insertBefore(el,par.childNodes[0]);}
function rm(o){if(o.parentNode)o.parentNode.removeChild(o);}
function hd_block(obj, is_hide){
    if (obj!=null) {
	    if (is_hide) {obj.style.display='';obj.style.display='none';}
	    if (!is_hide) {obj.style.display= (obj.tagName=='TR')?'':'block';}
	}
}	 

function _g_extend_prototype(){
	// extend form
	Element.addMethods({
			getMultiValue: function(frm,radioName) {
				var radioGroup = document.getElementsByName(radioName);
				for (radioGroupLoop = 0; radioGroupLoop < radioGroup.length; radioGroupLoop++){
					if (radioGroup[radioGroupLoop].checked){
						return radioGroup[radioGroupLoop].value;
					}
				}
				return false;
			}
		});			
}

function head_select_menu(active_menu) {
	$$("div#head_menu a[id='mnu_" + active_menu + "']").each(function(a) {
		var x = Element.extend(a);
		var n = x.next('div')
		var p = x.previous('div')
		x.toggleClassName('sel');
		p.toggleClassName('cut_sel_l'); ;
		if (n.className != 'cut_f') {
			n.toggleClassName('cut_sel_l_r'); ;
		} else {
			n.toggleClassName('cut_f_sel'); ;
		}
	});
}


function hideSelects(isshow){
	var vis = isshow ? 'visible' : 'hidden'
	if(!Prototype.Browser.IE)
		return;
	$A(document.getElementsByTagName("select")).each(
		function(el)
		{
			el.style.visibility = vis;
		}
	);
}





function alertw(txt, sTemplatePage, fCancel, fOk){
	_mnuHide();
    var img = cr('img');
		img.src = '/img/loader.gif';
		img.id='ajax_loader';
		img.style.display='none';
		ap(document.getElementsByTagName('body')[0],img);				
		new Effect.Appear(img, { duration: 0.1, to:1});

		var opt = {
			method: 'get',
			parameters: '',
			onComplete: function alertShow(or) {
				try {
					var json = or.responseText.evalJSON();
					switch (parseInt(json.actionStatusCode)) {
						case ERR_NOT_AUTH: alert(json.actionStatusMessage); gohome(); return null; break;
					}
				} catch (e) { };

				hideSelects(false);
				var d = document; var b = document.getElementsByTagName('body');
				var alert_div = $('alert_div');
				if (alert_div == null) {
					alert_div = cr('div');
					alert_div.id = 'alert_div';
					alert_div.style.zIndex = '-1';
					ap(b[0], alert_div)
					modalShow();
				}
				Element.update(alert_div, or.responseText)
				alert_div.style.position = 'absolute';

				if (txt != null) $('alert_body').innerHTML = txt;
				if ($('alert_title') != null) $('alert_title').onselectstart = function() { return false; };
				if ($('alert_ok')) $('alert_ok').href = 'javascript:;';
				if ($('alert_ok') && fOk == null) { $('alert_ok').onclick = alertc; $('alert_ok').href = 'javascript:alertc()'; }
				if ($('alert_close')) $('alert_close').onclick = alertc;
				if ($('alert_cancel')) $('alert_cancel').onclick = alertc;
				if (fOk != null && $('alert_ok')) $('alert_ok').onclick = fOk;
				if (fCancel != null) {
					if ($('alert_close')) $('alert_close').onclick = fCancel;
					if ($('alert_cancel')) $('alert_cancel').onclick = fCancel;
				}

				var win_h = (document.body.scrollTop) ? document.body.scrollTop : document.documentElement.scrollTop;
				var win_w = (document.body.scrollLeft) ? document.body.scrollLeft : document.documentElement.scrollLeft;
				//alert_div.style.top = (win_h + (document.viewport.getHeight() - alert_div.offsetHeight)/2) + "px";
				alert_div.style.top = (win_h + 100) + "px";
				alert_div.style.left = (win_w + (document.viewport.getWidth() - $('alert_message').offsetWidth) / 2 - 15) + "px";
				alert_div.style.display = 'none';
				alert_div.style.zIndex = '999';

				new Effect.Appear($('body'), { duration: 0.3, to: 0.2 });

				new Effect.Appear(alert_div, { duration: 0.3, to: 1 });
				if (win_h + (document.viewport.getHeight() - alert_div.offsetHeight) / 2 < 5) alert_div.style.top = '5px';
				if ($('ajax_loader')) { rm($('ajax_loader')); }
				ie6_png();
				new Draggable(alert_div, {});
				if (readCookie('trans_mode') == 'on') _trans_attach();
			}
		}
	if (sTemplatePage==null) sTemplatePage = 'default';
	    sTemplatePage = '/alert.asp?tpl=' + sTemplatePage;
	var aj = new Ajax.Request(sTemplatePage,opt);
}	

function alertc()
{
	new Effect.Appear($('body'), { duration: 0.5, to:1});
	if ($('alert_div')!=null) 
	{
		modalHide();
		hideSelects(true);
		document.getElementsByTagName('body')[0].removeChild($('alert_div'));
	}
	
}

function modalShow(){
		var d = document; var b = document.getElementsByTagName('body');
		var dm = cr('div');
			dm.id = 'modal_layer';
			dm.style.height=document.body.scrollHeight;
		ap(b[0],dm);
		hideSelects(false);
}

function modalHide(){
 if ($('modal_layer')) {
		rm($('modal_layer'));
		hideSelects(true); 		
 }
}

function insIn(o,s) {
    var scrrll = o.scrollTop;
    if (document.selection) {
     o.focus();
     var sel = document.selection.createRange();
     sel.text = s;
     o.focus();
    } else if (o.selectionStart || o.selectionStart == '0') {
        var startPos = o.selectionStart;
        var endPos = o.selectionEnd;
        o.value = o.value.substring(0, startPos)+ s + o.value.substring(endPos, o.value.length);
        o.focus();	    
        o.selectionStart = endPos + s.length;
        o.selectionEnd = endPos +  s.length;
    } else {
        o.value += s;
        o.focus();	    
    }        
    o.scrollTop = scrrll;
}    
    
        
function clipB(o){
    if (document.selection) {
        var c = o.createTextRange();
        c.select();
    } else {
        o.setSelectionRange(0,999);
    }
}

function createCookie(name,value,days)
{
    if (days)
    {
	    var date = new Date();
	    date.setTime(date.getTime()+(days*24*60*60*1000));
	    var expires = '; expires='+date.toGMTString();
    }
    else var expires = '';
    document.cookie = escape(name)+'='+escape(value)+expires+'; path=/';

}

function readCookie(name)
{
    var nameEQ = escape(name) + '=';
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++)
    {
	    var c = ca[i];
	    while (c.charAt(0)==' ') c = c.substring(1,c.length);
	    if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
}

function eraseCookie(name)	{createCookie(name,'',-1);}



function _g_callAction(params, response_func, s_http_method)
{	

	if (!s_http_method) s_http_method = 'get';
	new Ajax.Request(window.location.href,
    {
		method:s_http_method,
		parameters: Object.extend(params,{rq_type:RQ_AJAX_JSON}),
		onSuccess:
		function(response)
		{
			if (response_func)
				response_func(response);
			else {
				var json = response.responseText.evalJSON();
				if (json.actionStatusCode==ERR_OK) 
				{
					if (params.jsalert)
						alert(json.actionStatusMessage);
					else
						alertw(json.actionStatusMessage);
					
				}
			}
		}
	});	
}


function _global_key_check(e)
{
	if (!e) e = window.event;
    var k = e.keyCode;
    if (k==27) alertc();    
    if (e.ctrlKey) 
    {
		var el = Event.element(e);
		if (el && el.tagName && (el.tagName!="TEXTAREA" && el.tagName!="INPUT"))
		{	
			if (k == Event.KEY_LEFT && $('page_prev')) location.href = $('page_prev').href;
			if (k == Event.KEY_RIGHT && $('page_next')) location.href = $('page_next').href;
		}	
    }
    if (e.altKey)  {
		if (k == 49) {$('href_seo_title').onclick();}
		if (k == 50) {$('href_seo_description').onclick();}
		if (k == 51) {$('href_seo_keywords').onclick();}
		if (k == 48) {_g_enable_translation();}
		
    }
}



function g_seo_page(seo_url, seo_field_type, sData)
{
	var seo_field_value = prompt("Новое значение для " + seo_field_type + ' этой(!) страницы',sData);
	if(seo_field_value)
	{
		_g_callAction({gact:ACT_ADMIN_SEO_UPDATE,'seo_url':seo_url, 'seo_field_type':seo_field_type,'seo_field_value':seo_field_value}, function(){window.location.href=window.location.href;}, 'post');
	}
}

function _g_enable_translation(){
	var c_name = 'translation_mode';
	if (readCookie(c_name)!='on')
		createCookie(c_name, 'on', 10);
	else
		createCookie(c_name, 'off', 10);
	reload();
}



function g_cancelEvent(e)
{
  if(!e)
    e = window.event;
  if(e.stopPropagation)
    e.stopPropagation();
  if(e.preventDefault)
    e.preventDefault();
  e.cancelBubble = true;
  e.cancel = true;
  e.returnValue = false;
  return false;
}

function isValidDate(day,month,year){
	var dteDate=new Date(year,parseInt(month)-1,day);
	return ((parseInt(day)==dteDate.getDate()) && (parseInt(month)-1==dteDate.getMonth()) && (parseInt(year)==dteDate.getFullYear()));
}

function _g_order(g_data_type, i_order, bNeedReload) {
	createCookie(g_data_type + '.order', i_order, 365);
	if (bNeedReload) reload();
}


function LJS_add() {
	for (c=0; c < LJS_add.arguments.length; c+=2) {this[LJS_add.arguments[c]] = LJS_add.arguments[c+1];}
}
function LJS_get(strKeyName) {
	if (this[strKeyName])
		return(this[strKeyName]);
	else
		return(strKeyName);
}

function LJS() {
  this.add = LJS_add;
  this.get = LJS_get;
}

function eLoad() {
  this.i = 0;
  this.add = eLoad_add;
  this.call = eLoad_call;
}

function eLoad_add(f){
	this[this.i++] = f;
}

function eLoad_call(){
	for (i=0;i<this.i;i++)
	this[i]();
}

var _f_after_upload = null;
function _g_al_upload(target, f)
{
	_f_after_upload = f;
	alertw(null,'upload&target='+target,null,function(){_g_fsubmit('frm_upload')});
}

function _g_use_holidays()
{
	alertw(null,'use_holidays',null,null);
}

function _g_use_contacts(city_id)
{
	alertw(null, 'use_contacts&city_id=' + (city_id ? city_id : C_DEFAULT_CITY), null, null);
}

function _g_use_con_add(city_id, contact_type_id, contact_type_loc) {
	var prefix = prompt(jlang('Укажите префикс для контактов в адресной книге'), contact_type_loc);
	new Ajax.Request('/',
    {
		method:'get',
		parameters: { gact: ACT_USE_CON_ADD, rq_type: RQ_AJAX_JSON, 'city_id': city_id, 'contact_type_id': contact_type_id, 'prefix': prefix },
		onSuccess:function(response) {
				var json = response.responseText.evalJSON();
				if (json.actionStatusCode==ERR_OK) {alert(json.actionStatusMessage),go('/contacts?srch='+prefix)};
			}
	});	
}

function _g_use_holi_add(holi_type, holi_type_loc) {
	alertc();
	new Ajax.Request('/',
    {
		method:'get',
		parameters: {gact:ACT_USE_HOLI_ADD, rq_type:RQ_AJAX_JSON, 'holi_type':holi_type},
		onSuccess:function(response) {
				var json = response.responseText.evalJSON();
				if (json.actionStatusCode==ERR_OK) alertw(json.actionStatusMessage);
			}
	});	
}

function _g_upload_complete(data) {
	if(data.statusCode!=0)
		alert(data.statusText)
	else
	{
		_f_after_upload(data.statusText);
		alertc();
	}
}

function _g_upload_wiki_insert(sVal) {
		$('bodytextctl').value += '[img|'+sVal+']';
		$('bodytextctl').focus();
}

function _g_contact_avatar(sVal) {
	$('frm_con_save').avatar_temp_file.value = sVal;
	$('contact_avatar').src = '/img/upload/contacts/' + sVal;
}

function _g_import(sFile, sMode) {
	alertw(null,'import&file='+sFile + '&mode='+sMode,null,function(){reload();});
	//alert(sVal);
	//$('frm_con_save').avatar_temp_file.value = sVal;
}


function _g_remove_users(sFile, sMode) {
	alertw(null, 'adm_remove_users&file=' + sFile, null, function() { go('/admin-users.asp?user_filter=5') });
	//alert(sVal);
	//$('frm_con_save').avatar_temp_file.value = sVal;
}






function _g_al_invite()
{
	var first_guid='';
	$('frm_list').getInputs('checkbox').each(
		function (el){
			if (el.checked) {
				if(first_guid!='')
					first_guid += "," +el.value;
				else
					first_guid = el.value;
				el.checked = false;
			}
		}
	);	
	alertw(null,'invite&id='+first_guid,null, function(){_g_fsubmit('frm_invite')});
}

function _g_al_invite_validate(frm)
{
	var frm = $(frm);
	var fnames = frm.getInputs('text','first_name');
	var lnames = frm.getInputs('text','last_name');
	var emails = frm.getInputs('text','email');
	for(var i=0;i<fnames.length;i++)
	{
		if((fnames[i].value==''||lnames[i].value==''||emails[i].value=='')&!(fnames[i].value==''&lnames[i].value==''&emails[i].value==''))
		{
			alert(jlang('Необходимо заполнить все поля'));
			if(fnames[i].value=='')
				new Effect.Highlight(fnames[i]);
			if(lnames[i].value=='')
				new Effect.Highlight(lnames[i]);
			if(emails[i].value=='')
				new Effect.Highlight(emails[i]);
			return false;
		}
		if(emails[i].value.strip()!='' && emails[i].getAttribute('rq_format')) {
			var r = new RegExp(emails[i].getAttribute('rq_format'));
			if (!r.test(emails[i].value)) {
				alert(emails[i].getAttribute('rq_format_err'));
				emails[i].focus();
				new Effect.Highlight(emails[i]);
				return false;	
			}
		}
	}
	return true;
}
function _g_al_invite_sent()
{
	alertc();
	alertw(jlang('Приглашение отправлено'),null,null,null);
}

function tglClass(o, className) {
	Element.extend(o);
	o.toggleClassName(className);
}

function _g_load_nav_month(sDay) {
	new Ajax.Updater('scal2', '/calendar',
		{
			method:'get',
			parameters: 
					 {rq_type:RQ_AJAX_TEXT,
					  gact:ACT_LOAD_NAV_CALENDAR,
					  day:sDay
					 },
			evalScripts:false
		});	
}

function _g_al_detect_phone(bSilence) {
	if (C_ENABLE_DEVICE_DETECTION=='True') {
		_g_callAction(
			{ gact: ACT_DETECT_DEVICE },
			function(response) {
				var json = response.responseText.evalJSON();
				if (json.actionStatusCode == ERR_OK)
					_g_al_setup_phone(json.actionStatusMessage);
				else
					if (!bSilence) {
					alertw(jlang('Ваша модель телефона не определена.<br/>Выберите её из списка телефонов и выполните настройку'), null, null, function() { window.location.href = '/?sp=setup' });
				}
			},
			'get'
		);
		} else {
		go('/?sp=setup')
	}
}

function _g_al_setup_phone(device_id) {
	alertw(null, 'all_settings&device_id=' + device_id, null, function() { g_al_setup_phone_after(device_id); });
}

function g_al_setup_phone_after(device_id) {
	alertw(null, 'after_settings&device_id=' + device_id, null, null);
}

function _g_al_change_mail() {
	alertw(null, 'change_mail', null, function() { _g_fsubmit('frm_alert')});
}
function _g_al_change_password() {
	alertw(null, 'change_password', null, function() { _g_fsubmit('frm_alert')});
}
function frmValidatePasswordRepeat(form_name) {
	var frm = $(form_name);
	if (frm.password_1.value != frm.password_2.value) {
		alert(jlang('Пароль в обоих полях должен совпадать'));
		return false;
	} else {
		return true;
	}
}


function _g_send_settings_api(phone_name, device_id) {
	_g_callAction({ gact: ACT_SEND_SETTINGS, 'phone_name': phone_name },
		function(response) {
			var json = response.responseText.evalJSON();
			if (json.actionStatusCode == ERR_OK)
				alertw(json.actionStatusMessage, null, null, function() { g_al_setup_phone_after(device_id) });
			else
				alertw(json.actionStatusMessage);
		},
	'GET');
	}

	

/* jlang from asp code */

jlang('Начало события');
jlang('Окончание события');




function _show_lang_panel() {
	var l = Position.positionedOffset($('lang_selector'));
	var ps = $('lang_panel').style;
	ps.left = l[0] - 5 + 'px';
	ps.top = l[1] + 28 + 'px';
	_l_sw();
}
function _l_sw() {
	var ps = $('lang_panel').style;
	ps.display = (ps.display == 'block') ? 'none' : 'block';
}

function _adm_eu(uid) {
	alertw(null, 'adm_user' + '&user_id=' + uid, null, null);
}
function _g_adm_user_rights(uid, rv) {
	_g_callAction({ gact: ACT_ADM_UPDATE_USER_RIGHT, 'user_id': uid, 'rights': rv },
		function(response) {
			_adm_eu(uid);
		},
	'GET');
}

function _adm_use_city(city_id) {
	alertw(null, 'adm_city' + '&city_id=' + city_id, null, function() { _g_fsubmit('frm_city_edit'); reload(); });
}

function _adm_use_type(type_id) {
	alertw(null, 'adm_use_type' + '&type_id=' + type_id, null, function() { _g_fsubmit('frm_type_edit'); reload(); });
}
function _adm_phone(type_id) {
	alertw(null, 'adm_phone' + '&phone_id=' + type_id, null, function() { _g_fsubmit('frm_phone_save'); reload(); });
}
function _adm_use_data(contact_id, city_id, type_id) {
	alertw(null, 'adm_use_contact' + '&contact_id=' + contact_id + '&city_id=' + city_id + '&type_id=' + type_id, null, function() { _g_fsubmit('frm_contact_edit'); });
}
function _adm_use_data_reload() {
	$('frm_list').submit();
}

function _adm_use_holi_type(type_id) {
	alertw(null, 'adm_use_holi_type' + '&type_id=' + type_id, null, function() { _g_fsubmit('frm_holi_type_edit'); reload(); });
}
function _adm_use_holi_data(holi_id, type_id) {
	alertw(null, 'adm_use_holi' + '&holi_id=' + holi_id + '&type_id=' + type_id, null, function() { _g_fsubmit('frm_holi_edit'); });
}

function _dt_use_holi_copy() {
	var x = $('x1').value;
	$('x2').value = x;
	$('x3').value = x;
	$('x4').value = x;
	$('x5').value = x;
}


function _g_info_hide(o, s) {
	createCookie(s, "off", 365);
	o.parentNode.parentNode.removeChild(o.parentNode);
}

function _g_bill_country_change() {
	alertw(null, 'bill_country_change', null, function() { _g_fsubmit('frm_popup'); });
}

function _g_bill_tariff_change(account_type) {
	_g_callAction({ gact: ACT_BILL_TARIFF_CHNAGE, 'account_type': account_type },
		function(response) {
			var json = response.responseText.evalJSON();
			if (json.actionStatusMessage != '')
				alertw(json.actionStatusMessage, null, null, function() { go('/order-info.asp?sp=pay') });
			else
				go('/order-info.asp?sp=pay');

		},
	'GET');
}


function _gs_new_topic(forum_id) {
	alertw(null, 'new_topic&forum_id=' + forum_id, null, function() { _g_fsubmit('frm_topic_create'); });
}

function _gs_new_post(forum_id, topic_id) {
	alertw(null, 'new_post&forum_id=' + forum_id + '&topic_id=' + topic_id, null, function() { _g_fsubmit('frm_post_create'); });
}

function _gs_edit_post(forum_id, post_id) {
	alertw(null, 'new_topic&forum_id=' + forum_id + '&post_id=' + post_id, null, function() { _g_fsubmit('frm_topic_create'); });
}



function frm_onTopicCreate(or) {
	var json = or.responseText.evalJSON();
	switch (parseInt(json.actionStatusCode)) {
		case ERR_NOT_AUTH: alert(json.actionStatusMessage); gohome(); break;
		case ERR_OK:
			if (json.actionStatusMessage != '')
				go(json.actionStatusMessage);
			else
				reload();
			alertc();
			break;
	}
}

function frm_onPostCreate(or) {
	var json = or.responseText.evalJSON();
	switch (parseInt(json.actionStatusCode)) {
		case ERR_NOT_AUTH: alert(json.actionStatusMessage); gohome(); break;
		case ERR_OK: go(json.actionStatusMessage); alertc(); break;
	}
}