
var Base64 = {
 
	// private property
	_keyStr : "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",
 
	// public method for encoding
	encode : function (input) {
		var output = "";
		var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
		var i = 0;
 
		input = Base64._utf8_encode(input);
 
		while (i < input.length) {
 
			chr1 = input.charCodeAt(i++);
			chr2 = input.charCodeAt(i++);
			chr3 = input.charCodeAt(i++);
 
			enc1 = chr1 >> 2;
			enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
			enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
			enc4 = chr3 & 63;
 
			if (isNaN(chr2)) {
				enc3 = enc4 = 64;
			} else if (isNaN(chr3)) {
				enc4 = 64;
			}
 
			output = output +
			this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) +
			this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4);
 
		}
 
		return output;
	},
 
	// public method for decoding
	decode : function (input) {
		var output = "";
		var chr1, chr2, chr3;
		var enc1, enc2, enc3, enc4;
		var i = 0;
 
		input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
 
		while (i < input.length) {
 
			enc1 = this._keyStr.indexOf(input.charAt(i++));
			enc2 = this._keyStr.indexOf(input.charAt(i++));
			enc3 = this._keyStr.indexOf(input.charAt(i++));
			enc4 = this._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);
			}
 
		}
 
		output = Base64._utf8_decode(output);
 
		return output;
 
	},
 
	// private method for UTF-8 encoding
	_utf8_encode : function (string) {
		string = string.replace(/\r\n/g,"\n");
		var utftext = "";
 
		for (var n = 0; n < string.length; n++) {
 
			var c = string.charCodeAt(n);
 
			if (c < 128) {
				utftext += String.fromCharCode(c);
			}
			else if((c > 127) && (c < 2048)) {
				utftext += String.fromCharCode((c >> 6) | 192);
				utftext += String.fromCharCode((c & 63) | 128);
			}
			else {
				utftext += String.fromCharCode((c >> 12) | 224);
				utftext += String.fromCharCode(((c >> 6) & 63) | 128);
				utftext += String.fromCharCode((c & 63) | 128);
			}
 
		}
 
		return utftext;
	},
 
	// private method for UTF-8 decoding
	_utf8_decode : function (utftext) {
		var string = "";
		var i = 0;
		var c = c1 = c2 = 0;
 
		while ( i < utftext.length ) {
 
			c = utftext.charCodeAt(i);
 
			if (c < 128) {
				string += String.fromCharCode(c);
				i++;
			}
			else if((c > 191) && (c < 224)) {
				c2 = utftext.charCodeAt(i+1);
				string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
				i += 2;
			}
			else {
				c2 = utftext.charCodeAt(i+1);
				c3 = utftext.charCodeAt(i+2);
				string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
				i += 3;
			}
 
		}
 
		return string;
	}
 
}

var Url = { 
 
	// публичная функция для кодирования URL 
	encode : function (string) { 
		return escape(this._utf8_encode(string)); 
	}, 
 
	// публичная функция для декодирования URL 
	decode : function (string) {
		lsRegExp = /\+/g;
		return this._utf8_decode(unescape(string.replace(lsRegExp, " "))); 
	}, 
 
	// приватная функция для кодирования URL 
	_utf8_encode : function (string) { 
		string = string.replace(/\r\n/g,"\n"); 
		var utftext = ""; 
 
		for (var n = 0; n < string.length; n++) { 
 
			var c = string.charCodeAt(n); 
 
			if (c < 128) { 
				utftext += String.fromCharCode(c); 
			} 
			else if((c > 127) && (c < 2048)) { 
				utftext += String.fromCharCode((c >> 6) | 192); 
				utftext += String.fromCharCode((c & 63) | 128); 
			} 
			else { 
				utftext += String.fromCharCode((c >> 12) | 224); 
				utftext += String.fromCharCode(((c >> 6) & 63) | 128); 
				utftext += String.fromCharCode((c & 63) | 128); 
			} 
 
		} 
 
		return utftext; 
	}, 
 
	// приватная функция для декодирования URL 
	_utf8_decode : function (utftext) { 
		var string = ""; 
		var i = 0; 
		var c = c1 = c2 = 0; 
 
		while ( i < utftext.length ) { 
 
			c = utftext.charCodeAt(i); 
 
			if (c < 128) { 
				string += String.fromCharCode(c); 
				i++; 
			} 
			else if((c > 191) && (c < 224)) { 
				c2 = utftext.charCodeAt(i+1); 
				string += String.fromCharCode(((c & 31) << 6) | (c2 & 63)); 
				i += 2; 
			} 
			else { 
				c2 = utftext.charCodeAt(i+1); 
				c3 = utftext.charCodeAt(i+2); 
				string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63)); 
				i += 3; 
			} 
 
		} 
 
		return string; 
	} 
 
}

