function staticLoadScriptUrl(url)
{
   document.write('<script src="', url, '" type="text/javascript"><\/script>');
}

//staticLoadScriptUrl(" https://cdnjs.cloudflare.com/ajax/libs/jquery.maskedinput/1.4.1/jquery.maskedinput.min.js");

(function($) {
    $.fn.equalHeights = function() {
        var maxHeight = 0,
            $this = $(this);
        $this.each(function() {
            var height = $(this).innerHeight();
            if (height > maxHeight) {
                maxHeight = height;
            }
        });
        return $this.css('height', maxHeight);
    };
})(jQuery);

$(function() {
	$(".input_search").autocomplete({
		serviceUrl:'/ajax/search_products.php',
		minChars:1,
		noCache: false,
        open: function() { $('#div .ui-menu').width(300) },
		onSelect:
			function(value, data){
				 $(".input_search").closest('form').submit();
			},
		fnFormatResult:
			function(value, data, currentValue){
				var reEscape = new RegExp('(\\' + ['/', '.', '*', '+', '?', '|', '(', ')', '[', ']', '{', '}', '\\'].join('|\\') + ')', 'g');
				var pattern = '(' + currentValue.replace(reEscape, '\\$1') + ')';
  				return (data.image?"<img align=absmiddle src='"+data.image+"'> ":'') + value.replace(new RegExp(pattern, 'gi'), '<strong>$1<\/strong>');
			}
	});
	
	
	$('#sort-services').change(function(){
		
		var val = $('#sort-services').find('option:selected').val();
		var url = document.location.pathname.replace(/\/filter-[^/]+\//, '/');
		url = url.replace(/\/page-[0-9]+\//, '/');
		if(val != 0) url += 'filter-' + val + '/';
		//console.log(url)
		document.location.href = url;
	});
	
});

$(window).load(function(){
	$('[data-validation="phone"]').mask('+7(999) 999 - 99 - 99');
});

$(document).ready(function(e) {
	
	
    
      $('.pdf-download-content a').each(function() {
        
        //console.log( 'test' );
        
        if ($(this).attr('href')) {
            if ($(this).attr('href').indexOf('.pdf') > 0) { 
                var thisText = $(this).html(),
                    parentText = $(this).parent().html(),
                    addText = parentText.replace(thisText, ''),                                                                     
                    insert = '<div class="pdf-download"><span><a target="_blank" href="' + $(this).attr('href') + '">' + $(this).html() + '</a><p>' + addText + '</p></span></div>';
                $(this).parent().html(insert);
            } 
        }       
      }); 
        
      $('.pdf-download').each(function() {
      	var $el = $(this);
        var href = $el.find('a').attr('href');
        $el.css('cursor', 'pointer');
        
        $el.wrap('<a href="'+href+'" target="_blank" />');

        //$el.click(function() {
            //window.location.href = href;
        //});
      });     
        
    
    $('#top-shopcart').fadeIn();
    
    //$('[data-validation="phone"]').mask('+7(999) 999 - 99 - 99');
	
    $(window).scroll(function () {if ($(this).scrollTop() > 0) {$('#scroller').fadeIn();} else {$('#scroller').fadeOut();}});
    $('#scroller').click(function () {$('body,html').animate({scrollTop: 0}, 400); return false;});
    $('.copyright .ch').after(" " + (new Date).getFullYear());
    var amount = parseInt($('#b_count3').text());
    if(amount == 0)
    {  
        $('#top-shopcart').removeClass('notempty');
    }
    else
    {
        $('#top-shopcart').addClass('notempty');
    }
    $('.content table:not("form table")').removeAttr('style').removeAttr('class').removeAttr('border').removeAttr('cellpadding').removeAttr('cellspacing').removeAttr('align').addClass('table table-striped table-bordered');
    $('.content table td:not("form table td")').removeAttr('style').removeAttr('class').removeAttr('align').removeAttr('valign').addClass('td');
	$('.content table td img:not("form table td img")').each(function(){
		var _img = $(this);
			if(_img.hasClass('zooming')){
				_img.removeAttr('style').removeAttr('class').addClass('img-thumbnail zooming');
			}else{
				_img.removeAttr('style').removeAttr('class').addClass('img-thumbnail');
			}
	});	
    $('.content table td a:not("form table td a")').removeAttr('style').removeAttr('class').addClass('w');
    $('.content form.variants select').addClass('form-control');
    
	$('img.zooming').each(function(){
		var href = $(this).attr('src');
        var title = $(this).attr('alt');
        var src = $(this).attr('data-src');
        if(typeof src != 'undefined' && src) href = src;
		$(this).wrap('<a href="'+href+'" title="'+title+'" class="_zooming" rel="group777" />');
		//$(this).parent().wrap('<div class="col-sm-6 mb"/>'); 
	});
    
	$('a._zooming').fancybox({
        helpers:  {
            overlay: {
                locked: false
            },
            title: {
                //type: 'inside'
            }                        
        }
    });
               
    function vk() 
    {
        /*setTimeout(function(){ 
            $('#vk_groups').find('iframe').remove();
            VK.Widgets.Group("vk_groups", {mode: 0, width: $('#vk_groups').parent().width()-2, height: 256, color1: 'FFFFFF', color2: '2B587A', color3: '2e3338'}, 60705350); 
            }, 300); */   
    }
    function heightElems()
    {
        if ($('body').hasClass('desktop')) {
            $('.home-output .product-image').height('auto').equalHeights();
            $('.home-output .product-name').height('auto').equalHeights(); 
            $('.brands .brand .brand-image').height('auto').equalHeights();
            $('.brands .brand .brand-name').height('auto').equalHeights();  
            $('.categories .category .category-image').height('auto').equalHeights();
            $('.categories .category .category-name').height('auto').equalHeights();
            $('.articles .article .article-image').height('auto').equalHeights();
            $('.articles .article .article-name').height('auto').equalHeights(); 
            $('.blog-unit').height('auto').equalHeights();
        } else if ($('body').hasClass('mobile')) {
            $('.home-output .product').height('auto').equalHeights();
            $('.brands .brand').height('auto').equalHeights(); 
            $('.categories .category').height('auto').equalHeights();
            $('.articles .article').height('auto').equalHeights();
            $('.blog-unit').height('auto').equalHeights();            
        }   
    }
    $(window).load(function() {
        heightElems();
        vk();
    });
    $(window).resize(function() {
        heightElems();
        vk(); 
    });
    if ($('body').hasClass('mobile')) {
       $('.table').wrap('<div class="table-responsive"></div>');                   
    }  
    $('.slh0 span').remove();
            
	$('#c_submit').attr('disabled', false);
    
    ///////////////////////////////////////////////////////////////////////////////////////////////////
    if ($('#contact-form-replacer').length) {  // move contact form on /articles/ustanovochnye-tsentry/
        $('#hideContactForm').find('.contact-form').addClass('replaced-form');     
        var replacedForm = $('#hideContactForm').html();
        $('#hideContactForm').remove();
        $('#contact-form-replacer').replaceWith(replacedForm); 
        $('#chCallbackForm').sendForm({'header' : '#chCallbackFormHeader'}); 
        $('[data-validation="phone"]').mask('+7(999) 999 - 99 - 99'); 
    }   
	
    ///////////////////////////////////////////////////////////////////////////////////////////////////
});


function sendCallback(){
	var name = $('#c_name').val();
	var tel = $('#c_tel').val();
	var tema = $('#c_tema').val();
	
	if(tel.length < 5){
		formError('tel','номер телефона'); return;
	}

	$('#c_submit').attr('disabled', true).html('<i>отправка...</i>');
	$.post('/ajax/sendCallback.php',{name:name,tel:tel,tema:tema},function(){
		var msg = 'Ваше сообщение успешно отправлено';
		$('#call_form').html('<div class="alert alert-success">'+msg+'</div>');

	});
}

function formError(id,msg){

	$('#c_'+id).after('<div class="alert alert-error" id="form_error">Укажите '+msg+'</div>');

	$('#c_'+id).focus();
	$('#c_'+id).keyup(function(){$('#form_error').remove();});
}

//send forms
(function($) {
    $.fn.sendForm = function(options) { //console.log(Math.random(), this) 
        var settings = $.extend({
            'header': '#header'
        }, options);
        var form = this,
            header = $(settings.header),
            user = 0;
        if (form.find('input[name="user"]').val() == '') {
            user = 1;
        }
        form.find('input,textarea,button').removeAttr('disabled');
        form.find('.form-submit').click(function() {
            form.find('input').each(function(index, element) {
                if (index == 0 && user == 0) {
                    $(this).addClass('focus');
                }
                if (index == 1 && user == 1) {
                    $(this).addClass('focus');
                }
            });
            var required = [];
            form.find('[data-validation]').each(function(index, element) {
                required[index] = {
                    name: $(this).attr('name'),
                    validation: $(this).attr('data-validation')
                };
            });
            $.ajax({
                type: 'POST',
                url: '/mailer/',
                data: {
                    formData: form.serializeArray(),
                    requiredData: required
                },
                success: function(response) {
                    //console.log(response);
                    if (response.indexOf('}') > -1) {
                        var responseObj = jQuery.parseJSON(response),
                            i = 0;
                        $.each(responseObj, function(key, value) {
                            if (i == 0) {
                                //form.find('[name="' + value + '"]').focus(); // off focus, for replace placeholders (crutch), because use "maskedinput"
                                i++;
                            }
                            form.find('[name="' + value + '"]').addClass('required').change(function() {
                                $(this).removeClass('required');
                            });
                        });
                    } else {
                        form.find('.focus').focus();
                        form.find('input,textarea,button').attr('disabled', 'disabled');
                        header.html(response);
                    }
                    
                    // replace placeholders (crutch) //////////////////////////////////////////////////
                    $('input.required[data-validation="phone"]').attr('placeholder','Введите телефон');
                    $('input.required[data-validation="email"]').attr('placeholder','или Email');
                    ///////////////////////////////////////////////////////////////////////////////////
                    if(options.callback) options.callback();
                }
            });
        });
    };
})(jQuery);      

$(document).ready(function() {
    $('#bottomForm').sendForm({'header' : '#bottomFormHeader'});
    

    
    
});     