//oop
/*Function.prototype.method = function (name, func)
{
	this.prototype[name] = func;
	return this;
};

Function.method('inherits', function (parent)
{
	var d = {}, p = (this.prototype = new parent());
	
	this.method('uber', function uber(name)
	{
		if (!(name in d))
		{
			d[name] = 0;
		}        
		
		var f, r, t = d[name], v = parent.prototype;
		if (t)
		{
			while (t)
			{
					v = v.constructor.prototype;
					t -= 1;
			}
			f = v[name];
		}
		else
		{
			f = p[name];
			if (f == this[name]) f = v[name];
		}
		d[name] += 1;
		r = f.apply(this, Array.prototype.slice.apply(arguments, [1]));
		d[name] -= 1;
		return r;
	});
	
	return this;
});

Function.method('swiss', function (parent)
{
	for (var i = 1; i < arguments.length; i += 1)
	{
		var name = arguments[i];
		this.prototype[name] = parent.prototype[name];
	}
  
	return this;
});
//oop*/

function define(tplName, tplVal)
{
	try { eval(tplName + "=tplVal;") }
	catch(e){ alert(e + 'Ошибка создание шаблона ' + tplName)};	
}

function _each(obj, pFun)
{
	for (var key in obj)
	{
		if ((key != 'indexOf') && (key != 'each'))
		{
			pFun.call(obj, obj[key], key);
		}
	}								
}

var g_odd = 1;

function _t(tpl)
{
	var sText = tpl;
	var pos = 1;
	while (pos < arguments.length)
	{
		var arg1 = arguments[pos];
		var arg2 = (typeof(arguments[pos + 1]) == 'undefined') ? false : arguments[pos + 1];
		if (typeof(arg1) == 'object')
		{
			_each(arg1, function(val, key)
			{				
				if (val != null)
				{
					if (!((val instanceof Object) || (val instanceof Array)))
						sText = _t(sText, key.toString(), val.toString());				
				}
			});
		}
		else if (((typeof(arg1) == 'string') || (typeof(arg1) == 'number'))
						 && ((typeof(arg2) == 'string') || (typeof(arg2) == 'function') || (typeof(arg2) == 'number')))
		{			
			if (typeof(arg2) == 'function')
			{
				sText = arg2(arg1, sText);
			}
			else
			{
				var re = new RegExp('\\#\\{' + arg1 + '\\}', 'ig');
				sText  = sText.replace(re, arg2);
			}
			
			pos ++;		
		}
		else if ((typeof(arg1) == 'string') && ((typeof(arg2) == 'object') || (arg2 instanceof Array)))
		{
			var sMarker = '##' + arg1 + '##';
			var vBegin = sText.indexOf(sMarker);
			var vEnd   = sText.indexOf(sMarker, vBegin + 4);			
			var sBlock = sText.substring(vBegin + 4 + arg1.length, vEnd);			
			var txt  = '';
	
			_each(arg2, function(val, key)
			{
				//val['_key'] = key;
				//val['_odd'] = key % 2;
				g_odd = (g_odd + 1) % 2;
				txt += _t(sBlock, val, '_key', key, '_odd', g_odd);			
			});
			
			sText = sText.substr(0, vBegin) + txt + sText.substr(vEnd + 4 + arg1.length);
			pos++;
		}
		
		pos++;
	}

	return sText;
}

function _tc()
{
	return _c(_t.apply(_t, arguments));	
}

