function strpos (haystack, needle, offset) {
	var i = (haystack+'').indexOf(needle, (offset ? offset : 0));
    return i === -1 ? false : i;
}
function strrpos (haystack, needle, offset) {
    var i = -1;
    if (offset) {
        i = (haystack+'').slice(offset).lastIndexOf(needle); // strrpos' offset indicates starting point of range till end,        // while lastIndexOf's optional 2nd argument indicates ending point of range from the beginning
        if (i !== -1) {
            i += offset;
        }
    }    else {
        i = (haystack+'').lastIndexOf(needle);
    }
    return i >= 0 ? i : false;
}
function substr (str, start, len) {
    str += '';
    var end = str.length;
    if (start < 0) {        start += end;
    }
    end = typeof len === 'undefined' ? end : (len < 0 ? len + end : len + start);
    return start >= str.length || start < 0 || start > end ? !1 : str.slice(start, end);
}
function init_tabs()
{
	$('.toggle-menu > ul > li').each(function(w){
		var el = this;
		 
		$(el).bind('mouseover',function(){
		cur_tab_element.removeClass('bg-right');
		$(el).addClass('bg-right');});
	
		$(el).bind('mouseout',function(){
		$(el).removeClass('bg-right');
		cur_tab_element.addClass('bg-right');});
	});
}

function confirm_delete(elem, ok_link)
{
	var text = $(elem).html();
	$(elem).parent().parent().append('<div>удалить? <a href="' + ok_link + '">Да</a> / <a href="" onclick="no_delete(this, \'' + ok_link + '\'); return false;" id="no' + $(elem).id + '">Нет</a></div>');
}

function no_delete(link, ok_link)
{
	$(link).parent().remove();
}

var mainType = 'all';
var mainLeft = 'rat';

