
$().ready(function(){
	
	//scrolling
	
	function scrollpane(){
		$('#brands').jScrollPane({showArrows:true}); //scrollbarWidth:20
	}
	
	$('.cat_title_slider .spl div').click(function(){ /// move to tamplates
		var $search = $('.cat_title_slider .search');
		
		$search.animate({width: $search.hasClass('search_on') ? 180 : 530}, 200); // width of ".search_on" |".search"
		
		$search.toggleClass('search_on');
		$('.cat_title_slider .slider .content_wrp').toggleClass('content_short');
		
		scrollpane();
	});
	
	scrollpane();
	
});

function slide(){
	var $choice = $(this);
	
	if ($choice.parent().hasClass('sel')) //click on selected
		return;
	
	//init
	var $sel = $('.cat_title_slider .tabs .sel div.deco');
	
	var pos = $choice.position();
	var spos = $sel.position();
	var height = $choice.height();
	var sheight = $sel.height();
	
	//move
	$sel.animate({left: pos.left}, 100, function(){ 
		$sel.animate({height: height}, 100, function(){ 
			$sel.css('background-image', 'url("' + $sel.attr('img')  + '")'); }); });
			
	$choice.animate({left: spos.left}, 100, function(){ 
		$choice.animate({height: sheight}, 100, function(){ 
			$choice.css('background-image', 'url("' + $choice.attr('simg')  + '")'); 
			
			//change selection
			$sel.parent().removeClass('sel');
			$choice.parent().addClass('sel');
		}); 
	});
	
	//show tab info
	$('.cat_title_slider .slider .content #c' + $sel.attr('id').substr(1)).removeClass('top');
	$('.cat_title_slider .slider .content #c' + $choice.attr('id').substr(1)).addClass('top');
}

$.fn.cb = function(handler){
	
	var $$this = this;
	
	this.each(function(i){
		
		var $this = this;
		
		$('div.t', $this).click(function(e){ 
			$('.list', $$this).slideUp('fast');
			
			$('.list', $this).slideToggle('fast'); //this.parent()
			e.stopPropagation(); e.preventDefault();
			
			$().bind('click', function(e){ 
				$('.list', $this).slideToggle(); 
				e.stopPropagation(); 
				e.preventDefault(); 
				$().unbind('click'); 
				
				return false; 
			});
			
			return false;
		});
		
		$('.list div', $this)
			.hover(function(){ $(this).toggleClass('sel'); }, function(){ $(this).toggleClass('sel'); })
			.click(function(){ /*$this.slideUp();*/ 
				$('div.t span', $this).text($(this).text());
				$('div.t div input', $this).val($(this).attr('value'));
				
				handler($(this)); 
			});
		
	})
	
	return this;
}


/*utilities*/
$.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'){
		$.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';
	if (!req.datatype) req.datatype = 'html'; //xml
	if (!req.params) req.params = {};
		
	$.ajax({
		type: "GET",
		data: req.params, //.implode()
		cache: cache,
		url: uri,
		beforeSend: function(xhr){ xhr.setRequestHeader("Content-type", req.type); },
		dataType: req.datatype,
		success: callback,
		error: function(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);
		
		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.focusin(click).focusout(click);
	
	return $this;
}

/*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 TrimString(sInString){
	sInString = sInString.replace(/ /g,’ ‘);
	return sInString.replace(/(^\s+)|(\s+$)/g, “”);
}*/
String.prototype.trim = function(){
	return this.replace(/ /g, ' ').replace(/(^\s+)|(\s+$)/g, '').replace(/(^&nbsp;+)|(&nbsp;+$)/g, ' ');
}

String.prototype.humanize = function(){
    if (!this)
    	return;
    
    var price = this;
    var rprice = "";
    
    var prices = price.split(/\.|\,/);
    
    price = prices[0];
    var dec = prices.length > 1 ? prices[1] : '';
    
    var len = price.length;
    var count = Math.round(len / 3);
    var offset = 0;
    var num = 0;
    
    for (var i = 1; i <= count; i++){
        offset = len - i*3; //start index
        num = offset < 0 ? num + offset : 3;
        offset = offset < 0 ? 0 : offset;
        
        rprice = "&nbsp;" + price.substr(offset, num) + rprice;
    }
    
    rprice = price.substr(0, len - count*3) + rprice;
    
    return rprice.trim() + (dec ? "," + dec : '');
}

