function stLoader(display, wrapper) {
	if( wrapper === undefined) wrapper='#main';
	if (display) {
		jQuery(wrapper).append('<div id="stLoader"></div>');
	} else {
		jQuery(wrapper).find("#stLoader").remove();
	}
}


function imgcheffect(img,  filename) {
	jQuery(img).parent().append('<img style="position:relative; display:none; z-index:0;" src="'+filename+'" id="temp">');
	var TempImage=jQuery(img).parent().children('#temp').fadeTo('fast', 0);
	stLoader(true, jQuery(img).parent());
	jQuery(TempImage).bind('load',function(e, newimg, img){
		if (!newimg) return;
		stLoader(false, jQuery(img).parent());
		if (jQuery(img).attr('src')=='undefined') {
			jQuery(TempImage).fadeTo('fast', 1);
			return;
		};
		jQuery(img).animate({
			  opacity:0
		}, 500, 'linear', function() {
			jQuery(newimg).animate({
					  opacity:1
				}, 500,'linear', function(){
					jQuery(img).remove();
					jQuery(newimg).attr('id', '');
					jQuery(newimg).css('z-index','99');
				})
			}			
		);
			
		
	}).trigger('load', [TempImage, img]);	
}

function fillLots(data) { 		
	    //-- заполняем постраничную навигацию
	    var paginator=data["paginator"];
	    var ifcur;
	    jQuery("#paginator ul").html('');
	    if (paginator["pages"]==0) {
	    	jQuery("#paginator ul").append('<li>нет страниц</li>');
	    }
	    for (var i=1; i<=paginator["pages"]; i++) {
	    	ifcur=(paginator["paged"]==i)? 'cur':'';
	    	jQuery("#paginator ul").append('<li><a class="pg_page '+ifcur+'" id="'+i+'" href="'+paginator['link']+'/page/'+i+'">'+i+'</a></li>');
	    }	  
	  	$('div.isnew').remove();	    
	    //-- Заполняем таблицу товарами
	    jQuery.each(jQuery('#tlots td'), function(index){
			if (!data[index]) {
			  data[index]={};
			  data[index].prev_small='';
			  data[index].prev_big='';
			  data[index].descr='';	
			  data[index].link='';	
			  data[index].title='';
			  data[index].instock='';
			  data[index].article='';
			  data[index].price='';
			  data[index].isnew='';
			}
			var lot=jQuery(this).find('.lot');
			var img=jQuery(lot).find('img');
			var descr=jQuery(lot).find('.descr p.text');
			var link=jQuery(lot).find('a.link');
			var article=jQuery(lot).find('.descr p.article');
			var price=jQuery(lot).find('.descr p.price');
			if (jQuery(lot).hasClass('big')) { //-- 
				imgcheffect(img,  data[index].prev_big);
			} else { //-- 
				imgcheffect(img,  data[index].prev_small);
			}
			jQuery(article).html(data[index].article);
			jQuery(price).html(data[index].price);
			jQuery(descr).html(data[index].descr);
			jQuery(lot).addClass(data[index].instock);
			if ( data[index].isnew=='isnew') {
				$(lot).append('<div class="isnew"></div>');
			}
			jQuery(link).attr('href', data[index].link);
	    });
}

