$(document).ready(function(){
	
	$("#modal1").fancybox({'height': '425','autoDimensions' :false,'centerOnScroll' :true});
	$("#modal2").fancybox({'transitionIn'	: 'none','transitionOut'	: 'none'});
	$("#modal3").fancybox({'transitionIn'	: 'none','transitionOut'	: 'none'});
	$(".various").fancybox({'transitionIn'	: 'none','transitionOut'	: 'none'});
	$("#ajax-contact-form").submit(function () {
        var str = $(this).serialize(); 
        $.ajax({type: "POST",url: "/contact.php",data: str,success: function (msg){
                $("#note").ajaxComplete(function (event, request, settings){
                    if (msg == 'OK') {
                        result = '<div class="notification_ok">Ваше сообщение отправлено. Спасибо!</div>';
                        $("#fields").hide();
                    }else{result = msg;}
                    $(this).html(result);
                });
        }});
        return false;
    });
    $("#call").submit(function () {
        var str = $(this).serialize(); 
        $.ajax({type: "POST",url: "/call.php",data: str,success: function (msg){
                $("#note_call").ajaxComplete(function (event, request, settings){
                    if (msg == 'OK') {result = '<div class="notification_ok">Ваша заявка успешно отправлена. В ближайшее время мы Вам перезвоним</div>';}
                    else{result = msg;}
                    $(this).html(result);
                });
        }});
        return false;
    });
    $("#order_call").submit(function () {
        var str = $(this).serialize(); 
        $.ajax({type: "POST",url: "/call.php",data: str,success: function (msg){
                $("#note2").ajaxComplete(function (event, request, settings){
                    if (msg == 'OK') {result = '<div class="notification_ok">Ваша заявка успешно отправлена. В ближайшее время мы Вам перезвоним</div>';}
                    else{result = msg;}
                    $(this).html(result);
                });
        }});
        return false;
    });
	
	
	$("#main-nav li a.main-link").hover(function(){$("#main-nav li a.close").fadeIn();$("#main-nav li a.main-link").removeClass("active");$(this).addClass("active");$("#sub-link-bar").animate({height:"40px"});$(".sub-links").hide();$(this).siblings(".sub-links").show()});$("#main-nav li a.close").click(function(){$("#main-nav li a.main-link").removeClass("active");$(".sub-links").fadeOut();$("#sub-link-bar").animate({height:"10px"});$("#main-nav li a.close").fadeOut()})
	
	$(function(){$("ul.tabs").tabs("div.pans > div",{effect:"fade"})});$(".scrollable").scrollable();$(document).ready(function(){$("a[rel=example_group]").fancybox({transitionIn:"none",transitionOut:"none",titlePosition:"over",titleFormat:function(a,b,c){return'<span id="fancybox-title-over">Image '+(c+1)+" / "+b.length+(a.length?" &nbsp; "+a:"")+"</span>"}})});
			
			//When you click on a link with class of poplight and the href starts with a # 
$('a.poplight[href^=#]').click(function() {
    var popID = $(this).attr('rel'); //Get Popup Name
    var popURL = $(this).attr('href'); //Get Popup href to define size
 
    //Pull Query & Variables from href URL
    var query= popURL.split('?');
    var dim= query[1].split('&');
    var popWidth = dim[0].split('=')[1]; //Gets the first query string value
 
    //Fade in the Popup and add close button
    $('#' + popID).fadeIn().css({ 'width': Number( popWidth ) }).prepend('<a href="#" class="close"><img src="templates/default/img/close_pop.png" class="btn_close" title="Close Window" alt="Close" /></a>');
 
    //Define margin for center alignment (vertical   horizontal) - we add 80px to the height/width to accomodate for the padding  and border width defined in the css
    var popMargTop = ($('#' + popID).height() + 80) / 2;
    var popMargLeft = ($('#' + popID).width() + 80) / 2;
 
    //Apply Margin to Popup
    $('#' + popID).css({
        'margin-top' : -popMargTop,
        'margin-left' : -popMargLeft
    });
    //Fade in Background
    $('body').append('<div id="fade"></div>'); //Add the fade layer to bottom of the body tag.
    $('#fade').css({'filter' : 'alpha(opacity=80)'}).fadeIn(); //Fade in the fade layer - .css({'filter' : 'alpha(opacity=80)'}) is used to fix the IE Bug on fading transparencies 
 
    return false;
});
 
	//Close Popups and Fade Layer
	$('a.close, #fade').live('click', function() {
	    $('#fade , .popup_block').fadeOut(function() {$('#fade, a.close').remove();});
	    return false;
	});
	
	$('#content_pic_carousel').jcarousel();
	$("a[rel=gallery]").fancybox();
});

