
$.fn.rpc = function(uri, req, callback, cache){
	
	//loader
	if (!req.params) req.params = {};
	if (!req.method) req.method = 'get';
	req.params.t = (new Date()).getTime();
	
	/*if (!cache)
		req.params.time = (new Date()).getTime();*/
	
	if (req.method == 'get'){
		/*$().rpcraw(uri, req, function(data, textStatus){ 
			if (textStatus == 'success')
				callback(data, req);
		}, false);*/
		
		$.get(uri, req.params, function(data, textStatus){ 
			if (textStatus == 'success')
				callback(data, req);
		});
	} else {
		$().post(uri, req.params, function(data, textStatus){ 
			if (textStatus == 'success')
				callback(data, req);
		});
	}
}

$.fn.rpcraw = function(uri, req, callback, cache){ //http://api.jquery.com/jQuery.ajax/
	if (!req.type) req.type = 'text/html; charset=utf-8'; //xml
	if (!req.datatype) req.datatype = 'html'; //xml
	if (!req.params) req.params = {};
	
	var cb = callback;
	/*var cb = function(data){
		var xml;
		
		if (typeof data == "string") {
			xml = new ActiveXObject("Microsoft.XMLDOM");
			xml.async = false;
			xml.loadXML(data);
		} else {
			xml = data;
		}
		// Returned data available in object "xml"
		return callback(xml);
	}*/
	
	//.implode()
	$.ajax({
		type: "GET",
		data: req.params,
		cache: cache,
		url: uri,
		dataType: req.datatype, //($.browser.msie) ? "text" : "xml",
		beforeSend: function(xhr){ xhr.setRequestHeader("Content-type", req.type); }, ///
		success: cb,
		error: function(xhr, textStatus, errorThrown){ /*console.log(xhr, textStatus, errorThrown);*/ }
	});
}

$.fn.rpcadd = function(data, what){
	var args = {'success': false};
	
	$(this).each(function(i){
		if (what){
			var target = $(what.replace(/%index%/g, i), data); //*[@class=\'item\']:eq(' + i + ')
			if (!target.length)
				return;
				
			data = target.text();
		}
		
		$(this).html(data);
		
		args.success = true;
	});
	
	return args.success;
}

$.fn.redirect = function(uri, delay){
	var hndl = function(uri){ window.location = uri; }
	
	delay ? window.setTimeout(hndl, delay) : hndl(uri);
}

$.fn._blank = function(e){
	/*if (!e) e = window.event;
	
	e.returnValue = false;
	e.cancelBubble = true;*/
	
	/*if (e)
		return e.currentTarget;
	
	e = window.event;
	return e.srcElement;*/
	
	window.open(e.target.href);
	
	e.preventDefault();
	e.stopPropagation();
	
	return false;
}

$.fn.win = function(src, w, h, scrollBars, resizable) {
	var top = Math.round(window.screen.height/2 - h/2);
	var left = Math.round(window.screen.width/2 - w/2);
	
	var wnd = window.open(src, "untitled-" + Math.ceil(Math.random()*100), "status=no,help=no,resizable="+resizable+",scrollbars="+scrollBars+",width=" + w + ",height=" + h + ",top=" + top + ",left=" + left);
	if (wnd){
		wnd.opener = window; //
		wnd.focus();
	}
	
	return false;
}

$.fn.homepage = function(uri){
	var obj = window.event.srcElement;
	
	if (obj != undefined){
		obj.style.behavior = "url(#default#homepage)";
		obj.setHomePage(uri);
	}
	
	return false;
}

$.fn.fav = function(url, as){
	if (window.external != undefined)
		window.external.addFavorite(url, as);
	
	return false;
}

$.fn.isEmpty = function(val){
	if (typeOf(val) !== 'object')
		return true;
	
	var i, v;
		
	for (i in o){
		v = val[i];
		if (v !== undefined && typeOf(v) !== 'function')
			return false;
	}
	
	return true;
}

$.fn.typeOf = function(value){
	var s = typeof value;
	
	if (s !== 'object' || !value)
		return s;
		
	if (typeof value.length === 'number' && !(value.propertyIsEnumerable('length')) && typeof value.splice === 'function')
		s = 'array';
	else if (s == 'object')
		s = 'object';
	else
		s = 'null';
		
	return s;
}