function viewMain(type, t)
{
	mainType = type;
	mainLeft = t;
	$('#index-top div').removeClass('active');
	if ( type != 'all' ) {
		$('#index-top #line-'+type).addClass('active');
		$('#line-all').html('<a href="#" class="white" onclick="viewMain(\'all\', \''+mainLeft+'\');return false;">все</a><div class="left"></div><div class="right"></div>');
	} else {
		$('#line-all').addClass('active').html('все<div class="left"></div><div class="right"></div>');
	}
	rf = 'return false;';
	
	/*левый блок*/

	$("#i_sort_new").attr("onClick","viewMain('"+type+"', 'new');"+rf);
	$("#i_sort_pop").attr("onClick","viewMain('"+type+"', 'pop');"+rf);
	$("#i_sort_rat").attr("onClick","viewMain('"+type+"', 'rat');"+rf);
	$('.i_nav li').removeClass();
	$("#i_sort_"+mainLeft).parent().addClass('i_nav_now');

	
	/* верхний блок */
	$('#index-top .want a').attr("onClick","viewMain('want', '"+mainLeft+"');"+rf);
	$('#index-top .buy a').attr("onClick","viewMain('buy', '"+mainLeft+"');"+rf);
	$('#index-top .have a').attr("onClick","viewMain('have', '"+mainLeft+"');"+rf);
	$('#index-top .sale a').attr("onClick","viewMain('sale', '"+mainLeft+"');"+rf);
	$('#index-top .own a').attr("onClick","viewMain('own', '"+mainLeft+"');"+rf);
	
	$("#main-block-product").html('Загрузка...');
	$.getJSON(
		"/product/mainblock/", 
		{'type': type, 't': t}, 
		function(data) {
			$("#main-block-product").html('');
			var photo_path = '';
			var pos = 0;
			for ( var i = 0, len = data.length; i < len; ++i ) {
	            
				var item = data[i];
	            var item_rating = '<ul class="i-rating">';
	            for ( var i2 = 1, len2 = item.total_grade; i2 <= len2; ++i2 )
	            {
	            	item_rating = item_rating + '<li class="rating'+i2+'"></li>';
	            }
	            item_rating = item_rating + '</ul>';
	            if (item.photo_path) {	            	
	            	photo_path = item.photo_path;	            		            		            	
	            	pos = strrpos(item.photo_path,'/')+1;	            	
	            	photo_path = substr(item.photo_path,0,pos)+'index_'+substr(item.photo_path,pos);	            	
	            	if (substr(photo_path,strrpos(photo_path,'.')+1)=='jpg') {
	            		photo_path = substr(photo_path,0,strrpos(photo_path,'.'))+'.jpeg';	            		
	            	}
	            } else {
	            	photo_path = item.photo_path; 
	            }
	            var _html =
	        	 	'<div class="i_item" id ="main-block-product-'+i+'">'+
	                '    <div class="img">'+
	                '    	<a class="bg" href="/product/show/' + item.product_slug + '/">'+
	                '    	<img src="'+ (photo_path || '/i/default.gif') +'" alt="">'+
	                '        </a>'+
	                '   <ul class="i_item_show" id="stat_active_'+i+'">'+
		            '	<ul>'+
		            '		<li id="twant_'+i+'" class="twant"><a href="/product/user/' + item.product_id + '/want/">'+ (item.counts.want || 0) +' хотят</a></li>'+
		            '		<li id="tbuy_'+i+'" class="tbuy"><a href="/product/user/' + item.product_id + '/buy/">'+ (item.counts.buy || 0) +' покупают</a></li>'+
		            '		<li id="thave_'+i+'" class="thave"><a href="/product/user/' + item.product_id + '/have/">'+ (item.counts.have || 0) +' владеют</a></li>'+
		            '		<li id="tsale_'+i+'" class="tsale"><a href="/product/user/' + item.product_id + '/sale/">'+ (item.counts.sale || 0) +' продают</a></li>'+
		            '		<li id="town_'+i+'" class="town"><a href="/product/user/' + item.product_id + '/own/">'+ (item.counts.own || 0) +' имели</a></li>'+
		            '	</ul></ul>'+
	                '    </div>'+
	                '    <h6><a href="/product/show/' + item.product_slug + '/">'+ item.product_name +'</a><span></span></h6>'+
	                '    <div class="item_rating">'+item_rating+'<span class="num">'+ (item.count_users || 0) +'</span></div>'+
	                '</div>';

	            $("#main-block-product").append(_html);
	            $('#stat_active_'+i+' ul li.t'+type).html( '<div class="now">' + $('#main-block-product-'+i+' li.t'+type).html() + '</div><div class="now-l"></div>' ).css('height','16px');
		        if (type != 'all') {
		            $('#main-block-product-'+i+' .i_item_show').prepend('<li id="fshow_'+i+'" class="t'+ type+'"><div class="now">'+ eval('item.counts.' + type + ' || 0') +'</div><div class="now-l"></div></li>');
		            	
		        draw_status('stat_active_'+i);

		        }
			}
			if ( data.length == 0 )
				$("#main-block-product").html('К сожалению, вещи не найдены.');
	
			if (t=='rat') {
				var sort = 'rating';
			} else {
				if (t=='pop') {
					var sort = 'grade';
				} else {
					var sort = 'new';
				}
			}
			
			if ( type == 'all' ) {
				$("#main-block-product").append('<div class="view_all"><a href="/product/?sort='+sort+'">Посмотреть все</a></div>');
			} else {
				$("#main-block-product").append('<div class="view_all"><a href="/product/?status='+type+'&sort='+sort+'">Посмотреть все</a></div>');
			}




		}
	);

}

function draw_status(id) {
	var mainmenu=$('#'+id);
	mainmenu.each(function(i){
		var mainmenu=$(this);
		var subul=$(this).find('ul:eq(0)');

		mainmenu.hover(
			function(e){
				var targetul=$(this).children("ul:eq(0)");
				targetul.fadeIn();
				$(this).find('li:eq(0)').hide();
					},
			function(e){
				var targetul=$(this).children("ul:eq(0)");
				targetul.css({display:'none', visibility:'visible'});
				targetul.parent().find('li:eq(0)').show();
			}
		) //end hover
	}) //end $headers.each()
	mainmenu.find("ul").css({display:'none', visibility:'visible'});
	
}


function ajaxBlockC (order,filtr) 
{
	if (order == 'rat') {
		$("#sort-c-rat").html('рейтинг &#8595;');
		$('#sort-c-user').html('<a href="#" onclick="ajaxBlockC(\'user\',\''+filtr+'\');return false;">пользователи</a>');
	} else {
		$('#sort-c-user').html('пользователи &#8595;');
		$("#sort-c-rat").html('<a href="#" onclick="ajaxBlockC(\'rat\',\''+filtr+'\');return false;">рейтинг</a>');		
	}
	if (filtr == 'week') {
		$("#filtr-c-week").html('за неделю');
		$("#filtr-c-all").html('<a href="#" onclick="ajaxBlockC(\''+order+'\',\'all\');return false;">за всё время</a>');
		$("#filtr-c-week").addClass('top_com_now');
		$("#filtr-c-all").removeClass('top_com_now');
	} else {
		$("#filtr-c-all").html('за всё время');
		$("#filtr-c-week").html('<a href="#" onclick="ajaxBlockC(\''+order+'\',\'week\');return false;">за неделю</a>');
		$("#filtr-c-all").addClass('top_com_now');
		$("#filtr-c-week").removeClass('top_com_now');		
	}
	$('#block-c-ajax').html('Загрузка...');
	$.getJSON("/blog/ajaxblock/", {'order': order, 'filtr': filtr}, function(data)
	{
		$('#block-c-ajax').html('');
		for ( var i = 0, len = data.length; i < len; ++i ) 
		{
			var item = data[i];
			$('#block-c-ajax').append('<div class="onec_in_top"><div class="cpic"><img src="'+item.photo+'" alt=""></div><div class="cname"><a href="'+item.uri+'">'+item.name+'</a><span></span></div><div class="ratio">'+item.rating+'</div><div class="num_users"><a href="/blog/showusers/'+item.id+'/">'+item.countUsers+'</a></div></div>');
		}
	});
	return false;	
}