// вместо функции Dump()
var smsmaxlen  = 480; //максимум 3 смс
var rus = ["ж", "ч", "ш", "щ", "ю", "я", "Ж", "Ч", "Ш", "Щ", "Ю", "Я", "\x0d"];
var rus_len = [2, 2, 2, 3, 2, 2, 2, 2, 2, 3, 2, 2, 0]; //русские буквы, занимающие 2 байта

var objCount=0;
pics=new Array ();


function hide_block(id)
{
	if (obj = document.getElementById(id)) {
		obj.style.display = 'none';
	}
}

function show_block(id)
{
	if (obj = document.getElementById(id)) {
		obj.style.display = 'block';
	}
}

function setGlobalOnLoad(f) {
	var root = window.addEventListener || window.attachEvent ? window : document.addEventListener ? document : null
	if (root){
		if(root.addEventListener) root.addEventListener("load", f, false)
		else if(root.attachEvent) root.attachEvent("onload", f)
	} else {
		if(typeof window.onload == 'function') {
			var existing = window.onload
			window.onload = function() {
				existing()
				f()
			}
		} else {
			window.onload = f
		}
	}
}

function switch_checkbox(chb_id, row_id) {
	// flip checkbox
	if (chb_id != '') {
		var chb = document.getElementById(chb_id);
		chb.checked = (chb.checked ? false : true);
	}
	// flip css style
	if (row_id != '') {
		var tr = document.getElementById(row_id);
		//CssClasses(tr).flip('checked');
		tr.marked = tr.marked ? false : true;
		tr.style.backgroundColor = tr.marked ? '#E1E7CC' : '';
		
		var tr_addinfo = document.getElementById(row_id+'_addinfo');
		//CssClasses(tr).flip('checked');
		if(tr_addinfo != null) {
			tr_addinfo.marked = tr_addinfo.marked ? false : true;
			tr_addinfo.style.backgroundColor = tr_addinfo.marked ? '#E1E7CC' : '';
		}
		var tr_addrow1 = document.getElementById(row_id+'_addrow1');
		//CssClasses(tr).flip('checked');
		if(tr_addrow1 != null) {
			tr_addrow1.marked = tr_addrow1.marked ? false : true;
			tr_addrow1.style.backgroundColor = tr_addrow1.marked ? '#E1E7CC' : '';
		}
	}
}

function nic_dialog(obj, def) {
	var text = 'Укажите псеводним\n(пустая строка приравнивается к удалению псевдонима)';
	var new_nic = prompt(text, def);
	// TODO: переделать условие так, чтобы воспринималась пустая строка, но не "Cancel"
	if (new_nic || new_nic == '') {
		var arr = obj.href.split('?');
		arr[0] += '?nic='+new_nic+'&';
		obj.href = arr.join('');
		return true;
	}
	return false;
}

function setPos(obj, lyr)
{
	var newX = findPosX(obj);
	var newY = findPosY(obj);
	var x = new getObj(lyr);
	x.style.top = newY + 'px';
	x.style.left = newX + 'px';
}

function findPosX(obj)
{
	var curleft = 0;
	if (obj.offsetParent) {
		while (obj.offsetParent) {
			curleft += obj.offsetLeft
			obj = obj.offsetParent;
		}
	}
	else if (obj.x) {
		curleft += obj.x;
	}
	return curleft;
}

function findPosY(obj)
{
	var curtop = 0;
	if (obj.offsetParent) {
		while (obj.offsetParent) {
			curtop += obj.offsetTop
			obj = obj.offsetParent;
		}
	}
	else if (obj.y) {
		curtop += obj.y;
	}
	return curtop;
}

function getObj(name)
{
	if (document.getElementById)
	{
		this.obj = document.getElementById(name);
		this.style = document.getElementById(name).style;
	}
	else if (document.all)
	{
		this.obj = document.all[name];
		this.style = document.all[name].style;
	}
	else if (document.layers)
	{
		this.obj = getObjNN4(document,name);
		this.style = this.obj;
	}
}

function getObjNN4(obj,name)
{
	var x = obj.layers;
	var foundLayer;
	for (var i=0;i<x.length;i++) {
		if (x[i].id == name) {
			foundLayer = x[i];
		}
		else if (x[i].layers.length) {
			var tmp = getObjNN4(x[i],name);
		}
		if (tmp) {
			foundLayer = tmp;
		}
	}
	return foundLayer;
}