function _c(tpl)
{
	var tx = tpl;
	var pos = 1;
	while (pos < arguments.length)
	{
		
		var arg1 = arguments[pos];
		var arg2 = (typeof(arguments[pos + 1]) == 'undefined') ? false : arguments[pos + 1];
		if (typeof(arg1) == 'object')
		{
			_each(arg1, function(val, key){ if (!val) tx = _c(tx, key, val);});			
		}
		else
		{
			var sMarker = '#!' + arg1 + '!#';
			var vLength = sMarker.length;
			var vBegin  = tx.indexOf(sMarker);
			if (arg2)
			{
				var re = new RegExp(sMarker,'ig');
				tx = tx.replace(re, '');
			}
			else
			{
				while (vBegin >= 0)
				{
					var vEnd = tx.indexOf(sMarker, vBegin + 4);
					tx = tx.substr(0, vBegin) + tx.substr(vEnd + vLength);
					
					vBegin = tx.indexOf(sMarker);
				}					
			}
			
			pos++;
		}		
		pos++;
	}
	
	var res = -1;
	while((res = tx.search(/\#\#([^\#]*)\#\#/ig)) >= 0)
	{
		tx = _t(tx, RegExp.$1, []);
	}
	
	res = -1;
	while((res = tx.search(/\#\!([^\!]*)\!\#/ig)) >= 0)
	{
		tx = _c(tx, RegExp.$1, false);
	}
	return tx.replace(/\#\{[^\}]*\}+/ig, '');
}

function _echo(sMSG)
{
  WScript.Echo(sMSG);
}

function isset(oObj)
{
	if (typeof(oObj) == undefined) return false;
	if (typeof(oObj) == 'boolean') return oObj;
	return (oObj != null);
}

function MailValid(mail)
{
 var re = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
 return (re.test(mail));
} 

function _int(sVal)
{
	return parseInt(sVal);	
}

function _map(data, parent)
{
	_each(data, function(val, key)
	{
		var obj = isset(parent) ? jQuery('#' + key, '#' + parent) : jQuery('#' + key);
		if ((obj.length) && (val != null))
		{
			switch(obj.attr('class'))
			{
				case 'radio_group' :
					obj.radio(val);
					break;
				case 'check_list' :
					break;
				case 'check' :
					obj.check(val);	
					break;
				case 'rate' :
					obj.rate(5, val);
					break;
				default:
					var tag  = obj.get(0).tagName.toLowerCase();
					if (tag == 'img') obj.attr('src', val.toString());
					else
					{
						var tags = 'input;textarea;select;';
						if (tags.indexOf(tag) >= 0) obj.val(val);					
						else obj.html(val.toString());
					}
					break;
			}
		}
	});
}

function TextParse(str)
{
	return str;
}

function _rmap(data, chk_fun)
{
	var res 		= {};
	var bln_res = true;
	
	_each(data, function(val, key)
	{
		if (data instanceof Array) key = val;
		var obj = jQuery('#' + key);
		if (obj.length)
		{									
			if (isset(chk_fun)) bln_res = bln_res & chk_fun(key, obj);
			if (bln_res)
			switch(obj.attr('class'))
			{			
				case 'check' :
					res[key] = obj.check();
					break;
				case 'check_list' :								
					res[key] = obj.checkList();
					break;
				case 'radio_group' :
					res[key] = obj.radio();
					break;
				case 'rate' :
					res[key] = obj.attr('val');
					break;
				default :
					var tag  = obj.get(0).tagName.toLowerCase();
					var tags = 'input;textarea;select;';
					if (tags.indexOf(tag) >= 0) res[key] = TextParse(obj.val());
					else res[key] = TextParse(obj.html());
					break;
			}
		}
	});
	
	if (!bln_res) return false;
	return res;
}

function _union(src, dst)
{
	_each(dst, function(val, key)
	{
		src[key] = val;
	})
}

//data 
//--num_pages : всего страниц
//--curr_page : текущая страница
//--num_recs  : всего записей
//--tpl_href  : шаблон ссылки с параметром #{pg}
//--[max_pages] : максимальное кол-во видимых страниц 
function PageGen(data)
{
	var max_pages = (isset(data['max_pages'])) ? data['max_pages'] : 10;//10 на страницу
	var content 	= '';
	var min = 0;	
	var max = 0;
	
	if (data['curr_page'] >= max_pages)
	{
		min = data['curr_page'] - (data['curr_page'] % max_pages);
		max = min + max_pages;
		if (max > data['num_pages']) max = data['num_pages'];
	}
	else max = (data['num_pages'] > data["max_pages"]) ?  data["max_pages"] : data["num_pages"];
	
	for (var i = min; i < max; i++)
	{
		var active = (data['curr_page'] == i) ? 'class="pg_active"' : 'class="pg"';
		content 	+= _t(data['tpl_href'], 'pg', i, 'pg_str', i + 1, 'active', active);
	}
	
	if (min > 0) content = _t(data['tpl_href'], 'pg', min - 1, 'pg_str', '«', 'active', 'class="pg"') + content;
	if (max < data['num_pages']) content += _t(data['tpl_href'], 'pg', max, 'pg_str', '»', 'active', 'class="pg"');
	
	return '<div class="pages">' + content + '</div>';	
}

//ajax libs
var g_modules = {};
var g_call = {};
var g_fromDispatch = false;

function Dispatch(hash)
{      
	if (hash.length == 0)
	{			
		return;
	}	
	
	var srch = hash.match(/(g\_[a-z\d]+)(\.[a-z\d]+)\((.*)\)/i);
	if (srch != null)
	{
		var args = srch[3].split(',');
		
		_each(args, function(val, key)
		{
			var re = /^[\d\.]+jQuery/;
			if (re.test(val)) args[key] = Number(val);
			else args[key] = new String(decodeURI(val));
		});
		try
		{
			eval('var refObj=' + srch[1] + ';');
			eval('var refFun='  + srch[1] + srch[2] + ';');		
			g_fromDispatch = true;
			refFun.apply(refObj, args);					
		}
		catch(e){};
	}
	
	g_fromDispatch = false;
}
	
function include(sInclude, sCall)
{		
	var sInclude = sInclude;
	var sCall    = sCall;
	
	if (!isset(g_modules[sInclude]))
	{
		var script   = document.createElement("script");
		script.type  = 'text/javascript';
		script.defer = true;
		script.src   = sInclude;
		
		document.getElementsByTagName('head')[0].appendChild(script);		
		
		g_call[sInclude] = 0;
		
		jQuery.timer(400, function(timer)
		 {			 
				if (isset(g_modules[sInclude]))
				{					
					g_call[sInclude] = 0;
					timer.stop();
					if (isset(sCall)) {	try{ eval(sCall);} catch(e){ alert(e)};};				
					return true;
				}
				
				if (g_call[sInclude] > 4)
				{					
					timer.stop();
					alert(sInclude + ' failed');
					return false;
				} else g_call[sCall] ++;				
		 });			
	}
	else
	{
		if (isset(sCall)) {try{ eval(sCall);} catch(e){ alert('Debug On:' + e);};};
		return true;
	}
}

function HashSet(hash)
{
	hash = hash.replace(/^.*#/, '');

	if (jQuery.browser.opera)
	{
		var href = document.location.href.replace(/[\?\&]tm=[^\&]*/i,'').replace(/\#.*/i,'');
		var lab  = (href.indexOf('?') > 0) ? '&' : '?';
		document.location.assign(href + lab + 'tm=' + (new Date()).getTime() + '#' + hash);
	}        
	else
	{         
		jQuery.historyLoad(hash);
	}
}


jQuery.timer = function (interval, callback)
{
 var interval = interval || 100;

 if (!callback)
	 return false;
 
 _timer = function (interval, callback) {
	 this.stop = function () {
		 clearInterval(self.id);
	 };
	 
	 this.internalCallback = function () {
		 callback(self);
	 };
	 
	 this.reset = function (val) {
		 if (self.id)
			 clearInterval(self.id);
		 
		 var val = val || 100;
		 this.id = setInterval(this.internalCallback, val);
	 };
	 
	 this.interval = interval;
	 this.id = setInterval(this.internalCallback, this.interval);
	 
	 var self = this;
 };
 
 return new _timer(interval, callback);
};

function wrap(obj)
{
	if (!isset(obj._precall)) return;
	obj._refs = {};

	var key;	
	for (key in obj)	
	{
		if ((typeof(obj[key]) == 'function') && (key.substr(0,1) != '_'))
		{			
			obj._refs[key] = obj[key];
			obj[key] = new Function('\
				this._precall();\
				this._refs["' + key + '"].apply(this, arguments);\
			');
		}
	}
}
			
function Timer(fun, type, interval, funret)
{
	this.fun      = fun;
	this.interval = interval;
	this.funret   = funret;
	
	var self = this;
	
	this.callBack = function()
	{					
		self.fun[1].apply(self.fun[0], self.fun[2]);
		if (isset(self.funret)) self.funret(self);
	}

	this.start = function()
	{
		this.id = (type == 1) ? setInterval(this.callBack, this.interval) :  setTimeout(this.callBack, this.interval);					
	}
	
	this.stop = function()
	{
		(type == 1) ? clearInterval(this.id) : clearTimeout(this.id);
	}
	
	this.reset = function()
	{
		this.stop();
		this.start();
	}
	
	this.start();
}

function _w(id, data)
{
	jQuery('#' + id).html(data);
}

function _wp(id, data)
{
	jQuery('#' + id).prepend(data);
}

function _wa(id, data)
{
	jQuery('#' + id).append(data);
}

function ObjCopy(data)
{
	var obj = {};
	_each(data, function(val, key)
	{
		if (typeof(val) == 'object') val = ObjCopy(val);
		obj[key] = val;
	});
	
	return obj;
}

function Sort(data, field, desc)
{
	var arr   = [];	
	var field = field;
	var asc 	= isset(asc);
	var comp  = function(a, b)
	{
		if (isset(a) && (!isset(b))) return 1;
		if (isset(b) && (!isset(a))) return 1;
		if ((!isset(b)) && (!isset(a))) return 0;
		if (typeof(a) == 'string') a = a.toLowerCase();
		if (typeof(b) == 'string') b = b.toLowerCase();
		if (a < b) return -1;
		if (a > b) return 1;
		return 0;
	};
	
	_each(data, function(val, key)
	{
		arr.push({key:key, val:val});
	});
	
	arr = arr.sort(function(a, b)
	{
		if (desc)
		{
			var tm = a;
			a = b;
			b = tm;
		}
		
		var bln = (typeof(field) != 'object');
		var fld = bln ? field : field[0];
		var res = comp(a.val[fld], b.val[fld]);
		if ((res != 0) || bln) return res;
		
		var ind = 1;
		while(ind < field.length)
		{
			res = comp(a.val[field[ind]], b.val[field[ind]]);
			if (res != 0) return res;
			ind++;
		}
		
		return res;
	});
	
	var res = {};
	_each(arr, function(val)
	{
		res[val.key] = val.val;
	});
	
	return res;
}

function scrollGet()
{
  var scrollTop;
  var scrollLeft;
  
  if (window.pageYOffset)
  {  
  	scrollTop  = window.pageYOffset; 
  	scrollLeft = window.pageXOffset; 
  } 
  else if(document.documentElement && document.documentElement.scrollTop)
  { 
    scrollTop  = document.documentElement.scrollTop; 
    scrollLeft = document.documentElement.scrollLeft; 
  } 
  else if(document.body)
  { 
  	scrollTop  = document.body.scrollTop; 
  	scrollLeft = document.body.scrollLeft; 
  }       
  return [Number(scrollLeft), Number(scrollTop)];
}

function scrollSet(posX, posY)
{
  posX = Number(posX);
  posY = Number(posY);

  if (window.pageYOffset)
  {  
    //window.pageXOffset = posX;//ff ahtung!!!
    window.pageYOffset = posY;        
  }
  
  else 
  if(document.documentElement && document.documentElement.scrollTop)
  { 
    document.documentElement.scrollLeft = posX; 
    document.documentElement.scrollTop  = posY;     
  } 
  else 
  if(document.body)
  { 
  	document.body.scrollLeft = posX;
  	document.body.scrollTop  = posY;
  }   
}


function URLParse(variable)
{  
  var query = window.location.search.substring(1);
  var vars  = query.split("&");
	var res 	= {};
  for (var i = 0; i < vars.length; i++)
  {
    var pair = vars[i].split("=");
		res[pair[0]] = pair[1];
  }
  
	return res;
}


function remoteImgSize(result, url)
{
  var img  = new Image();
	img.src  = url;
	img.name = 'tmp_' + (new Date()).getTime() + '.jpg';
	img.onerror = function()
	{
		alert("'" + this.name + "' failed to load.");
		return true;
	};
	
	img.onload = function()
	{
		result(img.width, img.height);
	};
	
  return true;
}