function ajaxBlockU (order,filtr) 
{
	if ( order == 'rat' ) {
		$("#sort-u-rat").html('рейтинг &#8595;');
		$('#sort-u-product').html('<a href="#" onclick="ajaxBlockU(\'product\',\''+filtr+'\');return false;">вещи</a>');
	} else {
		$('#sort-u-product').html('вещи &#8595;');
		$("#sort-u-rat").html('<a href="#" onclick="ajaxBlockU(\'rat\',\''+filtr+'\');return false;">рейтинг</a>');		
	}
	if (filtr == 'week') {
		$("#filtr-u-week").html('за неделю');
		$("#filtr-u-all").html('<a href="#" onclick="ajaxBlockU(\''+order+'\',\'all\');return false;">за всё время</a>');
		$("#filtr-u-week").addClass('top_u_now');
		$("#filtr-u-all").removeClass('top_u_now');	
	} else {
		$("#filtr-u-all").html('за всё время');
		$("#filtr-u-week").html('<a href="#" onclick="ajaxBlockU(\''+order+'\',\'week\');return false;">за неделю</a>');
		$("#filtr-u-all").addClass('top_u_now');
		$("#filtr-u-week").removeClass('top_u_now');	
	}
	$('#block-u-ajax').html('Загрузка...');
	$.getJSON("/user/ajaxblock/", {'order': order, 'filtr': filtr}, function(data)
	{
		$('#block-u-ajax').html('');
		for ( var i = 0, len = data.length; i < len; ++i ) 
		{
			var item = data[i];
			$('#block-u-ajax').append('<div class="oneu_in_top"><div class="userpic"><img src="'+ item.userpic +'" width="36" height="36" alt=""><div class="bg"></div></div><div class="username"><a href="'+ item.uri +'" class="red">'+ item.nick +'</a></div><div class="ratio">'+ item.rating +'</div><div class="num_things"><a href="/userproduct/list/'+ item.nick +'/">'+ item.countProducts +'</a></div></div>');
		}
	});
	return false;	
}

function ajaxBlockComment (order) 
{
	if ( order == 'blog' )
	{
		$("#sort-comment-product").html('<a href="#" onclick="ajaxBlockComment(\'product\');return false;">продукты</a>');
		$('#sort-comment-blog').html('сообщества &#8595;');
	}
	else
	{
		$("#sort-comment-product").html('продукты &#8595;');
		$('#sort-comment-blog').html('<a href="#" onclick="ajaxBlockComment(\'blog\');return false;">сообщества</a>');
	}
	
	$('#sbcom').html('Загрузка...');
	$.getJSON("/comment/ajaxblock/", {'order': order}, function(data)
	{
		$('#sbcom').html('');
		if( order == 'blog' ) {
			for ( var i = 0, len = data.length; i < len; ++i ) 
			{
				item = data[i];
				var tmp = '';
	        	tmp += '<li>';
	        	tmp += '<div class="userpic"><img src="' + item.userpic + '" alt=""><div class="bg"></div></div>';
	        	tmp += '<a href="/blog/post/' + item.object_id + '/#comment' + item.id + '" class="com">' + item.text + '</a>';
	        	tmp += '<br>' + item.gender + ' <a href="/user/' + item.usernick + '/" class="red">' + item.usernick + '</a> ' + item.human_date + ', в сообществе <a href="/blog/show/' + item.blog_id + '/">' + item.blog_name + '</a>&nbsp;&rarr;&nbsp;<a href="/blog/post/' + item.object_id + '/" class="gray">' + item.object_title + '</a>';
	        	tmp += '</li>';
	        	
	        	$('#sbcom').append(tmp);
			}
		} else {
			for ( var i = 0, len = data.length; i < len; ++i ) 
			{
				item = data[i];
				var tmp = '';
	        	tmp += '<li>';
	        	tmp += '<div class="userpic"><img src="' + item.userpic + '" alt=""><div class="bg"></div></div>';
	        	tmp += '<a href="' + item.uri + '" class="com">' + item.text + '</a>';
	        	tmp += '<br> ' + item.gender + ' <a href="' + item.user_uri + '" class="red">' + item.usernick + '</a>'; 
	        	tmp += '&nbsp;<span title="' + item.date + '">' + item.human_date + '</span> для <a href="' + item.object_uri + '">' + item.object_name + '</a>';
	        	tmp += '</li>';
	        	$('#sbcom').append(tmp);
			}
		}
	});
	return false;	
}
// перенес из js.js