var _input_list = null;
var _tr_list = null;
function select_checkboxes(chb_mask, tr_mask) {
    $('input[id^="' + chb_mask + '"]:visible').attr('checked', true);
    if(tr_mask) {
        $('tr[id^="' + tr_mask + '"]:visible').css('background-color', '#E1E7CC').addClass('no_ruled').nextAll('tr').css('background-color', '#E1E7CC').addClass('no_ruled');
		$('tr[id^="' + tr_mask + '"]:visible td').addClass('cell_selected');
    }

	return false;
}

function unselect_checkboxes(chb_mask, tr_mask) {
    $('input[id^="' + chb_mask + '"]:visible').attr('checked', false);
    if(tr_mask) {
        $('tr[id^="' + tr_mask + '"]:visible').css('background-color', '').removeClass('no_ruled').nextAll('tr').css('background-color', '').removeClass('no_ruled');
		$('tr[id^="' + tr_mask + '"]:visible td').removeClass('cell_selected');
    }

	return false;
}

function get_selected_checkboxes(chb_mask) {
	if (_input_list == null) {
		_input_list = document.getElementsByTagName('input');
	}
	var ind, id, tr;
	var res = [];
	for(var i = 0; i < _input_list.length; i++) {
		ind = _input_list[i].id.indexOf(chb_mask);
		if (ind == 0 && _input_list[i].checked) {
			res[res.length] = _input_list[i].id
		}
	}
	return res;
}

function get_checkboxes(chb_mask) {
	if (_input_list == null) {
		_input_list = document.getElementsByTagName('input');
	}
	var ind, id, tr;
	var res = [];
	for(var i = 0; i < _input_list.length; i++) {
		ind = _input_list[i].id.indexOf(chb_mask);
		if (ind == 0) {
			res[res.length] = _input_list[i].id
		}
	}
	return res;
}

function show_hide_trs(tr_mask) {
	if (_tr_list == null) {
		_tr_list = document.getElementsByTagName('tr');
	}
	for(var i = 0; i < _tr_list.length; i++) {
		ind = _tr_list[i].id.indexOf(tr_mask);
		ivisible = _tr_list[i].style.cssText.indexOf('visible');
		if (ind == 0 && ivisible>=0) {
			_tr_list[i].style.cssText = 'visibility:hidden; position:absolute';
		}
		if (ind == 0 && ivisible<0) {
			_tr_list[i].style.cssText = 'visibility:visible; position:relative';
		}
	}
	return false;
}

function toggle_symbol(id) {
	if(document.getElementById(id).innerHTML=='+') {
		document.getElementById(id).innerHTML='-';
	} else {
		document.getElementById(id).innerHTML='+';
	}
	return false;
}


function CookieHandler() {}
CookieHandler.prototype = {
	// Функция установки значения cookie.
	setCookie: function(name, value, path, expires, domain, secure) {
		var curCookie = name + "=" + escape(value) +
		((expires) ? "; expires=" + expires.toGMTString() : "") +
		((path) ? "; path=" + path : "; path=/") +
		((domain) ? "; domain=" + domain : "") +
		((secure) ? "; secure" : "");
		document.cookie = curCookie;
	},

	// Функция чтения значения cookie.
	getCookie: function(name) {
		var prefix = name + "=";
		var cookieStartIndex = document.cookie.indexOf(prefix);
		if(cookieStartIndex == -1) return null;
		var cookieEndIndex = document.cookie.indexOf(";", cookieStartIndex + prefix.length);
		if (cookieEndIndex == -1) cookieEndIndex = document.cookie.length;
		return unescape(document.cookie.substring(cookieStartIndex + prefix.length, cookieEndIndex));
	}	
}

function SwitchBlockHandler(id) { this.constructor(id); }
SwitchBlockHandler = newClass(CookieHandler, {
	id  : null,
	obj : null,
	cookName : null,

	constructor : function (id) {
		this.id = id;
		this.cookName = '_block_'+id;
		this.obj = document.getElementById(this.id);
		this.toggle(null);
	},

	// "включить"
	on: function() {
		this.toggle(1);
	},

	// "выключить"
	off: function() {
		this.toggle(0);
	},

	// "переключить"
	toggle: function() {
		var args = arguments;
		var on;
		if (args.length > 0) { on = args[0]; }
		else { on = !this.getFlag(); }
		if (on == null) { on = this.getFlag(); }
		this.obj.style.display = on ? 'block' : 'none';
		this.setFlag(on ? 1 : 0);
	},

	setFlag: function(flag) {
		this.constructor.prototype.setCookie.call(this, this.cookName, flag ? 1 : 0, '/', new Date(new Date().getTime()+3600*24*365*1000));
	},

	getFlag: function() {
		return Math.round(this.constructor.prototype.getCookie.call(this, this.cookName));
	}
});