$(function(){$("#address").tabs("#address div",{tabs:"a",effect:"horizontal"})});





jQuery(document).ready(function() {
    // форма обратной связи
     $("#ajax-contact-form").submit(function (){
        var str = $(this).serialize(); // сериализуем данные для POST-запроса
        $.ajax({type: "POST",url: "contact.php",data: str,success: function (msg){
                $("#note").ajaxComplete(function (event, request, settings){
                	if (msg == 'OK'){
                		result = '<div class="notification_ok">Ваше сообщение отправлено. Спасибо!</div>';
                        $("#fields").hide();
                    }else{result = msg;}
                    $(this).html(result);
                });
        }});
        return false;
    });
});

//$(document).ready(function(){$("a[rel=example_group]").fancybox({transitionIn:"none",transitionOut:"none",titlePosition:"over",titleFormat:function(a,b,c){return'<span id="fancybox-title-over">Image '+(c+1)+" / "+b.length+(a.length?" &nbsp; "+a:"")+"</span>"}})});



          // Плагин сортировки
          (function($) {
          	$.fn.sorted = function(customOptions) {
          		var options = {
          			reversed: false,
          			by: function(a) { return a.text(); }
          		};
          		$.extend(options, customOptions);
          		$data = $(this);
          		arr = $data.get();
          		arr.sort(function(a, b) {
          		   	var valA = options.by($(a));
          		   	var valB = options.by($(b));
          			if (options.reversed) {
          				return (valA < valB) ? 1 : (valA > valB) ? -1 : 0;				
          			} else {		
          				return (valA < valB) ? -1 : (valA > valB) ? 1 : 0;	
          			}
          		});
          		return $(arr);
          	};
          })(jQuery);
      
          // Выполняется после загруки DOM
          $(function() {
          
            // привязыываем радиокнопки в форме
          	var $filterType = $('#filter input[name="type"]');
          	var $filterSort = $('#filter input[name="sort"]');
        	
          	// получаем первый набор
          	var $applications = $('#countryes');
        	
          	// клонируем первый набор, чтобы получить второй набор
          	var $data = $applications.clone();

            // вызываем Quicksand для каждого изменения в форме
          	$filterType.add($filterSort).change(function(e) {
          		if ($($filterType+':checked').val() == 'all') {
          			var $filteredData = $data.find('li');
          		} else {
          			var $filteredData = $data.find('li[data-type=' + $($filterType+":checked").val() + ']');
          		}
            
              // если нужна сортировка по размеру
          		if ($('#filter input[name="sort"]:checked').val() == "size") {
          			var $sortedData = $filteredData.sorted({
          				by: function(v) {
          					return parseFloat($(v).find('span[data-type=size]').text());
          				}
          			});
          		} else {
          		// если нужна сортировка по имени
          			var $sortedData = $filteredData.sorted({
          				by: function(v) {
          					return $(v).find('strong').text().toLowerCase();
          				}
          			});
          		}   
        		
          		// вызываем плагин 
          	  $applications.quicksand($sortedData, {
          	    duration: 1000,
          	    easing: 'easeInOutQuad',
          	    adjustHeight:	false,
          	   // useScaling: false
          	  });

          	});
          
          });

