/* ATTACH LENT */

    function CLent( _prm )
    {
        var $lent  = _prm.lent;
        var $pages = _prm.pages;

        var $next = _prm.next;
        var $prev = _prm.prev;

        var visibleBlocks = _prm.visibleBlocks || 2;
        var blockQty = _prm.blockQty;
        var step     = _prm.step;
        var curPage  = 1;

        var direction = _prm.direction || 'left';

/**/
        this.SetBlockQty = function( _qty ){blockQty = _qty;}
        this.SetStep = function( _step ){step = _step;}
/**/
        this.Go2CurPage = function(){
			this.ScrollCurPage();
			this.RefreshView();
        }
/**/
        this.ScrollCurPage = function(){
            var animeteCfg = {}

            animeteCfg[direction] = -step*(curPage-1);

            $lent.animate( animeteCfg, 'fast' );
        }
/**/
        this.RefreshView = function(){
			if($pages)
				$pages.find('li').eq(curPage-1).addClass('cur').siblings().removeClass('cur');

            if( $next != null )
                $next.toggleClass( 'hide', curPage == Math.ceil(blockQty/visibleBlocks) );
            if( $prev != null )
                $prev.toggleClass( 'hide', curPage == 1 );

        }
/**/
        this.BindControl = function(){
            this.BindPages();
            this.BindBtn();
        }
/**/
        this.BindPages = function(){var isThis = this;
			if($pages)
				$pages.find('li').each( function(i){
					$(this).click( function(){
						curPage = i+1; // Set cur Page
						isThis.Go2CurPage();
					});
				});
        }
/**/
        this.BindBtn = function(){var isThis = this;
            if( $next != null )
                $next.click( function(){if( curPage<(blockQty-visibleBlocks+1) ){curPage++;isThis.Go2CurPage();}} );

            if( $prev != null )
                $prev.click( function(){if(curPage>1){curPage--;isThis.Go2CurPage();}} );
        }
/**/
		  this.BuildNavi = function(){
            var html = "";
            var pagesQty = Math.ceil( blockQty/visibleBlocks );
            var i;


            if( blockQty > 0 ){
                html += "<li class='cur'>1</li>"

                for(i=2; i <= pagesQty; i++)
                    html += "<li>"+i+"</li>";
            }

            $pages.html( html );
		  };
/**/
        var cssCfg = {'position' : 'relative'};

        cssCfg[direction] = 0;

        $lent.css( cssCfg );
/**/
    }



    // Lenta Mini
    function CLentMini( _cfg ){
        this.view = _cfg.view;
        this.step = _cfg.step;
        this.borderLeft = _cfg.borderLeft;

        this.timing = 500;
        this.newLeft;


        // API
        this.Next = function(){
            if( !this.view.is(':animated') ){
                this.newLeft = Math.max( parseInt( this.view.css('left'), 10 ) - this.step, this.borderLeft);
                this.view.animate({left: this.newLeft}, this.timing);
            }

            return (this.newLeft == this.borderLeft);
        };

        this.Prev = function(){
            if( !this.view.is(':animated') ){
                this.newLeft = Math.min( parseInt( this.view.css('left'), 10 ) + this.step, 0 );
                this.view.animate({left: this.newLeft}, this.timing);
            }

            return (this.newLeft == 0);
        };

    };

    
function ImageLoader( _cfg ){
	_cfg.loadedCount = 0;

	function onLoad(){
		_cfg.loadedCount++;

		if( _cfg.loadedCount == _cfg.list.length )
			if( _cfg.hasOwnProperty('complete') )
				_cfg.complete();
	};

	for(var i=0; i< _cfg.list.length; i++ ){
		newImg = new Image();
		newImg.onload = newImg.onerror = newImg.onabort = onLoad;
		newImg.src = _cfg.list[i];
	};
};