function SwitchBlock(id) {
	return new SwitchBlockHandler(id);
}

function CustomColHandler(id) { this.constructor(id); }
CustomColHandler = newClass(CookieHandler, {
	
	id  : null,
	obj : null,
	cookName : null,
	
	constructor : function (id) {
		this.id = id;
		this.cookName = '_'+id;
		this.obj = document.getElementById(this.id);
		this.toggle();
	},
	
	// "переключить"
	toggle: function() {
		var args = arguments;
		var flag;
		if (args.length > 0) { flag = args[0]; }
		else { flag = this.getFlag(); }
		this.setFlag(flag);
	},

	setFlag: function(flag) {
		this.constructor.prototype.setCookie.call(this, this.cookName, Math.round(flag), '/', new Date(new Date().getTime()+3600*24*365*1000));
	},

	getFlag: function() {
		return Math.round(this.constructor.prototype.getCookie.call(this, this.cookName));
	}	
	
});

function CustomCol(id) {
	return new CustomColHandler(id);
}

function countLen(rl) {
	message_text    = document.getElementById('message').value;
	realLength      = rl;
	storeLength     = 0;
	storeRealLength = 0;
	countMess       = 0;

	for (i=0; message_text.length>i; i++) {
		
			big_sign = false;

			for (j=0; rus.length>j; j++) {
				if (smsmaxlen>=realLength) {
					storeRealLength = realLength;
					storeLength = i;
				}

				if(rus[j]==message_text.substring(i,i+1)) {
					realLength += rus_len[j];
					big_sign = true;
					break;
				}
			}

			if (!big_sign) {
				realLength += 1;
			}
		
	}

	if (realLength>smsmaxlen) {
		realLength = storeRealLength;
		document.getElementById('message').value = message_text.substring(0,storeLength);
	}
	
	countMess = Math.ceil(realLength / 160);

	document.getElementById('messcount').innerHTML=countMess;
	document.getElementById('messlen').innerHTML=realLength;
}

function getSMScount(text) {
	if(!text) {
		return {counter:1,nextBorder:160};
	}
	
	var rus_letters=/[а-яА-Я]/;
	if(text == '' || rus_letters.test(text) == false) { //англ.алф.
		if(text.length <= 160) {
			counter = 1;
			nextBorder = 160;
		} else if (text.length <= (160+146)) {
			counter = 2;
			nextBorder = (160+146);
		} else {
			without_2_msgs = text.length - (160+146); //длина без первых двух смс
			counter = Math.ceil(without_2_msgs / 153) + 2;
			nextBorder = (160+146)+((counter-2)*153);
		}
	} else {
		if(text.length <= 70) {
			counter = 1;
			nextBorder = 70;
		} else if (text.length <= (70+64)) {
			counter = 2;
			nextBorder = (70+64);
		} else {
			without_2_msgs = text.length - (70+64); //длина без первых двух смс
			counter = Math.ceil(without_2_msgs / 67) + 2;
			nextBorder = (70+64)+((counter-2)*67);
		}
	}
	
	return {counter:counter, nextBorder:nextBorder};
}


function resetSearchForm() {
	
}

var keyStr = "ABCDEFGHIJKLMNOP" +
                "QRSTUVWXYZabcdef" +
                "ghijklmnopqrstuv" +
                "wxyz0123456789+/" +
                "=";
 
   function decode64(input) {
      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("");
      }
      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); if(chr1>191)chr1+=848;
         chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);if(chr2>191)chr2+=848;
         chr3 = ((enc3 & 3) << 6) | enc4;if(chr3>191)chr3+=848;
 
         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 output;
   }

function mousePageXY(e)
{
  var x = 0, y = 0;

  if (!e) e = window.event;
  
  if (e.pageX || e.pageY)
  {
    x = e.pageX;
    y = e.pageY;
  }

  else if (e.clientX || e.clientY)
  {
    x = e.clientX + (document.documentElement.scrollLeft || document.body.scrollLeft) - document.documentElement.clientLeft;
    y = e.clientY + (document.documentElement.scrollTop || document.body.scrollTop) - document.documentElement.clientTop;
  }

  return {"x":x, "y":y};
}
function strtolower (str) {
    // Makes a string lowercase  
    // 
    // version: 909.322
    // discuss at: http://phpjs.org/functions/strtolower
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Onno Marsman
    // *     example 1: strtolower('Kevin van Zonneveld');
    // *     returns 1: 'kevin van zonneveld'
    return (str+'').toLowerCase();
}