function fakebutton(id) {

	$('.wrap_'+id).wrapInner('<div class="fakeButton bt_'+id+'"></div>').append('<div class="thisfilename name_'+id+'"></div>');
	$('.bt_'+id+' > input').addClass('customFile file_'+id);
	
	$('.bt_'+id).hover( 
		function() {
			$(this).addClass('activeBrowseButton')}, 
		function () {$(this).removeClass('activeBrowseButton')}
	);
    $('.file_'+id).change(
		function(){
			$('.name_'+id).text($(this).val());
	});
}

function f1 (object) {
$("#rub-body span").attr("class","");

$("#rub-body a.expand").show();
$(object).hide();
$(object).parent('div').children('span').attr("class","show");

return false;	
}

function fav_ico () {
	/* получаем фавиконку у сторонних сайтов */
	$('a.ext[href^="http://"]').filter(function(){
	  return this.hostname && this.hostname !== location.hostname;
	  }).each(function() {
	      var link = $(this);
	      var faviconURL =
	      link.attr('href').replace(/^(http:\/\/[^\/]+).*$/, '$1')+'/favicon.ico';
	      var faviconIMG = $('<img src="/i/favicon.png" alt="" class="favicon">')['insertBefore'](link);
	      var extImg = new Image();
	      extImg.src = faviconURL;
	      if (extImg.complete)
	      faviconIMG.attr('src', faviconURL);
	      else
	      extImg.onload = function() { faviconIMG.attr('src', faviconURL); };
	      });	
	/* получили */
}

function limitText(limitField, limitCount, limitNum) {
    if (limitField.value.length > limitNum) {
        limitField.value = limitField.value.substring(0, limitNum);
    } else {
        limitCount.value = limitNum - limitField.value.length;
    }
}
$(document).ready(function(){
	fav_ico();
	
	$("#scrollable").scrollable({horizontal:true}).mousewheel();
	
	$(".overlay").overlay();
	
	$("a[rel^='prettyPhoto']").prettyPhoto();

	$(".add").click(function(){
		$("#add-input").val($("#search-input").val());
		$("#search").animate({"top": "-500px"}, "fast").hide();
		$("#add").fadeIn("slow");
		return false;
	});

	$("#add .r").click(function(){
		$("#search-input").val($("#add-input").val());
		$("#add").hide();
		$("#search").animate({"top": "0px"}, "fast").fadeIn("slow");
		return false;
	});
	

	$(".opinion").click(function(){
		 $(".opinion_edit").css("visibility","visible");
		return false;
	});		

	$("#acclear").click(function(){	$('.ctype-bg').removeClass("ctype-bg").addClass("otype");
									$('.ctype-l').remove();});
	
	/*
	 * перенесено в шаблон
	$("#dtype").click(function(){$(".types").slideToggle("slow").toggleClass("active");});
	*/
	

	/* рубрикатор */
	$('#rubshow').click(function () {$("#rub-wrap").slideToggle("slow").toggleClass("active");});

	$("a[rel^='prettyPhoto']").prettyPhoto({theme:'light_rounded'});
	
	/* Checkboxes */
	$('.checkall').click(function(){
		if($('.checkall').hasClass('checkall')){
			$('.check').attr('checked', 'checked')
			$('.checkall').addClass('uncheckall').removeClass('checkall')
		}
		else{
			$('.check').removeAttr('checked', 'checked')
			$('.uncheckall').addClass('checkall').removeClass('uncheckall')
		}
	})
	
	$('#search_form').bind('submit',function(){
		var search_string = $('#search-input').val(); 
		if (search_string.length>=2) {
			return true;
		} else {
			Alert.show('', 'Поисковый запрос не может содержать<br />менее 2-х символов!', 'error');
			return false;			
		}
	});	
});