$.fn.cookie = function(name, value, duration, path, domain, secure){
	var today = new Date();
	today.setTime( today.getTime() );
	
	if (!duration)
		duration = 60*60*24*365*2*1000;
	
	if (!path)
		path = "/";
	
	if (!domain)
		domain = window.location.hostname;
	
	var expiresDate = new Date( today.getTime() + duration );
	
	document.cookie = name + "=" +escape( value ) +
		( ( duration ) ? ";expires=" + expiresDate.toGMTString() : "" ) + 
		( ( path ) ? ";path=" + path : "" ) + 
		( ( domain ) ? ";domain=" + domain : "" ) +
		( ( secure ) ? ";secure" : "" );
}

$.fn.input = function(){
	
	var $this = this;
	
	var click = function(e){
		//var $this = $(e.target);
		
		$this.toggleClass('focused');
		
		if ($this.attr('type') == 'password'){
			return;
		}
		
		if ($this.val() && $this.attr("ovalue") != undefined && $this.val() != $this.attr("ovalue")){
			$this.addClass('focused');
		}
		
		if ($this.attr("ovalue") == undefined)
			return;
		
		var oval = $this.attr("ovalue");
		
		if (oval){
			if ($this.val() == oval)
				$this.val("");
			else if ($this.val() == "")
				$this.val(oval);
		} else {
			$this.attr("ovalue", $this.val());
			$this.val("");
		}
	}
	
	$this.unbind().focusin(click).focusout(click);
	
	return $this;
}

$.fn.optbox = function(){
	
	var $this = this;
	var $input = $this.find('input:hidden');
	
	$this.find('span').unbind().click(function(){
		$this.find('span').removeClass('sel');
		$(this).addClass('sel');
		
		$input.val($(this).attr('id').replace('ob_', ''));
		
		return false;
	});
	
	return $this;
}

$.fn.choiceDialog = function(style, onSelect, onSelectPath){
	
	if (typeof style != 'object'){
		style = {width:'', height:'', css:'', cls: ''};
	}
	
	var $dialog = $('<div class="choice_dialog"><div class="canvas"></div><div class="choice_block">'
		+'<div class="action"><a href="#" class="do_close">закрыть</a></div><div class="choice_content"></div></div></div>');
	
	var $ch_block = $('.choice_block', $dialog);
	var $canvas = $('.canvas', $dialog);
	
	if (typeof style.css == 'object')	
		$ch_block.css(style.css);
	
	if (style.cls)
		$ch_block.addClass(style.cls);
		
	function close(event, args){
		//$('.choice_dialog', document.body).remove();
		/*$('.choice_dialog').cycle({ 
		    fx: 'zoom', 
		    speed: 100
		    speedIn: 500, 
		    speedOut: 500, 
		    easeIn: null, 
		    easeOut: null, 
		    sync: 0, 
		    delay: -4000
		});*/
		
		$ch_block.removeShadow().css('zIndex', $ch_block.parent().find('.canvas').css('zIndex') + 1000).hide('fold', {}, 2000, function(){ 
			if (args && typeof args.callback == 'function')
				args.callback();
				
			$dialog.remove(); 
		});
		
		return false;
	}
	
	function change(init){
		if (style.height)
			$ch_block.height(style.height);
		
		$ch_block
			//.css({'width': style.width+'px', 'height': style.height+'px'})
			.width(style.width)
			.offset({ 
				top: Math.round($(window).scrollTop() + ($(window).height() / 2) - $ch_block.height() / 2), 
				left: Math.round(($(window).width() / 2) - $ch_block.width() / 2) 
		});
		
		//init ? $ch_block.dropShadow({left: -1, top: -1, blur: 3, opacity: 0.5}) : $ch_block.redrawShadow();
		if (!init)
			$ch_block.redrawShadow();
	}
	
	$('.choice_content', $dialog).append($(this)); //.html()
	$(document.body).append($dialog);
	
	$canvas.height($('body').height()).click(close); //.width($('body').width())
	
	if (style.height)
		$ch_block.height(style.height);
	
	change(true);
	//$('.choice_content', $dialog).hide();
	$ch_block.show('fold', {}, 2000, function(){ $(this).dropShadow({left: -1, top: -1, blur: 3, opacity: 0.5}); $('.choice_content', $dialog).show(); });
	
	if (onSelectPath){
		$('.choice_content ' + onSelectPath, $ch_block).click(function(event){ onSelect($(this)); return close(); }); //a[id]
	}
	
	$('.do_close', $ch_block).click(function(){ return close(); });
	$(this).bind('close', close);
	
	$(this).change(function(){ change(false); });
	
	return $(this);
}