function in_array(what, where) {
    var a=false;
    for(var i=0; i<where.length; i++) {
        if(what == where[i]) {
            a=true;
            break;
        }
    }
    return a;

}

////////////////////ДЛЯ ФОРМАТИРОВАНИЯ НАСЕЛ.ПУНКТОВ (AJAX)
function formatcity(row,i,num){
 	var result,
        main_title = '',
        area = '';
 	
 	// [0]  (текст) значение
  	// [1]  ID нас.пункта
  	// [2]  (текст) название+тип региона
  	// [3]  (текст) тип региона (ПЕРЕЖИТОК!!)
  	// [4]  Флаг "большой город"
  	// [5]  ID района
  	// [6]  ID региона
  	// [7]  ID страны
  	// [8]  (текст) название+тип района
  	// [9]  (текст) тип нас.пункта
  	// [10] Флаг "Делится на округа"
	// [11] (текст) Транслитное название
 	
 	if(parseInt(row[1]) == '-1') { //совпадений не найдено
 		result = "<center><b>"+row[0]+"</b></center>";
 	} else if(parseInt(row[1]) <= '0' && parseInt(row[5]) <= '0' && parseInt(row[6]) <= '0' && parseInt(row[7]) > '0') { //СТРАНА
 		result = "<b>"+row[0]+"</b> (любой населенный пункт)";
 	} else if(parseInt(row[1]) <= '0' && parseInt(row[5]) <= '0' && parseInt(row[6]) > '0') { //РЕГИОН
 		result = "<b>"+row[2]+"</b> (регион)";
 	} else { //ГОРОД
 	
	 	if(row[10] != '1' && row[5] != '0') {
	 		area = ", "+row[8];
	 	} else {
	 		area = '';
	 	}
	 	
	 	if(row[4] != '0') { //is_big_city
	 		main_title = "<b>"+row[0]+"</b>";
	 	} else {
	 		main_title = row[0];
	 	}
	 	
	 	result=main_title+" ("+row[9]+")"+", "+row[2]+area;
 	}
 	
 	if(result.length > 60) {
		result = result.substr(0,60)+'...';
	}
	
 	return result;
 }
 function formatcity4input(row,i,num){
 	var result;
 	var area;
	if(parseInt(row[1]) <= '0' && parseInt(row[5]) <= '0' && parseInt(row[6]) <= '0' && parseInt(row[7]) > '0') { //СТРАНА
 		result = row[0]+" (любой населенный пункт)";
 	} else if(parseInt(row[1]) <= '0' && parseInt(row[5]) <= '0' && parseInt(row[6]) > '0') { //РЕГИОН
		result = row[2]+" (регион)";
	} else { //ГОРОД
 		if(row[10] != '1') {
 			area = ", "+row[8];
 		} else {
	 		area = '';
 		}
 		result=row[0]+", "+row[2]+area+" ("+row[9]+")";
	}
 	
	return result;
 }
 function formatcity_mini(row,i,num){
 	var result;
 	var area;
	if(parseInt(row[1]) <= '0' && parseInt(row[5]) <= '0' && parseInt(row[6]) <= '0' && parseInt(row[7]) > '0') { //СТРАНА
 		result = row[0]+" (любой населенный пункт)";
 	} else if(parseInt(row[1]) <= '0' && parseInt(row[5]) <= '0' && parseInt(row[6]) > '0') { //РЕГИОН
		result = row[2]+" (регион)";
	} else { //ГОРОД
 		result=row[0]+" ("+row[9]+")";
	}

	return result;
 }

 function str_replace(haystack, needle, replacement) { 
	var temp = haystack.split(needle); 
	return temp.join(replacement); 
} 

 function prepare_tooltip(obj) { // заглушка
 	return false;
 }
 function is_numeric (mixed_var) {
    // Returns true if value is a number or a numeric string  
    // 
    // version: 1006.1915
    // discuss at: http://phpjs.org/functions/is_numeric
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: David
    // +   improved by: taith
    // +   bugfixed by: Tim de Koning
    // +   bugfixed by: WebDevHobo (http://webdevhobo.blogspot.com/)
    // +   bugfixed by: Brett Zamir (http://brett-zamir.me)
    // *     example 1: is_numeric(186.31);
    // *     returns 1: true
    // *     example 2: is_numeric('Kevin van Zonneveld');
    // *     returns 2: false
    // *     example 3: is_numeric('+186.31e2');
    // *     returns 3: true
    // *     example 4: is_numeric('');
    // *     returns 4: false
    // *     example 4: is_numeric([]);
    // *     returns 4: false
    return (typeof(mixed_var) === 'number' || typeof(mixed_var) === 'string') && mixed_var !== '' && !isNaN(mixed_var);
}