jQuery(document).ready(function($){
	$.each($('ul#ulfeatures li.d0'), function(index){ //-- устанавливаем у подменюшек минимальный размер как у предка
	  $(this).children('ul').css('min-width', parseInt($(this).css('width'))-1);
	});
		
	$('ul#ulfeatures li.d0').mouseover(function() { //-- показываем подменюшки
	  $(this).children('ul').css('display', 'block');
	  $(this).children('ul').fadeTo(0, .9);
	}).mouseout(function(){
	  $(this).children('ul').css('display', 'none');
	});
	
	
	$('INPUT.number').spinbox({
		min:1,
		max:500,
		step:1
	});

	$('.bubbleInfo').each(function () {
        var distance = 10;
        var time = 250;
        var hideDelay = 500;

        var hideDelayTimer = null;

        var beingShown = false;
        var shown = false;
        var trigger = $('.trigger', this);
        var info = $('.popup', this).css('opacity', 0);


        $([trigger.get(0), info.get(0)]).mouseover(function () {
            if (hideDelayTimer) clearTimeout(hideDelayTimer);
            if (beingShown || shown) {
                return;
            } else {
                beingShown = true;

                info.css({
                    top: 45,
                    left: -130,
                    display: 'block'
                }).animate({
                    top: '-=' + distance + 'px',
                    opacity: 1
                }, time, 'swing', function() {
                    beingShown = false;
                    shown = true;
                });
            }

            return false;
        }).mouseout(function () {
            if (hideDelayTimer) clearTimeout(hideDelayTimer);
            hideDelayTimer = setTimeout(function () {
                hideDelayTimer = null;
                info.animate({
                    top: '-=' + distance + 'px',
                    opacity: 0
                }, time, 'swing', function () {
                    shown = false;
                    info.css('display', 'none');
                });

            }, hideDelay);

            return false;
        });
    });
	
	
	
	$('.addbutton').live('addcomplete', function(e, data) { 
		if ($(this).hasClass('Bag')) {
			$(".totalPrice").html(data['price']);			
		}		
	});
	
	$('.deletebutton').live('deletecomplete', function (e, data) {
		if ($(this).hasClass('Bag')) {
			$("#llot"+data['id']).hide('slow');
			$(".totalPrice").html(data['price']);
		}
	});
	
	$(".toBag").click(function(){
		if ($(this).hasClass('active')) return;
		$('#lbToBag').lightbox_me({
				centered: true, 
				destroyOnClose: false,
				onLoad: function() { 
					
				}
		});
	});
	
	$('.sub_preview').click(function(){
		a=$(this);
		showPrev($(a));
	});
	
	function showPrev(a) {
		stLoader(true, '.main_preview');
		$.get('/maginza?action=getattach&size=main_preview&lot='+$(a).attr('id'), function(data){
			$('.attachment-main_preview').remove();
			$('.main_preview').append(data);
			$('.cur').removeClass('cur');
			$(a).addClass('cur');
			stLoader(false);
		});
	}
	
	$('#arrleft').click(function(){
			if (($('.cur').length==0)||($('.cur').prev('.sub_preview').length==0)) {
				showPrev($('.sub_preview:last'));
			} else {	
				showPrev($('.cur').prev('.sub_preview'));				
			}			
			return false;
	}); 
	
	$('#arrright').click(function(){
			if (($('.cur').length==0)||($('.cur').next('.sub_preview').length==0)) {
				showPrev($('.sub_preview:first'));
			} else {	
				showPrev($('.cur').next('.sub_preview'));				
			}		
			return false;
	}); 
	
	$('#features').on({
		loadprep: function(e, params){	
  			
  			var features='', sep='';
  			$.each($('.cur-term'), function(index){ //-- собираем все характеристики в одну
  				features=features+sep+$(this).attr('id');
	  			sep=',';
	  		});
	  		return {features: features};
  		},
  		loadcomplete: function(e, params) {
  				if ('features' in params) {  				
  				var features=params.features.split(','), ftitle='';
  				$("#features a.cur-term").removeClass('cur-term')
  				var  ftitle='';
  				for (key in features) {
  					if (features[key]=="") continue;
  					ftitle=': '+$("#features a#"+features[key]).text();
  					$("#features a#"+features[key]).addClass('cur-term').parents('li.d0').children('a').children('span').text(ftitle);;
  				}  				
  			}	
  		}
	});
	
	//delegate $('#features').
	$('#features').on({ //--загружаем товары с выбранными характеристиками
  		click: function(){
  			  a=$(this);
			  var  ftitle=': '+$(a).text();
			  $(a).parent().parent().parent().find('.cur-term').removeClass('cur-term');
			  $(a).addClass('cur-term').parents('li.d0').children('a').children('span').text(ftitle);
			  navigate({}, $(a));
			  return false;
  		}  		
	}, 'ul.dropdown li a');	
	
	//bind
	$('#finstock #instock').on({  //-- выбираем товары которые есть на складе
		click: function() {				
			navigate({}, $(this));			
	    },
	    loadprep: function(e,param){
	    	return ($("#instock").is(':checked'))? { instock:'instock' } : {instock:''};	    				
		},
		loadcomplete: function (e, params) {
			if ('instock' in params) {
				if (params.instock=="instock") { 
					$("#instock").attr('checked','checked');
				} else {
					$("#instock").removeAttr('checked');
				}	
			}
		}	    
	});	
	
	$("#paginator").on({
		loadprep: function(e, params) {
			if ($("a.pg_page.cur").length==0) return; //--если нет страниц
			if ($(params.target).hasClass('pg_page')) {
				return {paged:parseInt($(params.target).attr('id'))};
			} else {
				return {paged:parseInt($("a.pg_page.cur").attr('id'))};
			}			
		},
		loadcomplete: function (e, params){
			var pag=params.loaddata['paginator'];
			if (pag['pages']==0) return;
			if (pag['paged']>pag['pages']) { //--  перебор со страницей
				navigate({}, $("a.pg_page#1"));				
				return;
			}
			if ( ('paged' in params)&&($("a.pg_page.cur").attr('id')!=params.paged) ) {			
				$("a.pg_page.cur").removeClass('cur');
				$("a.pg_page.cur#"+params.paged).addClass('cur');
			}
		},
		loaderror:function(e, params){
			navigate({}, $("a.pg_page#1"));	
		}		
	});
	//delegate	
	$("#paginator").on({
		click: function(e){
			navigate({}, $(this));			
			return false;
		}		
	}, 'a.pg_page');
	
	//bind
	$("#lots").on("loadcomplete", function(e, params){
		fillLots(params.loaddata);
	});
	
	
	
	function ptrigger(ename, params){
		var phevent;
		var result={};
		phevent=new jQuery.Event(ename);
		cache = jQuery.cache;	
		
		for ( i in cache ) {
			if ( cache[ i ].events && cache[ i ].events[ename] ) {
				//$(cache[i].handle.elem).delegateCount=0;
				
				jQuery.event.trigger(phevent, params, cache[i].handle.elem, false);
				$.extend(result,phevent.result);
			}	
		}
		
		return result;
		
	}
	
	
	
	function navigate(params, target) {		
		params.target=target;
		var loadparams=ptrigger('loadprep', params);		
		load(loadparams);		
	}
	
	function load(params) {
		var sep='', hash='';
		for (key in params) {
			hash=hash+sep+key+'='+params[key];
			sep='&';
		}		
		var pn=document.location.protocol+'//'+document.location.host+document.location.pathname+document.location.search;
		var qu=(pn.indexOf("?")>0)? '&' : '?';		
		$.get(pn+qu+hash+'&metod=ajax', function(data){
			params.loaddata=$.parseJSON(data);			
			if (document.location.href.indexOf("#")==-1) {nochhash=true;}
			nochhash=true;
			document.location.hash=hash;
			ptrigger('loadcomplete', params);			
		}).error(function(e){ //-- если ошибка загрузки
			ptrigger('loaderror', {error:'error'});
		});		
	}
	
	function hashch() {
		
		//TODO: параметры из document.location.search перенести в hash
		if (!nochhash) {
			var hash=document.location.hash;	
			var reg = new RegExp("([a-z0-9-]*)=([a-z0-9-]*)", "ig"); //-- разбираем хэш по параметрам
			var params={};		
			while ((param = reg.exec(hash)) != null) {
				params[param[1]]=param[2];
			}		
			load(params);
		}	
		nochhash=false;
	}
	
	$(window).bind('hashchange', hashch);
	nochhash=false; //-- если следующее событие изменения хэша обрабатывать не надо, например при изменении хэша из скрипта
	
	hashch();
});