/// make as component
$.fn.hasValue = function(callback){
	if (callback){
		if (callback(this))
			return true;
	}
	
	var $el = $("input[type=hidden],.textbox", this); //.textbox
	if ($el.length){
		var orig = $el.attr("custom") ? $el.attr("custom") : $el.attr("ovalue");
		return $el.val() != "" && $el.val() != orig;
	}
		
	$el = $(".selectbox :selected", this);
	
	return $el.length > 0 && $el.val() != -1;
}

/// make as component
$.fn.showMessage = function(item, key, def){
	if (!key){ key = 'message'; }
	if (!def) { def = 'message'; }
	
	var text = item && item.attr(key) ? item.attr(key) : this.attr(def);
	var message = this.eq(0).clone().text(text).removeAttr(key);
	//console.log(item, key, def, text, message);
	
	if (item){
		$('.'+key, item).remove();
		
		var $el = $('.input > *:last', item);
		if ($el.length){
			$el.after(message);
		} else if (item.attr('message_target')){
			$(item.attr('message_target')).append(message); //'.msg', 
		}
	} else {
		this.text(text);
	}
}

/*function redirect(el){
	
	/// combo
	
	var value = el.options[el.selectedIndex].value;
	if (value == -1)
		return;
		
	window.location = value;
}*/

/*$.fn.minWidth = function(minvalue, value){
	return document.body.offsetWidth <= minvalue ? minvalue - 5 + "px" : value + "%";
}*/

$.fn.currentScroll = function(dir){
	return dir == 'v' 
		? this.pageYOffset || (document.documentElement && document.documentElement.scrollTop) || (document.body && document.body.scrollTop)
		: this.pageXOffset || (document.documentElement && document.documentElement.scrollLeft) || (document.body && document.body.scrollLeft);
}

$.fn.clientSize = function(dir){
	return dir == 'v' 
		? (document.compatMode == 'CSS1Compat' ? document.documentElement.clientHeight : document.body.clientHeight)
		: (document.compatMode == 'CSS1Compat' ? document.documentElement.clientWidth : document.body.clientWidth);
}

//Object.prototype.implode = Array.prototype.implode 
var List = function(what){ //new
	//return new List.fn.init();
	
	this.context = what;
	
	if (List.prototype._)
		return List.prototype;
	
	return List.prototype = {
		_: true,
		implode: function(spl, del){
			var str = '', k = 0;
			
			//this.context
			
			if (!spl) spl = '=';
			if (!del) del = '&';
			
			for (var i in context)
				if (typeof context[i] != 'function' && typeof context[i] != 'object')
					str += (k++ ? del : '') + i + spl + context[i];
			
			return str;
		}
	};
}

String.prototype.isEmail = function(){
	if (!this.length) return false;
	
	re = /.@{1}[0-9A-Za-z\-]{1,}\.{1}[A-Za-z]{2,4}/
	return re.test(this);
}

function seq(value, label1, label2, label3){
	/*val = new String(value);
	lc = val.substring(value.length - 1, 1);
	lc = value[value.length - 1];*/
	
	var str = new String(value);
	lc = str.substr(str.length - 1, 1);
	//console.log(lc, value, label1, label2, label3);
	if (value > 10 && value < 20){
		return label3;
	} else {
		switch(lc*1){
			case 1:
				return label1;
			case 2:
			case 3:
			case 4:
				return label2;
			case 5:
			case 6:
			case 7:
			case 8:
			case 9:
			case 0:
				return label3;
		}
	}
}