function parse_phone(phone) {
	not_numeric = /\D+/g;
	res = phone.replace(not_numeric,'');
	if(res.length == 11 && res.substr(0,1) == '8') {
		res = '7'+res.substr(1);
	}
	return res;
}
 
function format_phone(phone) {
	res = parse_phone(phone);
	if(res.length != 11) {
		return phone;
	}
	return '+'+res.substr(0,1)+' '+res.substr(1,3)+' '+res.substr(4);
}

function switch_only_photo_view(state) {
	var source_hash = top.location.hash;
	var source_loc = top.location.href.replace('#', '').replace(source_hash, '').replace('f%5Bhas_photo%5D','f[has_photo]');
	var result_loc = '';
	if(state == false) { //значит надо включить
		if(source_loc.indexOf('f[has_photo]') > -1) {
			return true; //уже включено
		}
		if(source_loc.indexOf('?') > -1) {
			delim = '&';
		} else {
			delim = '?';
		}
		result_loc = source_loc + delim + 'f[has_photo]=1';
	} else {
		if(source_loc.indexOf('f[has_photo]') == -1) {
			return true; //уже включено
		}
		
		if(source_loc.indexOf('?f[has_photo]=1&') > -1) {
			result_loc = source_loc.replace('?f[has_photo]=1&', '?');
		} else if(source_loc.indexOf('&f[has_photo]=1&') > -1) {
			result_loc = source_loc.replace('&f[has_photo]=1&', '&');
		} else if(source_loc.indexOf('?f[has_photo]=1') > -1) {
			result_loc = source_loc.replace('?f[has_photo]=1', '');
		} else  if(source_loc.indexOf('&f[has_photo]=1') > -1) {
			result_loc = source_loc.replace('&f[has_photo]=1', '');
		}
	}
	if(result_loc != '') {
		top.location.href = result_loc+source_hash;
		return true;
	} else {
		return false;
	}
}

function html_entity_decode (string, quote_style) {
    // Convert all HTML entities to their applicable characters  
    // 
    // version: 1008.1718
    // discuss at: http://phpjs.org/functions/html_entity_decode
    // +   original by: john (http://www.jd-tech.net)
    // +      input by: ger
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +    revised by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   bugfixed by: Onno Marsman
    // +   improved by: marc andreu
    // +    revised by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +      input by: Ratheous
    // +   bugfixed by: Brett Zamir (http://brett-zamir.me)
    // +      input by: Nick Kolosov (http://sammy.ru)
    // +   bugfixed by: Fox
    // -    depends on: get_html_translation_table
    // *     example 1: html_entity_decode('Kevin &amp; van Zonneveld');
    // *     returns 1: 'Kevin & van Zonneveld'
    // *     example 2: html_entity_decode('&amp;lt;');
    // *     returns 2: '&lt;'
    var hash_map = {}, symbol = '', tmp_str = '', entity = '';
    tmp_str = string.toString();
    
    if (false === (hash_map = this.get_html_translation_table('HTML_ENTITIES', quote_style))) {
        return false;
    }
 
    // fix &amp; problem
    // http://phpjs.org/functions/get_html_translation_table:416#comment_97660
    delete(hash_map['&']);
    hash_map['&'] = '&amp;';
 
    for (symbol in hash_map) {
        entity = hash_map[symbol];
        tmp_str = tmp_str.split(entity).join(symbol);
    }
    tmp_str = tmp_str.split('&#039;').join("'");
    
    return tmp_str;
}

