/**
 * jQuery.fn.sortElements
 * --------------
 * @param Function comparator:
 *   Exactly the same behaviour as [1,2,3].sort(comparator)
 *   
 * @param Function getSortable
 *   A function that should return the element that is
 *   to be sorted. The comparator will run on the
 *   current collection, but you may want the actual
 *   resulting sort to occur on a parent or another
 *   associated element.
 *   
 *   E.g. $('td').sortElements(comparator, function(){
 *      return this.parentNode; 
 *   })
 *   
 *   The <td>'s parent (<tr>) will be sorted instead
 *   of the <td> itself.
 */
jQuery.fn.sortElements = (function(){
 
    var sort = [].sort;
 
    return function(comparator, getSortable) {
 
        getSortable = getSortable || function(){return this;};
 
        var placements = this.map(function(){
 
            var sortElement = getSortable.call(this),
                parentNode = sortElement.parentNode;
                // Since the element itself will change position, we have
                // to have some way of storing its original position in
                // the DOM. The easiest way is to have a 'flag' node:
            var    nextSibling = parentNode.insertBefore(
                    document.createTextNode(''),
                    sortElement.nextSibling
                );
 
            return function() {
 
                if (parentNode === this) {
                    throw new Error(
                        "You can't sort elements if any one is a descendant of another."
                    );
                }
 
                // Insert before flag:
                parentNode.insertBefore(this, nextSibling);
                // Remove flag:
                parentNode.removeChild(nextSibling);
 
            };
 
        });
 
        return sort.call(this, comparator).each(function(i){
            placements[i].call(getSortable.call(this));
        });
 
    };
 
})();

$(document).ready(function(){
    
    /*
     * Эффекты оформления
     */
    var animate = function(){
        $('.clouds').animate({
            "background-position":"-1523px"
        },120000,function(){
            $('.clouds').css("background-position","0px");
            animate();
        });
    };

    $(document).mousemove(function(e){
        x = e.clientX/60+50;
        y = e.clientY/60+50;
        $('.flyer').css('background-position',y+'px '+x+'px');
    });

    animate();





    /*
     * Дополнение цитат линиями сверху и снизу
     */
    $('blockquote').before('<div class="blockquote"></div>');
    $('blockquote').after('<div class="blockquoteB"></div>');




    /*
     * Выставление индекса для вложенного меню
     * и позиционирование меню второго уровня
     */
    var menuTotalWidth = 0;
    var navStartPosition = $('header nav').position().left+275;
    $('header li').each(function(){
        menuTotalWidth += $(this).width();
    });
    var navTotalPosition = navStartPosition+menuTotalWidth+100;

    $('.submenu').each(function(){
        $(this).parent().addClass('subMShow');

        tempLeft = ($(this).parent().position().left-($(this).width()/2)+($(this).parent().width()/2)+20);

        if (tempLeft<navStartPosition){
            tempLeft = navStartPosition;
        }
        if ((tempLeft+$(this).width())>navTotalPosition){
            tempLeft = navTotalPosition - $(this).width();
        }

        $(this).css('left',tempLeft+'px');
    });

    $('.active.subMShow .submenu').fadeIn('slow');








    /*
     * Отображение вложенного меню
     */
    $('.subMShow').hover(function(){
        $('header nav ul li.active .submenu').hide();
        $(this).children('.submenu').show();
    },function(){
        $(this).children('.submenu').hide();
        $('header nav ul li.active .submenu').show();
    });






    /*
     * Поиск по элементам
     */
    $('#find').keyup(function(){
        $('.title').each(function(){
            if ($(this).text().toLowerCase().indexOf($('#find').val().toLowerCase())==-1){
                $(this).parent().parent().hide();
            }else{
                $(this).parent().parent().show();
            }
        });
    });





    /*
     * Сортировки
     */
    $('.sortUp').live('click',function(){
        $('.product').sortElements(function(a, b){
            return $(a).attr('data-price') > $(b).attr('data-price') ? 1 : -1;
        });
        $(this).addClass('sortDown')
               .removeClass('sortUp')
               .text('по убыванию');
    });
    $('.sortDown').live('click',function(){
        $('.product').sortElements(function(a, b){
            return $(a).attr('data-price') < $(b).attr('data-price') ? 1 : -1;
        });
        $(this).addClass('sortUp')
               .removeClass('sortDown')
               .text('по возрастанию');
    });




	/*
	 * Отправка сообщений
	 */
	$('#sendMSG').click(function(){
		var save = true;
		if($('#fio').val()=='' || $('#fio').val()=='Это поле обязательно для заполнения!'){
			save = false;
			$('#fio').val('Это поле обязательно для заполнения!').addClass('alert');
			
		}
		if($('#contact').val()=='' || $('#contact').val()=='Это поле обязательно для заполнения!'){
			save = false;
			$('#contact').val('Это поле обязательно для заполнения!').addClass('alert');
		}
		if($('#msg').val()=='' || $('#msg').val()=='Это поле обязательно для заполнения!'){
			save = false;
			$('#msg').val('Это поле обязательно для заполнения!').addClass('alert');
		}
		if (save){
            jQuery.post(
                '/api.post/structure_site.send',
                {
                    fio:     $('#fio').val(),
                    contact: $('#contact').val(),
                    msg:     $('#msg').val()
                },
                function (data){
                    if (data.status){
                        $('.contactForm').html('<p>Сообщение успешно отправлено!</p>');
                    }else{
                        $('.contactForm').html('<p>При отправке сообщения произошла ошибка. Повторите попытку позже!</p>');
                    }
                },
                'json'
            );
        }
	});
	
	$('.alert').live('focus',function(){
		$(this).val('');
		$(this).css('color','#444');
	}).live('blur',function(){
		if ($(this).val()=='' || $(this).val()=='Это поле обязательно для заполнения!'){
			$(this).val('Это поле обязательно для заполнения!');
			$(this).css('color','red');
		}else{
			$(this).removeClass('alert');
		}
	});
});
