
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;
	}
 
}
// вместо функции 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' : '';
		}
	}
}

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) {
	if (_input_list == null) {
		_input_list = document.getElementsByTagName('input');
	}
	var ind, id, tr;
	for(var i = 0; i < _input_list.length; i++) {
		ind = _input_list[i].id.indexOf(chb_mask);
		if (ind == 0 && _input_list[i].disabled == false) {
			_input_list[i].checked = true;
			if (tr_mask != '') {
				id = _input_list[i].id.slice(ind+chb_mask.length);
				if (tr = document.getElementById(tr_mask+id)) {
					tr.marked = true;
					tr.style.backgroundColor = '#E1E7CC';
				}
				if (tr_addinfo = document.getElementById(tr_mask+id+'_addinfo')) {
					tr_addinfo.marked = true;
					tr_addinfo.style.backgroundColor = '#E1E7CC';
				}
			}
		}
	}
	return false;
}

function unselect_checkboxes(chb_mask, tr_mask) {
	if (_input_list == null) {
		_input_list = document.getElementsByTagName('input');
	}
	for(var i = 0; i < _input_list.length; i++) {
		ind = _input_list[i].id.indexOf(chb_mask);
		if (ind == 0) {
			_input_list[i].checked = false;
			if (tr_mask != '') {
				id = _input_list[i].id.slice(ind+chb_mask.length);
				if (tr = document.getElementById(tr_mask+id)) {
					tr.marked = false;
					tr.style.backgroundColor = '';
				}
				if (tr_addinfo = document.getElementById(tr_mask+id+'_addinfo')) {
					tr_addinfo.marked = false;
					tr_addinfo.style.backgroundColor = '';
				}
			}
		}
	}
	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) {
			if(_input_list[i].checked == true) {
				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;
 	var main_title = '';
 	var 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[2]+area+" ("+row[9]+")";
 	}
 	
 	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 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);
}
 