function get_html_translation_table (table, quote_style) {
    // Returns the internal translation table used by htmlspecialchars and htmlentities  
    // 
    // version: 1008.1718
    // discuss at: http://phpjs.org/functions/get_html_translation_table
    // +   original by: Philip Peterson
    // +    revised by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   bugfixed by: noname
    // +   bugfixed by: Alex
    // +   bugfixed by: Marco
    // +   bugfixed by: madipta
    // +   improved by: KELAN
    // +   improved by: Brett Zamir (http://brett-zamir.me)
    // +   bugfixed by: Brett Zamir (http://brett-zamir.me)
    // +      input by: Frank Forte
    // +   bugfixed by: T.Wild
    // +      input by: Ratheous
    // %          note: It has been decided that we're not going to add global
    // %          note: dependencies to php.js, meaning the constants are not
    // %          note: real constants, but strings instead. Integers are also supported if someone
    // %          note: chooses to create the constants themselves.
    // *     example 1: get_html_translation_table('HTML_SPECIALCHARS');
    // *     returns 1: {'"': '&quot;', '&': '&amp;', '<': '&lt;', '>': '&gt;'}
    
    var entities = {}, hash_map = {}, decimal = 0, symbol = '';
    var constMappingTable = {}, constMappingQuoteStyle = {};
    var useTable = {}, useQuoteStyle = {};
    
    // Translate arguments
    constMappingTable[0]      = 'HTML_SPECIALCHARS';
    constMappingTable[1]      = 'HTML_ENTITIES';
    constMappingQuoteStyle[0] = 'ENT_NOQUOTES';
    constMappingQuoteStyle[2] = 'ENT_COMPAT';
    constMappingQuoteStyle[3] = 'ENT_QUOTES';
 
    useTable       = !isNaN(table) ? constMappingTable[table] : table ? table.toUpperCase() : 'HTML_SPECIALCHARS';
    useQuoteStyle = !isNaN(quote_style) ? constMappingQuoteStyle[quote_style] : quote_style ? quote_style.toUpperCase() : 'ENT_COMPAT';
 
    if (useTable !== 'HTML_SPECIALCHARS' && useTable !== 'HTML_ENTITIES') {
        throw new Error("Table: "+useTable+' not supported');
        // return false;
    }
 
    entities['38'] = '&amp;';
    if (useTable === 'HTML_ENTITIES') {
        entities['160'] = '&nbsp;';
        entities['161'] = '&iexcl;';
        entities['162'] = '&cent;';
        entities['163'] = '&pound;';
        entities['164'] = '&curren;';
        entities['165'] = '&yen;';
        entities['166'] = '&brvbar;';
        entities['167'] = '&sect;';
        entities['168'] = '&uml;';
        entities['169'] = '&copy;';
        entities['170'] = '&ordf;';
        entities['171'] = '&laquo;';
        entities['172'] = '&not;';
        entities['173'] = '&shy;';
        entities['174'] = '&reg;';
        entities['175'] = '&macr;';
        entities['176'] = '&deg;';
        entities['177'] = '&plusmn;';
        entities['178'] = '&sup2;';
        entities['179'] = '&sup3;';
        entities['180'] = '&acute;';
        entities['181'] = '&micro;';
        entities['182'] = '&para;';
        entities['183'] = '&middot;';
        entities['184'] = '&cedil;';
        entities['185'] = '&sup1;';
        entities['186'] = '&ordm;';
        entities['187'] = '&raquo;';
        entities['188'] = '&frac14;';
        entities['189'] = '&frac12;';
        entities['190'] = '&frac34;';
        entities['191'] = '&iquest;';
        entities['192'] = '&Agrave;';
        entities['193'] = '&Aacute;';
        entities['194'] = '&Acirc;';
        entities['195'] = '&Atilde;';
        entities['196'] = '&Auml;';
        entities['197'] = '&Aring;';
        entities['198'] = '&AElig;';
        entities['199'] = '&Ccedil;';
        entities['200'] = '&Egrave;';
        entities['201'] = '&Eacute;';
        entities['202'] = '&Ecirc;';
        entities['203'] = '&Euml;';
        entities['204'] = '&Igrave;';
        entities['205'] = '&Iacute;';
        entities['206'] = '&Icirc;';
        entities['207'] = '&Iuml;';
        entities['208'] = '&ETH;';
        entities['209'] = '&Ntilde;';
        entities['210'] = '&Ograve;';
        entities['211'] = '&Oacute;';
        entities['212'] = '&Ocirc;';
        entities['213'] = '&Otilde;';
        entities['214'] = '&Ouml;';
        entities['215'] = '&times;';
        entities['216'] = '&Oslash;';
        entities['217'] = '&Ugrave;';
        entities['218'] = '&Uacute;';
        entities['219'] = '&Ucirc;';
        entities['220'] = '&Uuml;';
        entities['221'] = '&Yacute;';
        entities['222'] = '&THORN;';
        entities['223'] = '&szlig;';
        entities['224'] = '&agrave;';
        entities['225'] = '&aacute;';
        entities['226'] = '&acirc;';
        entities['227'] = '&atilde;';
        entities['228'] = '&auml;';
        entities['229'] = '&aring;';
        entities['230'] = '&aelig;';
        entities['231'] = '&ccedil;';
        entities['232'] = '&egrave;';
        entities['233'] = '&eacute;';
        entities['234'] = '&ecirc;';
        entities['235'] = '&euml;';
        entities['236'] = '&igrave;';
        entities['237'] = '&iacute;';
        entities['238'] = '&icirc;';
        entities['239'] = '&iuml;';
        entities['240'] = '&eth;';
        entities['241'] = '&ntilde;';
        entities['242'] = '&ograve;';
        entities['243'] = '&oacute;';
        entities['244'] = '&ocirc;';
        entities['245'] = '&otilde;';
        entities['246'] = '&ouml;';
        entities['247'] = '&divide;';
        entities['248'] = '&oslash;';
        entities['249'] = '&ugrave;';
        entities['250'] = '&uacute;';
        entities['251'] = '&ucirc;';
        entities['252'] = '&uuml;';
        entities['253'] = '&yacute;';
        entities['254'] = '&thorn;';
        entities['255'] = '&yuml;';
    }
 
    if (useQuoteStyle !== 'ENT_NOQUOTES') {
        entities['34'] = '&quot;';
    }
    if (useQuoteStyle === 'ENT_QUOTES') {
        entities['39'] = '&#39;';
    }
    entities['60'] = '&lt;';
    entities['62'] = '&gt;';
 
 
    // ascii decimals to real symbols
    for (decimal in entities) {
        symbol = String.fromCharCode(decimal);
        hash_map[symbol] = entities[decimal];
    }
    
    return hash_map;
}