$(function(){

	$('a[href=#]').attr('href', 'javascript:void(0);');
	
	$('.show_more_menu_text').click(function(){
		$(this).hide();
		$('.menu_text').hide();
		$('.more_menu_text').show();
		$('.hide_more_menu_text').show();
	});
	
	$('.hide_more_menu_text').click(function(){
		$(this).hide();
		$('.more_menu_text').hide();
		$('.menu_text').show();
		$('.show_more_menu_text').show();
	});

    function AttachPhotoLenta2(){

       $('div.photoLenta2').each( function(i){
           var $pl = $(this);
           var $lenta = $pl.find('div.lenta').css({position:'relative', left:0});
           var $blocks = $lenta.find('a');
           var lng=0;
           var step = parseInt( $pl.find('div.lentaWrap').width(), 10 );

           var srcList = [];
           var isLent;


           $blocks.attr('rel', 'fbg'+i).fancybox();

           $blocks.find('img').each( function(){ srcList.push( this.getAttribute('src') ) });
           ImageLoader({list: srcList, complete: function(){

              $blocks.each(function(){lng+=$(this).width();});

              isLent = new CLentMini({
                    view : $lenta
                  , step : step
                  , borderLeft : (lng-step)*-1
              });

              // next
              $pl.find('div.next').click( function(){
                  var stt = isLent.Next();

                  $pl.find('.prev').removeClass('hide');
                  $(this).toggleClass( 'hide', stt );
              });

              // prev
              $pl.find('div.prev').click( function(){
                  var stt = isLent.Prev()

                  $pl.find('.next').removeClass('hide');
                  $(this).toggleClass( 'hide', stt );
              });
           } });
       });


       $('div.photoLenta2 div.lenta img').mouseenter( function(){
            var $img=$(this);


            $('img.popupImagePreview').each( function(){ var $i=$(this);$i.stop().animate({opacity:0}, 333, function(){$i.detach();});});

            var $preview = $('<img class="popupImagePreview">');

            var w = parseInt($img.width(),10);
            var h = parseInt($img.height(),10);
            var k = 1.3;


            $preview.attr('src', this.src ).css({position: 'absolute', zIndex:100, width:w, height:h, opacity:1}).css( $img.offset() );

            $preview.click( function(){ $img.click(); } );
            $preview.mouseleave( function(){$preview.stop().animate({opacity:0}, 333, function(){ $preview.detach();});})

            $('body').append( $preview );

            $preview.animate({width: w*k
            , height: h*k
            , left: '-='+w*(k-1)/2+'px'
            , top: '-='+h*(k-1)/2+'px'
            }, 333);
        });

    };

    var $glr2List = $('img.galleryPlaceholder');

    if( $glr2List.length > 0 )
        $glr2List.each(function(){
           var gallery = $(this);
           $.post('/gallery/ajax_render',
              {
                 id: $(this).attr('rel'),
                 style: $(this).attr('alt')
              },
              function(_data){
                 gallery.hide();
                 gallery.after(_data);

                 AttachPhotoLenta2();
                 //alert(_data);
              }
           );
        });

    else
        AttachPhotoLenta2();


    // promoblock
    (function(){

        var $block = $('.promoPhotoBlock');

        var $next   = $block.find('div.next');
        var $lenta  = $block.find('div.photos div.lenta');
        var $photos = $lenta.find('img');
        var count   = $photos.length;

        var $text   = $('div.photoTxt div.block',$block);
        var move    = 0;

        if(count){

            function makeMove(){

                move = (move == (count-1) ? 0 : move+1);

                var $curPhoto = $photos.eq(move);

                $lenta.animate({'margin-left':'-'+290*move},400);

                $text.fadeOut();

                setTimeout(function(){
                   $text.text($curPhoto.attr('alt')).fadeIn();
                },500);
            }

            $next.click(function(e){
                e.preventDefault();

                makeMove();
            });

        }

	})();


   // galleria ... ?!$@#%^
	(function(){

		// Load theme
	    Galleria.loadTheme('/static/js/themes/classic/galleria.classic.js');

	    // run galleria and add some options
	    $('.galleria').galleria({
	        image_crop: true, // crop all images to fit
	        thumb_crop: true, // crop all thumbnails to fit
	        transition: 'fade', // crossfade photos
	        transition_speed: 700, // slow down the crossfade
	        data_config: function(img) {
	            // will extract and return image captions from the source:
	            return  {
	                title: $(img).parent().next('strong').html(),
	                description: $(img).parent().next('strong').next().html()
	            };
	        },
	        extend: function() {
	            this.bind(Galleria.IMAGE, function(e) {
	                // bind a click event to the active image
	                $(e.imageTarget).css('cursor','pointer').click(this.proxy(function() {
	                    // open the image in a lightbox
	                    this.openLightbox();
	                }));
	            });
	        }
	    });

	})();

	(function(){

        var $hiders = $('._autohide');

        $hiders.each(function(i){

            var $hider = $hiders.eq(i);
            var $input = $('#'+$hider.attr('for'));

            $hider.click(function(){
                $hider.hide();
                $input.focus();
            });

            $input.focusin(function(){
                $hider.hide();
            });

            $input.focusout(function(){
                if(!$input.val()){
                    $hider.show();
                }
            });

        });

    })();

     (function(){
        // Показывает и скрывает флеш-баннер
       $(".flashBlock .link").click(function() {
       		//debugger;
       		var $d = $(this);
            var now = new Date();
		    var stt = $('.flashBlock .flash').is(':visible');
		    
		    
		    $('.flashBlock .flash').slideToggle(stt);
		    $d.toggleClass('show', !stt).toggleClass('hide', stt).text(stt?'Показать':'Скрыть');
		    
		    
            if (stt) {
                setCookie('noflash', stt, now.setDate(now.getDate() + 14 ), '/');
            } else {
                setCookie('noflash', stt, now.setDate(now.getDate() - 1 ), '/');
            }
            swapMessage($(this));
        });

        if (getCookie('noflash') == 'true') {
            $('.flashBlock .flash').hide();
            $('.flashBlock .link').removeClass('show').addClass('hide').text('Показать');
            swapMessage($(".flashBlock .link"));
        }
    })();

    (function(){
        // FAQ - скрывает и показывает факи
        $('.allQuestion').click(function() {
            var allQuestion = $(this);
            $('div.question').each(function(i) {
                if (!$(allQuestion).attr('hideAll')) {
                    $(this).addClass('cur');
                } else {
                    $(this).removeClass('cur');
                }
            });
            if (!$(this).attr('hideAll')) {
                $(this).attr('hideAll', '1');
            } else {
                $(this).removeAttr('hideAll');
            }
            swapMessage(this);
        });

        $('.question > .name').click(function(){
            if ($(this).parent().hasClass('cur')) {
                $(this).parent().removeClass('cur');
            } else {
                $(this).parent().addClass('cur');
            }
        });
    })();

    // Лента для популярных моделей
    (function() {

        var products = $('.infoBlock, .block1');

        if (products.length) {

        products.each(function() {

            var self = this,
            $this = $(this),
            $lenta = $this.find('.lenta'),
            $blocks = $lenta.find('> *'),
            $prev = $this.find('.prev'),
            $next = $this.find('.next'),
            $document = $(document),
            pos = 0,
            w = -236,
            lim = $blocks.length - 3,
            scrolling = false,
            i = 0;


            this.stopScrolling = function(e) {
                scrolling = false;
                $document.unbind('mousemove', self.stopScrolling);
                $document.unbind('mouseup', self.stopScrolling);
            }

            $next.hover(function() {

                scrolling = true;
                self.nextFunc.apply(this);

            }, function(e) {

                $document
                .one('mousemove', self.stopScrolling)
                .one('mouseup', self.stopScrolling);

                e.stopPropagation();
                e.cancelBubble = true;

            });


            $prev.hover(function() {

                scrolling = true;
                self.prevFunc.apply(this);

            }, function(e) {

                $document
                .one('mousemove', self.stopScrolling)
                .one('mouseup', self.stopScrolling);

                e.stopPropagation();
                e.cancelBubble = true;

            });

            this.prevFunc = function() {
                if(pos > 0){
                    pos--;
                    $lenta.stop().animate({left:pos*w}, 500, function(){
                    if(scrolling){
                    setTimeout(self.prevFunc, 150);
                    }
                    });
                    if (pos <= 0) {
                    $prev.addClass('hide');
                    }
                    $next.removeClass('hide');
                }
            }

            this.nextFunc = function() {
                if(pos < lim){
                    pos++;
                    $lenta.stop().animate({left:pos*w}, 500, function(){
                        if(scrolling){
                            setTimeout(self.nextFunc, 150);
                        }
                    });
                    if (pos >= lim) {
                       $next.addClass('hide');
                    }
                    $prev.removeClass('hide');
                }
            }

        });

        }

    })();

    // Форма обратной связи
    (function(){
		function feedback()
		{
			$('#darkness').toggle();
			$('#feedbackForm').toggle();
		}
		
		$('.feedbackDoor,.feedback, #closeForm, #darkness').click(function(){
			feedback();
		});
		
		if ((location.hash =='#feedback')) {
			feedback();
		}
    })();

	// Страница О компании - история компании
    (function(){
        $('.historyBlock li').click(function(){
            $('.historyBlock li.cur').removeClass('cur');
            $(this).addClass('cur');
            $('.history .block:visible').hide();
            $('#h' + $('div', this).html()).show();
        });
    })();
    
	$('.historyBlock>ul>li:first').click();


    // Горизонтальная лента для видео
    var player = document.getElementById('flash');
	(function(){
		var $SliderPreview  = $('.videoBlockLenta');
		var $Up             = $SliderPreview.find('.up');
		var $Down           = $SliderPreview.find('.down');
		var $Lenta          = $SliderPreview.find('.lenta');
		var $Items          = $Lenta.find('> *');
		var $curPhoto       = $Lenta.find('.cur');
		var length          = $Items.length;
       var ItemHeight      = 128; // Высота элемента + бордюр

		if (length) {

			var offset  = parseInt($Lenta.css('top').replace('px',''));
			var top     = offset/ItemHeight;
			var cur     = Math.abs(top);

			$Lenta.css({"height":(length*ItemHeight+3)});

			$Up.bind('mousedown', function(e){
				if (cur > 0) {
					cur--;
					$Lenta.animate({
						"top": -ItemHeight * cur
					}, 100);
					upBtns();
				}

			});

			$Down.bind('click', function(e){
				if (length-cur-1>=5) {
					cur++;
					$Lenta.animate({
						"top": -ItemHeight * cur
					}, 100);
					upBtns();
				}
			});

			function upBtns(){
				if (cur == 0) {
					$Up.fadeOut(300);
				}else if (cur == 1){
					$Up.fadeIn(300);
				}
				if (length-cur-1 < 5) {
					$Down.fadeOut(300);
				}else{
					$Down.fadeIn(300);
				}
			}
			upBtns();
		}

        $('.play').click(function() {
            var $divPlay = $(this);

            var $h2 = $('div.block1 h2');
            var $descr = $('div.videoBlock div.descr');


            $h2.text( $divPlay.prev('img').attr('alt') );
            $descr.text( $divPlay.closest('div.block').find('div.descr').text() );

            player.sendEvent('LOAD', {file: $divPlay.attr('path')
                                     , image: $divPlay.closest('div.block').find('img').attr('src').replace( /\/thumbs\//, '/full/' )
                                     } );
            player.sendEvent('PLAY');
        });
	})();


   // Galery
   (function(){

       var $wrap = $('div.productMain div.generalWrap:gt(0) > div.block');

       var $blocks;
       var $block;
       var $imgBlock;

       var isLent;


       // medium preview
       $('div.photoBlock.ext1 div.block').click( function(ev){
           var $div = $(this);
           var $fImg = $div.closest('div.photoBlock').find('div.f img');

           $div.parent().find('.cur').removeClass('cur');
           $div.addClass('cur');

           $fImg.attr('src', $div.find('img').attr('medium') );

           $fImg.data('medium', $div.find('img').attr('medium'));
           $fImg.data('big', $div.find('img').attr('big'));

           // Load
           //(new Image()).src = $fImg.data('big');
        });

        $('div.photoBlock.ext1 div.f img').click( function(){
           var $img = $(this);

            window.open( $img.data('big') );
        });
/*
        // big preview
        $('div.productMain div.generalWrap div.block div.photoBlock div.f img').fancybox({
              autoScale : true
            , autoDimensions : true
            , onStart: function(_arr, _index, _opts){
                var $img = _opts.orig;

                $img.attr('src', $img.data('big') );
              }
            , onComplete: function(){
                //$('#fancybox-wrap').live( 'click', function(){ alert(1); } );
                //setTimeout( function(){ $('#fancybox-inner img').click(); },1000);
            }
            , onClosed: function(_arr, _index, _opts){
                var $img = _opts.orig;

                $img.attr('src', $img.data('medium') );
              }
        });
*/

        for(i=0;i<$wrap.length;i++){

           $block = $wrap.eq(i).find('div.bestModels');
           $blocks = $block.find('div.block');

           var isLent = new CLent({
               lent     : $block.find('div.lenta'),
               next     : $block.find('div.next'),
               prev     : $block.find('div.prev'),
               visibleBlocks : 5,
               blockQty : $blocks.length,
               step     : 79*4//$blocks.eq(0).outerWidth()
            });

            isLent.BindControl();


            $imgBlock = $wrap.eq(i).find('div.photoBlock');
            $blocks = $imgBlock.find('div.block');


            isLent.BindControl();

            $blocks.filter(':first').click();
       }

   })();

   // Video gallery
   (function(){ // videoBlockLenta

       var $blocks = $('div.videoBlockLenta div.block');

       var isLent = new CLent({
              lent     : $('div.videoBlockLenta div.lenta')
            , next     : $('div.videoBlockLenta div.down')
            , prev     : $('div.videoBlockLenta div.up')
            , visibleBlocks : 5
            , blockQty : $blocks.length
            , step     : $blocks.eq(0).outerHeight()
            , direction: 'top'
        });

        isLent.BindControl();
   })();

   (function(){
		$('div.photosLenta div.next, div.photosLenta3 div.next, div.photosLentaBig div.next').live('click', function(){ //debugger;
		var $lentBlock = $(this).closest('div.photosLenta, div.photosLenta3, div.photosLentaBig');
			var $lent = $lentBlock.find('div.lenta');
          
              var $el = $lent.children(':first');

              if( $el.is(':animated') )
                return;

              $el.find('div').slideUp(222);
              $el.animate({width:0}, 500, function(){
                  $lent.append( $lent.children(':first').removeAttr('style') );
                  $el.find('div').slideDown(0);
              });
          });
   
   })();
   

    // snake lent
    (function(){
        var $main = $('div.photoLentaBlock.snake');

        var $first  = $('div.lenta', $main);
        var $second = $('div.lenta', $main).clone();
        var $next = $('div.next', $main);
        var $prev = $('div.prev', $main);

        var lent1;
        var lent2;

        var size = 5;
        var $blocks;
        var lborder;
        var lstep;


        $first.find('div.block:gt(' + ($first.find('div.block').length-size-1) + ')').detach();
        $second.find('div.block:lt(' + size + ')').detach();

        $('div.lenta').parent().append( $second );

        $main.find('div.lenta').css({position:'relative', left:0, width: 10000});

        $blocks = $first.find('div.block');

        lborder = ($blocks.length-5)*176*-1;
        lstep = 176*5;

        if(lborder>0)
            lborder=0;

        lent1 = new CLentMini({view : $first, step : lstep, borderLeft : lborder});
        lent2 = new CLentMini({view : $second, step : lstep, borderLeft : lborder});

        $next.live('click',  function(){ lent1.Next(); lent2.Next(); } );
        $prev.live('click',  function(){ lent1.Prev(); lent2.Prev(); } );
    })();

    $('.jobTitle').bind('click',function(){

        if ($(this).siblings('div.jobText').is(':hidden')) {
            $('div.jobText').hide('fast');
            $('span.jobTitle').removeClass('cur');            
        }
        $(this).siblings('div.jobText').toggle('fast');
        $(this).toggleClass('cur');
	});

    $('#closeResult').live('click',function(){
        $('#feedbackResult').hide();
        $('#darknessAnswer').hide();        
		
	});
    
    $('#designer_size').live('click',function(){

        $('#designer_size_block').show();
        $('#designer_size_block').siblings().hide();
        $(this).siblings().removeClass('cur');
        $(this).addClass('cur');
        
	});
        $('#designer_price').live('click',function(){

        $('#designer_price_block').show();
        $('#designer_price_block').siblings().hide();
        $(this).siblings().removeClass('cur');
        $(this).addClass('cur');
        
	});
        $('#designer_style').live('click',function(){

        $('#designer_style_block').show();
        $('#designer_style_block').siblings().hide();
        $(this).siblings().removeClass('cur');
        $(this).addClass('cur');
        
	});
        $('a#gallery2').live('click',function(){
          var link=$(this).children('img').attr('alt');
        	//$('#product_image').parent().attr('href', link.replace('340x236' ,'full'));
        	$('#product_image').attr('src', link);
        
	});
   
   
       (function(){

        var $photos = $("a[rel=gallery]");
        var $photos2 = $("a[rel=gallery_2]");
/*
        $photos.hover(
            function(){
                $(this).siblings('div.text').slideDown(100);
            },

            function(){
                $(this).siblings('div.text').slideUp(100);
            }
        );
*/
        $("a[rel=gallery] ~ div.text").show();

        $photos.fancybox({
            'transitionIn'		: 'none',
            'transitionOut'	: 'none',
            'titlePosition' 	: 'over',
            'titleFormat'		: function(title, currentArray, currentIndex, currentOpts) {
                return '<span id="fancybox-title-over">'+title+'</span>';
            }
        });
        $photos2.fancybox({
            'transitionIn'		: 'none',
            'transitionOut'	: 'none',
            'titlePosition' 	: 'over',
            'titleFormat'		: function(title, currentArray, currentIndex, currentOpts) {
                return '<span id="fancybox-title-over">'+title+'</span>';
            }
        });

    })();


    // Lenta 
    (function(){
        var $main = $('div.bestModels');

        var $lent = $main.find('div.lenta')
        var $next = $main.find('div.next');
        var $prev = $main.find('div.prev');
        var $blocks;

        var lent;

        var size = 6;
        var blockSize = 80 + 40;
        var lborder;
        var lstep;


        $blocks = $lent.find('div.block');

        lborder = ($blocks.length-size)* blockSize *-1;
        lstep = blockSize * size;


        if(lborder>0){
            lborder=0;
            $next.hide();
            $prev.hide();
        }

        lent = new CLentMini({ view : $lent, step : lstep, borderLeft : lborder });


        $next.click( function(){
            $prev.removeClass('hide');

            $next.toggleClass( 'hide', lent.Next() );
        });

        $prev.click( function(){
            $next.removeClass('hide');

            $prev.toggleClass( 'hide', lent.Prev() );
        });

    })();

});



function swapMessage(element) {
    var swap = $('span', element).attr('swap');
    var text = $('span', element).text();
    $('span', element).attr('swap', text).text(swap);
}

function setCookie (name, value, expires, path, domain, secure) {
      document.cookie = name + "=" + escape(value) +
        ((expires) ? "; expires=" + expires : "") +
        ((path) ? "; path=" + path : "") +
        ((domain) ? "; domain=" + domain : "") +
        ((secure) ? "; secure" : "");
}

function getCookie(name) {
	var cookie = " " + document.cookie;
	var search = " " + name + "=";
	var setStr = null;
	var offset = 0;
	var end = 0;
	if (cookie.length > 0) {
		offset = cookie.indexOf(search);
		if (offset != -1) {
			offset += search.length;
			end = cookie.indexOf(";", offset)
			if (end == -1) {
				end = cookie.length;
			}
			setStr = unescape(cookie.substring(offset, end));
		}
	}
	return(setStr);
}