function stripslashes (str) {
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Ates Goral (http://magnetiq.com)
    // +      fixed by: Mick@el
    // +   improved by: marrtins
    // +   bugfixed by: Onno Marsman
    // +   improved by: rezna
    // +   input by: Rick Waldron
    // +   reimplemented by: Brett Zamir (http://brett-zamir.me)
    // +   input by: Brant Messenger (http://www.brantmessenger.com/)
    // +   bugfixed by: Brett Zamir (http://brett-zamir.me)
    // *     example 1: stripslashes('Kevin\'s code');
    // *     returns 1: "Kevin's code"
    // *     example 2: stripslashes('Kevin\\\'s code');
    // *     returns 2: "Kevin\'s code"
    return (str+'').replace(/\\(.?)/g, function (s, n1) {
        switch (n1) {
            case '\\':
                return '\\';
            case '0':
                return '\u0000';
            case '':
                return '';
            default:
                return n1;
        }
    });
}
function rand( min, max ) {	// Generate a random integer
	// 
	// +   original by: Leslie Hoare

	if( max ) {
		return Math.floor(Math.random() * (max - min + 1)) + min;
	} else {
		return Math.floor(Math.random() * (min + 1));
	}
}
var ru2en = { 
  ru_str : "АБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдеёжзийклмнопрстуфхцчшщъыьэюя", 
  en_str : ['A','B','V','G','D','E','JO','ZH','Z','I','J','K','L','M','N','O','P','R','S','T',
    'U','F','H','C','CH','SH','SCH','"','Y',"'",'E','JU',
    'JA','a','b','v','g','d','e','jo','zh','z','i','j','k','l','m','n','o','p','r','s','t','u','f',
    'h','c','ch','sh','sch','"','y',"'",'e','ju','ja'], 
  translit : function(org_str) { 
    var tmp_str = ""; 
    for(var i = 0, l = org_str.length; i < l; i++) { 
      var s = org_str.charAt(i), n = this.ru_str.indexOf(s); 
      if(n >= 0) { tmp_str += this.en_str[n]; } 
      else { tmp_str += s; } 
    } 
    return tmp_str; 
  } 
}

var gm_timeout;
var gm_open_timeout;
var opened_gm_id = '';

function show_gm_menu(gm_id, e, x_offset) {
	if(x_offset == null) {
		x_offset = 0;
	}
    clearTimeout(gm_open_timeout);
    if(opened_gm_id != '' && opened_gm_id != gm_id) {
            hide_gm_menu(opened_gm_id);
            opened_gm_id = '';
    }
    if(opened_gm_id != gm_id) {
            ttmp=mousePageXY(e);
            document.getElementById(gm_id).style.left = ttmp['x']-215+x_offset;
            opened_gm_id = gm_id;
    }
    gm_open_timeout = setTimeout("document.getElementById('"+gm_id+"').style.display='inline';",200);
}
function hide_gm_menu(gm_id) {
    if(gm_id == '') {
            return true;
    }
    document.getElementById(gm_id).style.display='none';
    if(gm_timeout != null) {
            clearTimeout(gm_timeout);
    }
}

function disableEnterKey(e)
{
	var key;

	if(window.event)
		key = window.event.keyCode;     //IE
	else
		key = e.which;     //firefox

	return (key != 13);
}
