﻿jQuery(function() {
    jQuery.noConflict();
	jQuery("#checkorder #telephone").mask("99 (999) 999-99-99");
	jQuery("#checkorder_fast #telephone").mask("99 (999) 999-99-99");
	jQuery("#regaccount #mobile").mask("99 (999) 999-99-99");

	var timetogo = 7;
	var timer = window.setInterval(function()
	{
		jQuery('#countdown').text ('Через '+timetogo+' сек. вы будете перенаправлены на главную страницу.');
		if (timetogo <= 0){

			 window.clearInterval(timer);
		}
		timetogo--;
	}, 1000);
    var isiPad = navigator.userAgent.match(/iPad/i) != null; //Определение iPad
    if (isiPad == true){
		var cssObj = {
			'left':'740px'
		}
		var cssObj1 = {
			'left':'10px'
		}
		var cssObj2 = {
			'font-size':'0.86em'
		}
		var cssObj3 = {
			'width':'332px'
		}
		var cssObj4 = {
			'height':'20px'
		}
		var cssObj5 = {
			'margin-top':'-1px'
		}
		var cssObj6 = {
			'width':'4px'
		}
		var cssObj7 = {
			'margin-right':'-2px'
		}
		var cssObj8 = {
			'background-position':'50% 77px'
		}
    	jQuery('.cart').css(cssObj);  
		jQuery('.main_menu').css(cssObj1);  
		jQuery('.main_menu a').css(cssObj2);
		jQuery('.order .tabs').css(cssObj3);
		jQuery('.pop_up .pop_up_top').css(cssObj4);
		jQuery('.CallForm .pop_up_bot').css(cssObj5);
		jQuery('.main_page_products .product_category .left_edge').css(cssObj6);	
		jQuery('.main_page_products .product_category .right_edge').css(cssObj7);	
		jQuery('.compare').css(cssObj8);		  
    }
    var in_compare = 5;
    addCooki(); //Создаем Cookis
    if (jQuery.browser.msie && jQuery.browser.version <= 8) { //FIX для IE8 и ниже
        var zIndexNumber = 1000;
        jQuery('div.header > *').each(function() {
            jQuery(this).css('zIndex', zIndexNumber);
        zIndexNumber -= 10;
        });
    }
    jQuery('input[placeholder], textarea[placeholder]').placeholder(); //Адаптация placeholder к IE6-8
    //Главный Слайдер - настройки http://slidesjs.com/
    jQuery("#slides").slides({ play: 5000, slideSpeed: 300, pause: 5000 });
    //Показывает DIV логин
    jQuery('.login a').bind('click', function (){
        if (jQuery.browser.msie && jQuery.browser.version <= 8) { //FIX для IE8 и ниже
            runEffect('fade','','.LoginForm','easeInOutExpo',this,'active');
        }else{
            runEffect('drop','up','.LoginForm','easeInOutExpo',this,'active');
        }
        if (jQuery(this).attr('href')=='#') return false;
    });
    //Показывает DIV @позвонить нам
    jQuery('.call_as a').bind('click', function (){
        runEffect('fade','','.CallForm','easeInOutExpo',this);
        return false;
    });
    //Показывает DIV @книга жалоб
    jQuery('.proposal_book, .complaintsForm a').bind('click', function() {
        runEffect('fade','','.complaintsForm','easeInOutExpo',this,'active'); //Стиль, id контейнера, ефект, объект, класс добавления
        return false;
    });
    //Обработчик показа @корзины
    if (jQuery('.total_product').text()=='' || jQuery('.total_product').text()==0) {
        jQuery('.cart_info').hide(); jQuery('.cart_container').addClass('empty');
    }else {
        jQuery('.cart_container').addClass('full_cart');
    }
    //Обработчик добавления в @корзину
    jQuery('.add_to_cart').bind('click', function(){
        if (jQuery(this).is('.added'))  { var url = jQuery(this).attr('href');  window.open(url, '_self'); return false;}
		//если товар уже добавлен прекрашение добавлять
        var articl = jQuery(this).attr('id').replace('addcart_','');
        var div_prodact = jQuery('#img_'+articl);
        if (jQuery('.cart_container').is('.empty')) { //Если @карзина нустая добавляет класс
            jQuery('.cart_container').removeClass('empty').addClass('full_cart');
        }
        var basketX = jQuery('.cart').offset().left; //Позиция корзины на экране от левого края
        var basketY = jQuery('.cart').offset().top;  //Позиция корзины на экране от верхнего края
        var productX = div_prodact.offset().left; //Позиция товара на экране от левого края
        var productY = div_prodact.offset().top; //Позиция товара на экране от верхнего края
        var gotoX = basketX - productX;  //Расчет растояния от товара к карзине от левого края
        var gotoY = basketY - productY;  //Расчет растояния от товара к карзине от верхнего края
        var total_prise = parseInt(jQuery('#price_'+articl).text().replace(' ','')); //Фиксации цеты товара

        jQuery('a[id="addcart_'+articl+'"]').empty().text('Оформить').addClass('added').attr('href','http://city.com.ua/cart/'); //Меняем кнопку купить на оформить добавляем класс

        //Движение картинки от товара к карзине
        jQuery('#img_'+articl).children('img').clone().css({'position':'absolute','top':0}).appendTo(div_prodact)
            .animate({opacity: 1}, 100 )
            .animate({opacity: 0.1, marginLeft: gotoX, marginTop: gotoY, width: 20, height: 20}, 500, function() {
                if (jQuery('.total_product').text()==='') { //Захват количества продукции и общей стоимости в карзине
                    val_product = 0;
                }else{
                    val_product = parseInt(jQuery('.total_product').text());
                }
                if (jQuery('.total_prise').text()==='') {
                  val_price = 0;
                }else{
                  val_price = parseFloat(jQuery('.total_prise').text());
                }
                jQuery(this).remove(); //Удаление картинки товара по дохождению к карзине
                jQuery('.total_product').empty().append(val_product + 1);  //добавляем уденицу к количеству товаров в карзине
                var cart_amount = val_price + total_prise; //сумируем общюю стоимость корзины
                jQuery('.total_prise').empty().append(cart_amount); //Записуем стоимость
                jQuery('.cart_container:not(.hide) .cart_info').slideDown('slow');
            });
        xajax_cassa('add',articl,'1','0'); //Виктор
        return false;
    });
    jQuery('.hide_cart').bind('click',function(){ //По клику свернуть свернуть карзину и закрепить на верху
        jQuery('.cart_container').toggleClass('hide');
        return false;
    });
    function runEffect(effect,direction,container,easi,element,css) { //Функция Эфектов всплывающих окон
        var options = {};
        if ( effect === "drop" ) {
            options = { direction: direction, easing: easi };
        } else if ( effect === "clip" ) {
            options = { easing: easi };
        }
        jQuery(container).toggle(effect, options, 500);
    };
    if (jQuery('.selected_item').is(':empty')) jQuery('.selected_filters').hide(); //Проверка пустоты фильтров если пустой скрываем его
    jQuery('div.index_product').each(function(index) { //Добавление уникального класса к продукции
        jQuery(this).addClass('div_id_'+index);
    });
    jQuery('a.filters_select').bind('click', function(){ //Обработка добавления фильтров

        var append_li = jQuery(this).parent().outerHeight(true)-2; //Высота LI нажатого фильтра
        var class_li = jQuery(this).parent().attr('class'); //Класс родительского пункта нажатого фильтра
        var parent = jQuery(this).parent().parent().parent();
        var parent_class = parent.attr('class'); //Класс папки фильтра
        var value_filters = jQuery(this).html(); //Значение фильтра
        var div_add = '<div class="'+parent_class+'" style="display: none;"><h4>'+parent.find('h4').text()+'</h4><ul class="item_filter" style="height:0px"></ul></div>'; //Добавляемый DIV с названием типа фильтров
        var url_select=jQuery('.filtration').attr('href'); //Виктора
		if(jQuery('.'+parent_class).attr('class').substr(7,4)==2 || jQuery('.'+parent_class).attr('class').substr(7,4)==157) url_select=url_select+jQuery('.'+class_li).attr('class').replace('fvalue_','')+'/'; //Виктора
		else url_select=url_select+jQuery('.'+parent_class).attr('class').substr(7,4)+'-'+jQuery('.'+class_li).attr('class').substr(7,4)+'/'; //Виктора 
//			alert('url_select='+url_select+'; class='+jQuery('.'+class_li).attr('class').replace('fvalue_',''));
        jQuery('.filtration').attr('href',url_select); //Виктора
        url_select=jQuery('.filtration').attr('href'); //Виктора
        if (jQuery('.selected_item').find('.'+parent_class).length==0){ //Проверка есть тип фильтров и добавление его если нет
            jQuery('.selected_item').append(div_add);
            jQuery('.'+parent_class).fadeIn('slow');
        }
        jQuery('.'+parent_class+' .item_filter').append('<li style="display: none;" class="'+class_li+'"><a href="#"><span class="minus"></span>'+value_filters+'</a></li>'); //Добавление пункта к типу фильтров
        jQuery('.'+parent_class+' .item_filter .'+class_li).bind('click', function(){ //Добавление функции для удаления фильтра
        if (jQuery(this).children('span:last').is('.wait')) {return false;}else{jQuery(this).append('<span class="wait" style="display:none"></span>');}
            var parent_div = jQuery(this).parents('div').attr('class'); //Класс типа фильтров с каторого удаляеться фильтр
            var del_li = jQuery(this).outerHeight(true); //Высота удаляемого LI
            jQuery(this).slideUp(100, function() { //Плавное поднятие и проверка по окончанию
                jQuery(this).remove(); //Удаление фильтра
                jQuery(this).find('.wait').remove();
                if (jQuery('.'+parent_div+' .item_filter').is(':empty')) jQuery('.selected_item .'+parent_div).slideUp(500, function() { //Проверка на пустоты типа фильтра и скрытия если пустой
                    jQuery(this).remove(); //Удаление типа фильтра
                    if (jQuery('.selected_item').is(':empty')) jQuery('.selected_filters').slideUp(500); //Проверка наличее фильтров и скрытия DIVа фильтров
                });
            });
            jQuery('.'+parent_class+' .item_filter').animate({ height: "-="+del_li +"px" }); //Уменьшение UL фильтров
            url_select=jQuery('.filtration').attr('href'); //Виктора
			if(jQuery('.'+parent_class).attr('class').substr(7,4)==2 || jQuery('.'+parent_class).attr('class').substr(7,4)==157)	url_select=url_select.replace(jQuery('.'+class_li).attr('class').replace('fvalue_','')+'/',''); //Виктора
			else	url_select=url_select.replace(jQuery('.'+parent_class).attr('class').substr(7,4)+'-'+jQuery('.'+class_li).attr('class').substr(7,4)+'/',''); //Виктора 
			
//            url_select=url_select.replace(jQuery('.'+parent_class).attr('class').substr(7,4)+'-'+jQuery('.'+class_li).attr('class').substr(7,4)+'/',''); //Виктора
            jQuery('.filtration').attr('href',url_select); //Виктора
            jQuery.getJSON("/test1.php?url_path="+url_select, function(data) { //Получение массива нужных фильтров
                jQuery('.filters li ul li').each(function(){ //Проверка фильтров и показ их
                    if (jQuery.inArray(jQuery(this).attr('class'), data)>=0)  jQuery(this).show();
                });
            });
            return false;
        });
        jQuery('.'+parent_class+' .item_filter li:last').fadeIn('slow'); //Показывает добавленый фильтр
        if (jQuery('.selected_filters').css('display') == 'none') { //Показ DIVа фильтров
            jQuery('.selected_filters').slideDown('slow');
        }
        jQuery('.'+parent_class+' .item_filter').animate({ height: "+="+append_li+"px" }); //Увеличение UL фильтров
        jQuery.getJSON("/test1.php?url_path="+url_select, function(data) { //Проверка фильтров и скрытие ненужных
            jQuery('.filters li ul li').each(function(){
                if (jQuery.inArray(jQuery(this).attr('class'), data)<0)  jQuery(this).hide();
            });
        });
        return false;
    });
    jQuery('.show_all_filters').bind('click', function(){ //Показ/Скрыть второстипенных фильтров
        jQuery('.secondary_filters').slideToggle('slow');
        jQuery(this).toggleClass('saf_view');
        return false;
    });

    jQuery('.add_compare').each(function(){
        var idProd, name_img, div_compare_item_img, prodact_name;
        idProd = jQuery(this).attr('id').replace('com_','');
        workArray = cookiMas('compar');
        if (jQuery.inArray(idProd, workArray) >= 0 ) {
            if (jQuery('body').attr('id')=='full_com'){
                jQuery(this).attr('checked','checked').parent().addClass('select');
            }
        }
    });

    if (jQuery('.compare_item').is(':empty')) jQuery('.compare').hide(); //Скрытие DIVа сравнения
    if (jQuery('.compare_item').is(':empty')) jQuery('.compare_small').hide(); //Скрытие DIVа сравнения

    jQuery('.add_compare:not(.similar_items .add_compare)').bind('click', function(){
        if ( jQuery(this).parent().find('span:last').is('.wait')) {return false;}else{jQuery(this).parent().append('<span class="wait" style="display:none"></span>');}
        compare('.compare',this,'full',5,'s_210');
    });

    jQuery('.similar_items .add_compare').bind('click', function(){
        if ( jQuery(this).parent().find('span:last').is('.wait')) {return false;}else{jQuery(this).parent().append('<span class="wait" style="display:none"></span>');}
        compare('.compare_small',this,'small',5,'s_100');
    });
    jQuery('.compare_button').bind('click', function(){
        if (jQuery('.compare_item li').size() <= 1) return false;

    });
    function compare(div,element,fun,in_compare,size) {
        var but, url_select, articl, img_prodact, prodact_name;
        articl = element.id.replace('com_','');
        cookiAdd('compar',articl);
        if (fun=='small'){
            but = jQuery('.compare_similar_button');
        }else{
            but = jQuery('.compare_button');
        }

        jQuery(div).show(); //Показывает DIV сравнить
        jQuery('.compare_view').fadeIn('slow'); //Анимация увеличения DIVа сравнить
        img_prodact = jQuery('#img_'+articl);
        prodact_name = jQuery('#name_'+articl).text(); //Название товара

        var name_img = img_prodact.children('img').attr('src').replace('/images/products/'+size+'/','');  //имя файла картинки товара
        var div_compare_item_img = '<img src="/images/products/s_38/'+name_img+'" />'; //добавление картинки товара

        if (fun=='small'){
            if (jQuery('.compare_item li').size()==0) {
                var main_prod = jQuery('.product_main_info').find('.add_to_cart,.not_exist_product,.preorder,.check_exist').attr('id').replace('addcart_','');
                var main_prod_img =  jQuery('#img_'+main_prod).children('img').attr('src').replace('/images/products/s_320/','')
                main_prod_img = '<img src="/images/products/s_38/'+main_prod_img+'" />';
                jQuery('.compare_item').prepend('<li style="display: none;">'+main_prod_img+'</li>');
                jQuery('.compare_item li:last').slideDown('slow');

                url_select=but.attr('href'); //Виктора
                id_compitem =main_prod.replace('com_','');//Виктора
                if(url_select=='/compare/') url_select=but.attr('href')+main_prod; //Виктора
                else url_select=but.attr('href')+'-'+main_prod; //Виктора
                but.attr('href',url_select); //Виктора
            }
        }else{
            div_compare_item_img = div_compare_item_img + '<span>'+prodact_name+'</span>'
        }

        if (jQuery('#com_'+articl).parent().is('.select')) { //Обработка удаление элемента из DIVа сравнения
            jQuery('.compare_item').find('.com_'+articl).slideUp(500, function() {
                jQuery(this).remove();

                url_select=but.attr('href').replace(articl,'');//Виктора
                url_select =url_select.replace('--','-')
                url_select =url_select.replace('/-','/');//Виктора
                but.attr('href',url_select); //Виктора

                if (jQuery('.compare_item li').size()<in_compare) {
                    jQuery('label:not(.select)').show();
                }
                if (fun=='small'){
                    if (jQuery('.compare_item li').size()==1) { //Проверка DIVа сравнения если пустой скрывает его
                        jQuery('.compare_view').fadeOut(500, function() {
                            jQuery('.compare_item').empty();
                            jQuery(div).hide();
                        });
                    }
                }else{
                    if (jQuery('.compare_item').is(':empty')) { //Если DIV сравнения пуст скрыть его
                        jQuery('.compare_view').fadeOut(500, function() {
                            jQuery(div).hide();
                        });
                    }
                }
            });
            jQuery('#com_'+articl).parent().removeClass('select'); //Удаляем класс SELECT из ссылок сравнения
            jQuery('#com_'+articl).parent().find('.wait').remove();
            return false;
        }
        jQuery('#com_'+articl).parent().addClass('select');

        url_select=but.attr('href'); //Виктора
        if(url_select=='/compare/') url_select=but.attr('href')+articl; //Виктора
        else url_select=but.attr('href')+'-'+articl; //Виктора
        but.attr('href',url_select); //Виктора

        jQuery('.compare_item').append('<li style="display: none;" class="com_'+articl+'"><a href="#" class="remove_item">'+div_compare_item_img+'</a></li>'); //Добавление товара для сравнения

        if (jQuery('.compare_item li').size()==in_compare) {
            jQuery('label:not(.iPhoneCheckLabelOff, .iPhoneCheckLabelOn, .select)').hide();//.addClass('block');
        }
        jQuery('.compare_item li:last').slideDown('slow',function(){
            jQuery('#com_'+articl).parent().find('.wait').remove();
        });

        jQuery('a.remove_item').bind('click', function() { //Добавления функции удаление товара из DIVа сравнения
            var class_rem, but, url_select;
            class_rem = jQuery(this).parent().attr('class').replace('com_','');
            jQuery(this).parent().slideUp(500, function() { //Скрывание товара из DIVа сравнения и удаление его
                jQuery(this).remove();
                cookiAdd('compar',class_rem);
                if (fun=='small'){
                    but = jQuery('.compare_similar_button');
                }else{
                    but = jQuery('.compare_button');
                }
                url_select=but.attr('href').replace(class_rem,'');//Виктора
                url_select =url_select.replace('--','-')
                url_select =url_select.replace('/-','/');//Виктора
                but.attr('href',url_select); //Виктора

                if (jQuery('.compare_item li').size()<in_compare) {
                    jQuery('#com_'+articl).removeAttr('checked').parent().removeClass('select');
                    jQuery('label:not(.select)').show();//.removeClass('block'); //Убираем класс блокировки
                }
                if (fun=='small'){
                    if (jQuery('.compare_item').size()==1) { //Проверка DIVа сравнения если пустой скрывает его
                        jQuery('.compare_view').fadeOut(500, function() {
                            but.attr('href','/compare/');
                            jQuery('.compare_item').empty();
                            jQuery(div).hide();
                        });
                    }
                }else{
                    if (jQuery('.compare_item').is(':empty')) { //Проверка DIVа сравнения если пустой скрывает его
                        jQuery('.compare_view').fadeOut(500, function() {
                            but.attr('href','/compare/'); //Виктора
                            jQuery(div).hide();
                        });
                    }
                }
            });
            jQuery('#com_'+articl).parent().removeClass('select'); //Удаляем класс SELECT из ссылок сравнения
            return false;
        });
    };
    jQuery('a.remove_item').bind('click', function() { //Добавления функции удаление товара из DIVа сравнения
        var class_rem, but, url_select;
        class_rem = jQuery(this).parent().attr('class').replace('com_','');
        jQuery(this).parent().slideUp(500, function() { //Скрывание товара из DIVа сравнения и удаление его
            jQuery(this).remove();
            cookiAdd('compar',class_rem);

            url_select=jQuery('.compare_view').next().attr('href').replace(class_rem,'');//Виктора
            url_select =url_select.replace('--','-')
            url_select =url_select.replace('/-','/');//Виктора
            jQuery('.compare_view').next().attr('href',url_select); //Виктора

            if (jQuery('.compare_item li').size()< in_compare) {
                jQuery('#com_'+class_rem).removeAttr('checked').parent().removeClass('select');
                jQuery('label:not(.select)').show(); //Убираем класс блокировки
            }
            if (jQuery('.compare_item').is(':empty')) { //Проверка DIVа сравнения если пустой скрывает его
                jQuery('.compare_view').fadeOut(500, function() {
                    jQuery('.compare_view').next().attr('href','/compare/'); //Виктора
                    jQuery('.compare_view').parent().hide();
                });
            }
        });
        jQuery('#com_'+class_rem).parent().removeClass('select'); //Удаляем класс SELECT из ссылок сравнения
        return false;
    });
    jQuery('.clear_compare').bind('click', function(index) { //Очистка DIVа сравнения
        jQuery('.compare_view').fadeOut(500, function() {
            jQuery('.compare').hide();
            jQuery('.compare_item').empty();
            jQuery('.content div.index_product').find('.add_compare').removeAttr('checked').parent().removeClass('select');
            jQuery('.index_product label:not(.select)').fadeIn();//.removeClass('block'); //Убираем класс блокировки
        });
        jQuery('.compare_button').attr('href','/compare/'); //Виктора
        cookiAdd('compar','all');
        return false;
    });
    jQuery('.compare_button, .compare_similar_button').bind('click', function() {
        addCookiURL();
    });
    jQuery('.main_menu li').each(function(){
        var lis = jQuery(this).find('a:not(h3 a)');
        for(var i = 0; i < lis.length; i+=7) {
            lis.slice(i, i+7).wrapAll("<span class='new_wrap_ul'></span>");
        }
    });
    jQuery('.main_menu li .sub_menu').hide(); //Скрытие выпадающих пунктов меню
    jQuery('.main_menu li:first').addClass('first'); //Добавление к первому пункту меню класс
    var config = {
        over: makeTall, // function = onMouseOver callback (REQUIRED)
        timeout: 500, // number = milliseconds delay before onMouseOut
        out: makeShort // function = onMouseOut callback (REQUIRED)
    };
    function makeTall(){
        var span_width=0;
        jQuery(this).find('span').each(function(){
            span_width = span_width+jQuery(this).outerWidth();
        });
        jQuery(this).find('.sub_menu').css({'width':span_width+2});
        jQuery(this).addClass('view_sub').find('.sub_menu').slideDown('slow');
    }
    function makeShort(){ jQuery(this).removeClass('view_sub').find('.sub_menu').slideUp('fast');}
    jQuery('.main_menu li').hoverIntent(config); //Действие при наведении мышки на пункт меню
    jQuery('.on_off :checkbox').iphoneStyle({ //Бигунок дешевле/дороже
        checkedLabel: '',
        uncheckedLabel: ''
    });
    if (jQuery('.on_off :checkbox').is(':checked')){ //Обработка бегунка
        jQuery('.cost_sort a:eq(1)').addClass('cost_selected'); //Дороже
    }else{
        jQuery('.cost_sort a:eq(0)').addClass('cost_selected'); //Дешевле
    }
    jQuery('.cost_sort a:not(a.show_all)').bind('click', function(){
        if ( jQuery(this).is('.cost_selected')) return false; //Если пункт выбран прекращаем функцию
        jQuery('.cost_sort a').removeClass('cost_selected');  //Удаление класса выбранного пункта @дешевле/дороже
        jQuery(this).addClass('cost_selected'); //Отмечаем пункт @дешевле/дороже
        jQuery('.on_off :checkbox').attr('checked', !jQuery('.on_off :checkbox').is(':checked')).change();
        return false;
    });
    jQuery('.on_off :checkbox').change(function (){ //Обработка бегунка
        jQuery('.cost_sort a').removeClass('cost_selected');
        if (jQuery('.on_off :checkbox').is(':checked')){
            jQuery('.cost_sort a:eq(1)').addClass('cost_selected'); //Дороже
            window.location = "?sort=desc"; //Виктора
        }else{
            jQuery('.cost_sort a:eq(0)').addClass('cost_selected'); //Дешевле
            var url_ref=window.location.toString().replace('?sort=desc/',''); //Виктора
            var url_ref=url_ref.replace('?sort=desc',''); //Виктора
            window.location = url_ref; //Виктора
        }
    });
    //Менялка картинок
    jQuery('.thumbnails li').each(function(){ //добавление класса к картинки с главной картинки
        var name_img_big = jQuery('.top_img img').attr('src').replace('/images/products/s_320/','');
        var name_img = jQuery(this).children('img').attr('src').replace('/images/products/s_38/','');
        if (name_img_big==name_img) { jQuery(this).addClass('current'); return false;}
    });

    jQuery('.thumbnails li').bind('click', function(){ //Меняем главную картинку на ту каторую нажали
        if (jQuery(this).is('.current')) return false;
        jQuery('.thumbnails li').removeClass('current');
        name_img = jQuery(this).addClass('current').children('img').attr('src').replace('/images/products/s_38/','');
        new_img = '<img src="/images/products/s_320/'+name_img+'" width="320" height="320 alt="" style="display:none;" />';
        jQuery('.top_img img').fadeOut('600', function() {
            jQuery(this).remove();
            jQuery('.top_img').append(new_img).children('img').fadeIn();
        });
    });
    jQuery('.tabs li:not(current)').each(function(){ //скрываем все дивы и показывает тот DIV каторый пунк меню выбран
        var lis = jQuery(this).attr('class');
        jQuery('div.'+lis).hide();
        jQuery('div.tabs_info_header').hide();
    });

    if (jQuery('.tabs li.all').is('.current')==true) {
			setTimeout(margin, 2000);
          jQuery(this).addClass('current');
          jQuery('div.tabs_info_header').show();
          jQuery('div.form').hide();
          jQuery('div.info').children('div').fadeIn();
          margin('begin');
    }

    jQuery('.tabs li').bind('click', function(){ //Прячем и показываем DIVы по нажатию на пункты меню
        jQuery('.tabs li').removeClass('current');
        var lis = jQuery(this).attr('class');
        jQuery('div.form').show();
        jQuery('div.tabs_info_header').hide();
        if (lis!='all') {
            jQuery(this).addClass('current');
            jQuery('div.info').children('div').hide();
            jQuery('div.'+lis).fadeIn();
        }else{
            jQuery(this).addClass('current');
            jQuery('div.tabs_info_header').show();
            jQuery('div.form').hide();
            jQuery('div.info').children('div').fadeIn()
        }
        if(jQuery(this).parents('div').is('.order')) return false;
        margin();
        return false;
    });


    function margin(star) {  //Определение высоты правого слайдера
        var div_all, div, title, margin;
        div_all = jQuery('#right_slide li').size();
        div = jQuery('#right_slide li').outerHeight();
        title = jQuery('.additional_products_header').outerHeight();
        margin = jQuery('.full_info').outerHeight();
        if (star=='begin') {
            jQuery('.jcarousel-clip-vertical').animate({height: (div_all-1)*div});
        }else{
            jQuery('.jcarousel-clip-vertical').animate({height: margin-title-9});
        }
    };
    jQuery('#right_slide').jcarousel({  //Правый слайдер
        vertical: true,
        auto: 1,
        scroll:1,
        animation:1000,
        wrap: 'circular',
        buttonNextHTML:null,
        buttonPrevHTML:null,
        initCallback: initCallback,
        itemFirstOutCallback:margin
    });
    jQuery('#bottom_slide').jcarousel({ //Нижний слайдер
        scroll:1,
        animation:1000,
        buttonNextHTML:'<div class="next_price">дороже</div>',
        buttonPrevHTML:'<div class="prev_price">дешевле</div>',
        start: jQuery('#bottom_slide li').index(jQuery('.item_page'))
    });

    function initCallback(carousel){ //Остановка автоскролла при наведении мышки
        carousel.clip.hover(function() {
            carousel.stopAuto();
        }, function() {
            carousel.startAuto();
        });
        if (jQuery('.tabs li.all').is('.current')==true) {
            margin('begin');
        }else{
            margin();
        }
    };
	  
    jQuery('.cond_table tr:even').addClass('grey'); //Добавление класса к четным полям таблицы

    jQuery( ".parameters_col" ).disableSelection();
    jQuery( ".compare_folder" ).sortable({
        connectWith: ".compare_item",
        scroll:false,
        helper:'clone',
        create: lastDiv,
        update: lastDiv
	});

    function lastDiv (){
        jQuery('.compare_item').removeClass('last');
        jQuery('.compare_item:last').addClass('last');
    };
    jQuery('.parameters_col li').each(function(){
        var liHeight, ind;
        liHeight = jQuery(this).outerHeight();
        ind = jQuery(this).index();
        jQuery('.compare_folder .compare_item').each(function(){
            liHeight_div = jQuery(this).find('li:eq('+ind+')').outerHeight();
            if (liHeight_div > liHeight) liHeight = liHeight_div;
        });
        jQuery('.parameters_col li:eq('+ind+')').css({'height':liHeight});
        jQuery('.compare_item').find('li:eq('+ind+')').css({'height':liHeight});
    });
    jQuery('.parameters_col li:odd').addClass('grey'); //Добавляем нечетным класс
    jQuery('.compare_folder .compare_item').each(function(){
        jQuery(this).find('li:odd').addClass('grey');
    });
    jQuery('.parameters_col li, .compare_folder .compare_item li').not(':first').hover(function(){
        var ind = jQuery(this).index();
        if (ind==0) return false;
        jQuery('.parameters_col li:eq('+ind+')').addClass('hover');
        jQuery('.compare_folder .compare_item').each(function(){
            jQuery(this).find('li:eq('+ind+')').addClass('hover');
        });
    }, function(){
        var ind = jQuery(this).index();
        if (ind==0) return false;
        jQuery('.parameters_col li:eq('+ind+')').removeClass('hover');
        jQuery('.compare_folder .compare_item').each(function(){
            jQuery(this).find('li:eq('+ind+')').removeClass('hover');
        });
    });
    jQuery('.del').bind('click',function(){
        jQuery(this).parents('ul').remove();
        lastDiv();
    });
    jQuery('.plus').bind('click',function(){
        var col_vo, price, articl, val_product, cart_amount;

        col_vo = parseInt(jQuery(this).prev().val()) + 1;
        jQuery(this).prev().val(col_vo);
        price = parseInt(jQuery(this).parents(' .cart_item').find('.item_price .price_ceil').text().replace(' ',''));

        val_product = parseInt(jQuery('.total_product').text()) + 1; //Добавление 1 еденицы к верхней корзине
        jQuery('.total_product').empty().append(val_product);  //записываем величену
        if (jQuery('.total_prise').text()==='') {
            val_price = 0;
        }else{
            val_price = parseFloat(jQuery('.total_prise').text());
        }
        cart_amount = val_price+price; //сумируем общюю стоимость корзины
        jQuery('.total_prise').empty().append(cart_amount); //Записуем стоимость

        jQuery(this).parents('.cart_item').find('.total_item_price .price_ceil').empty().text(price*col_vo);
            articl = jQuery(this).attr('id').replace('plus_',''); //Виктор
		    xajax_add_itemcart(articl,0); //Виктор
        total_prise();
    });
    jQuery('.minus').bind('click',function(){
        var col_vo = parseInt(jQuery(this).next().val())-1;
        if (col_vo < 0) return false;
        if (col_vo == 0) {
            jQuery(this).parents('.cart_item').slideUp('slow', function(){
                jQuery(this).remove();
            });
        }
        jQuery(this).next().val(col_vo);
        var price = jQuery(this).parents(' .cart_item').find('.item_price .price_ceil').text().replace(' ','');

        val_product = parseInt(jQuery('.total_product').text()) - 1; //Добавление 1 еденицы к верхней корзине
        jQuery('.total_product').empty().append(val_product);  //записываем величену
        if (jQuery('.total_prise').text()==='') {
            val_price = 0;
        }else{
            val_price = parseFloat(jQuery('.total_prise').text());
        }
        cart_amount = val_price-price; //сумируем общюю стоимость корзины
        jQuery('.total_prise').empty().append(cart_amount); //Записуем стоимость

        jQuery(this).parents('.cart_item').find('.total_item_price .price_ceil').empty().text(price*col_vo);
            var articl = jQuery(this).attr('id').replace('minus_',''); //Виктор
    		xajax_del_itemcart(articl,0); //Виктор
        total_prise();
        if (jQuery('.total_product').text()==='' || jQuery('.total_product').text()==0) { //
            jQuery('.cart_info').slideUp('slow',function(){
                jQuery('.cart_container').removeClass('full_cart').addClass('empty');
            });
        }
    });
    function total_prise(){
        var total = 0;
        jQuery('.total_item_price .price_ceil').each(function(){
            total = total+parseInt(jQuery(this).text().replace(' ',''));
        });
        jQuery('.total_price').find('.price_ceil strong').empty().text(total)
    }
    jQuery('.delivery_payment .info ul li:not(.active)').each(function(){
        jQuery(this).find('h4 ~ *').hide();
    });
    jQuery('.delivery_payment .info ul li').bind('click',function(){
        jQuery(this).toggleClass('active').find('h4 ~ *').slideToggle(500);
    });
    jQuery('.form .add_address').bind('click',function(){
        var nameEl, idEl, classEl;
        if  (jQuery('#delivery_address').val()=='') {
            jQuery('#delivery_address').focus();
            return false;
        }
        nameEl = parseInt(jQuery('#delivery_address:first').attr('name').replace('delivery_address_',''));
        classEl = 'wide new';
        input = '<input type="text" id="delivery_address" name="delivery_address_'+(nameEl+1)+'" class="'+classEl+'">';
        jQuery('<div class="del_row">х</div>').insertBefore('#delivery_address:first');
        jQuery(input).insertBefore('.del_row:first');
    });
    jQuery('.del_row').live('click',function(){
        jQuery(this).prev().hide().remove();
        jQuery(this).hide().remove();
    });
    /* Cookie */
     //{"id":[ "29", "28", "27", "26", ]} Пример масива
    function addCooki(mas,arr){
        var cookiArr, compar, url, cookiVal, doadd = true, compar_temp, url_temp;
        cookiArr = new Array();
        cookiVal = jQuery.cookie('compere');
        switch(mas){
            case "compar":
                compar = arr;
            break;
            default:
                if (cookiVal==null) { //Если Cooki не существует создает переменные
                    compar = '';
                }else{
                    doadd = false;
                }
        }
        if (!doadd) return false;

        cookiArr.push(compar);
        cookiVal = cookiArr.join(',');
        jQuery.cookie('compere', cookiVal, { expires: 7, path: '/', secure: false });
    };
    function addCookiURL(){
        var url = document.location.href;
        url = url.replace(document.domain,'').replace('http://','');
        jQuery.cookie('url', url, { expires: 7, path: '/', secure: false });
    };
    function cookiMas(){ //Масив для работы из Cooki
        var cookiVal, cookiArr_temp, cookiArr = new Array(), idCall, workArray;
        cookiVal = jQuery.cookie('compere');
        if (cookiArr.length >0  ) cookiArr = cookiVal.split(",");
        else cookiArr = [''];
        workArray = cookiArr;
        return workArray;
    };

    function cookiAdd(mas,element){
        var workArray;
        if (element == 'all'){
            workArray = '';
            addCooki(mas,workArray);
            return false;
        }else{
            workArray = cookiMas();
        }
        if (workArray[0]=='') workArray.shift();
        if (jQuery.inArray(element, workArray)<0){
            workArray.push(element);
        }else{
            workArray.splice (jQuery.inArray(element, workArray),1);
        }
        addCooki(mas,workArray);
    };

    jQuery('.personal_contact_info input').each(function() {
            inputVal =jQuery(this).val();
            jQuery(this).attr('placeholder',inputVal);
    });

    jQuery('.change').bind('click',function(){
        changeInp(this)
        return false;
    });
    function changeInp(elm){
        if (jQuery('.personal_contact_info div.one_info').is('.active')==true) return false;
        jQuery(elm).parents('.one_info').addClass('active').find('.one_info_input').removeAttr('disabled').focus();
        jQuery(elm).parents('.one_info').find('.one_info_input:first').focus();
    };
    jQuery('.reset').bind('click',function(){
        jQuery('.personal_contact_info div.one_info').removeClass('active')
        jQuery('.personal_contact_info input').each(function() {
            inputVal =jQuery(this).attr('placeholder');
            jQuery(this).val(inputVal).prop('disabled', true);
        });
        return false;
    });
    jQuery('.personal_contact_info .add_address').bind('click',function(){
        jQuery('.personal_contact_info div.one_info').removeClass('active')
        jQuery('.personal_contact_info input').each(function() {
            inputVal =jQuery(this).attr('placeholder');
            jQuery(this).val(inputVal).prop('disabled', true);
        });

        if  (jQuery('#delivery_address:first').val()=='') {
            jQuery('#delivery_address:first').parents('.one_info').addClass('active').find('.one_info_input').removeAttr('disabled').focus();
            return false;
        }

        jQuery(this).prev().clone(true).insertBefore(jQuery('#delivery_address').parents('.one_info'))
            .addClass('active').find('.one_info_input').removeAttr('disabled').focus();
        jQuery('#delivery_address:first').val('').attr('placeholder','');

        nameEl = parseInt(jQuery('#delivery_address:first').attr('name').replace('delivery_address_',''));
        jQuery('#delivery_address:first').attr('name','delivery_address_'+(nameEl+1));
        return false;
    });
    /* Всплывающие окна */
	jQuery('.not_exist_product').click(function(){
		//var elem = $(this).closest('.item');
		var articl = jQuery(this).attr('id').replace('addcart_','');
		jQuery.confirm({
			'title'		: 'Этого товара пока<br />нет в наличии.<br />Оставьте свои данные,<br />и мы сообщим Вам о<br />появлении товара.',
			'message'	: '<input type="text" class="pop_up_input" name="name_user" placeholder="Имя"/><br/><input type="text" class="pop_up_input" name="email_user" placeholder="E-mail"/><input type="text" class="pop_up_input" name="phone_user" placeholder="Телефон" />',
			'name_form':'frm_not_exist_product',
			'id_product':articl,
			'buttons'	: {
				'Отправить'	: {
					'class'	: 'submit_button',
					'action': function(){
//						elem.slideUp();
					xajax_send_available_submit(xajax.getFormValues('frm_not_exist_product'));
					}
				},
				'x'	: {
					'class'	: 'cancel_button',
					'action': function(){}	// Nothing to do in this case. You can as well omit the action property.
				}
			}
		});
		return false;
	});
    jQuery('.check_exist').click(function(){
//		var elem1 = jQuery(this).closest('.item');
//		var elem1 = jQuery(this).closest('.item');
		var articl = jQuery(this).attr('id').replace('addcart_','');
//		alert(articl);
		jQuery.confirm({
			'title'		: 'Наличие товара<br />необходимо уточнить.<br />Оставьте свои данные,<br />и мы оперативно сообщим<br />Вам о наличии товара.',
			'message'	: '<input type="text" class="pop_up_input" name="name_user" placeholder="Имя" /><br/><input type="text" class="pop_up_input" name="phone_user" placeholder="Телефон" />',
			'name_form':'frm_check_exist',
			'id_product':articl,
			'buttons'	: {
				'Отправить'	: {
					'class'	: 'submit_button',
					'action': function(){
//						elem.slideUp();
						xajax_send_check_exist_submit(xajax.getFormValues('frm_check_exist'));
//						alert(jQuery('#frm_check_exist').attr('name'));
					}
				},
				'x'	: {
					'class'	: 'cancel_button',
					'action': function(){}	// Nothing to do in this case. You can as well omit the action property.
				}
			}
		});
		return false;
	});
    jQuery('.preorder').click(function(){
		//var elem = $(this).closest('.item');
		var articl = jQuery(this).attr('id').replace('addcart_','');		
		jQuery.confirm({
			'title'		: 'На этот товар можно<br />оформить предзаказ.<br />Отправьте свой контакт,<br />и мы сообщим Вам, когда<br />Вы сможете забрать заказ.',
			'message'	: '<input type="text" class="pop_up_input" name="name_user" placeholder="Имя" id="name_user" /><br/><input type="text" class="pop_up_input" name="contact_user" placeholder="Контакт"/>',
			'name_form':'frm_preoder',
			'id_product':articl,			
			'buttons'	: {
				'Отправить'	: {
					'class'	: 'submit_button',
					'action': function(){
//						elem.slideUp();
						xajax_send_preoder_submit(xajax.getFormValues('frm_preoder'));
//						checkPreoderForm();
					}
				},
				'x'	: {
					'class'	: 'cancel_button',
					'action': function(){}	// Nothing to do in this case. You can as well omit the action property.
				}
			}
		});
		return false;
	});
    jQuery.confirm = function(params){
		if(jQuery('#confirmOverlay').length){
			// A confirm is already shown on the page:
			return false;
		}
		var buttonHTML = '';
		jQuery.each(params.buttons,function(name,obj){
			// Generating the markup for the buttons:
			buttonHTML += '<a href="#" class="button '+obj['class']+'">'+name+'</a>';
			if(!obj.action){
				obj.action = function(){};
			}
		});
		var markup = [
			'<div id="confirmOverlay" class="pop_up">',
			'<div id="confirmBox">',
			'<div class="pop_up_top"></div>',
			'<div class="pop_up_mid">',
			'<span>',params.title,'</span>',
			'<form action="#" method="post" name="',params.name_form,'" id="',params.name_form,'">',
			'<p>',params.message,'</p>',
			'<div id="confirmButtons">',
			buttonHTML,
			'</div>',
			'<input type="hidden" name="id_product" value="',params.id_product,'">',
			'</form>',
			'</div>',
			'<div class="pop_up_bot"></div>',
			'</div></div>'
		].join('');
		jQuery(markup).hide().appendTo('body').fadeIn();
        jQuery('input[placeholder], textarea[placeholder]').placeholder();
		var buttons = jQuery('#confirmBox .button'),
			i = 0;
		jQuery.each(params.buttons,function(name,obj){
			buttons.eq(i++).click(function(){
				// Calling the action attribute when a
				// click occurs, and hiding the confirm.
				if(obj['class']=='cancel_button'){
						obj.action();
						jQuery.confirm.hide();
						return false;
				
				}
				else{
					if(checkConfirmForm(params.name_form) ){
						obj.action();
						jQuery.confirm.hide();
					}

				}
					return false;				
			});
		});
	}

	jQuery.confirm.hide = function(){
		jQuery('#confirmOverlay').fadeOut(function(){
			jQuery(this).remove();
		});
	}

	

});


function chkRegNewAccForm() {
	var fsel = document.regaccount;
	 if	(chkSpace(fsel.mail.value))	{ 
		alert("Не заполнено обязательное поле 'E-mail'"); return false; 
	}	
	else if	(chkSpace(fsel.password.value))	{ 
		alert("Не заполнено обязательное поле 'Пароль не должен быть пустой'"); return false; 
	}
	else if	(fsel.password.value.length<6)	{ 
		alert("Минимальная длинна пароля 6 символов"); return false; 
	}
	else if	(chkSpace(fsel.cpassword.value))	{ 
		alert("Не заполнено обязательное поле 'Повторите пароль'"); return false; 
	}	
	else if	(fsel.password.value!=fsel.cpassword.value)	{ 
		alert("Пароли должны совпадать"); return false; 
	}	
	else if	(fsel.cpassword.value.length<6)	{ 
		alert("Минимальная длинна пароля 6 символов"); return false; 
	}	
	else if	(chkSpace(fsel.name.value))	{ 
		alert("Не заполнено обязательное поле 'Имя'"); return false; 
	}
	/*
	else if	(chkSpace(fsel.surname.value))	{ 
		alert("Не заполнено обязательное поле 'Фамилия'"); return false; 
	}
	*/
	else if	(chkSpace(fsel.mobile.value))	{ 
		alert("Не заполнено обязательное поле 'Контактный телефон'"); return false; 
	}
	else if (fsel.agre_terms.checked == false) { 
			alert("Необходимо согласится с правилами!"); return false; 
	}
	/*
	else if	(chkSpace(fsel.city.value))	{ 
		alert("Не заполнено обязательное поле 'Город'"); return false; 
	}	

	else if	(chkSpace(fsel.address1.value))	{ 
		alert("Не заполнено обязательное поле 'Адрес доставки 1'"); return false; 
	}
		*/
	
	
	else xajax_RegUsrAcc(xajax.getFormValues('regaccount'));
	
}
function chkOrderForm(mode) {
	if(mode==1 ){
		var fsel = document.checkorder;
		if	(chkSpace(fsel.telephone.value))	{ 
			alert("Не заполнено обязательное поле 'Телефон'"); return false; 
		}
		else if (fsel.telephone.length<18) { 
			alert("Заполните правильно обязательное поле 'Телефон'"); return false; 
		}
		else if (fsel.agre_terms.checked == false) { 
			alert("Необходимо согласится с правилами!"); return false; 
		}		
		else xajax_ordersunmit(xajax.getFormValues('checkorder'));		
	}
	else {
		var fsel = document.checkorder_fast;
		if	(chkSpace(fsel.telephone.value))	{ 
			alert("Не заполнено обязательное поле 'Телефон'"); return false; 
		}
		else if (fsel.agre_terms.checked == false) { 
			alert("Необходимо согласится с правилами!"); return false; 
		}		
		else xajax_ordersunmit(xajax.getFormValues('checkorder_fast'));
	}
	return false; 
}

function checkFrmRecall() {
	var fsel = document.FrmRecall;
	
	if	(chkSpace(fsel.phone.value) || fsel.phone.value=='Телефон')	{ 
		alert("Не заполнено обязательное поле 'Контактный телефон'"); 		
		return false; 
	}
	else {
//	alert(';'+fsel.Phone.value+';'); 
		document.getElementById('recall_popup').style.display = 'none';
		xajax_FrmRecallsubmit(xajax.getFormValues('FrmRecall'));

	}

}

function checkFrmBook() {
	var fsel = document.FrmBook;
	if	(chkSpace(fsel.text_book.value))	{ 
		alert("Отсутствует текст сообщения!"); 		
		return false; 
	}
	else {
		document.getElementById('book_popup').style.display = 'none';
		xajax_FrmBooksubmit(xajax.getFormValues('FrmBook'));
	}
	
}

function checkConfirmForm(nameform) {
	var fsel = document.getElementById(nameform);
	if(nameform=='frm_preoder'){
		if	(chkSpace(fsel.contact_user.value))	{ 
			alert("Введите телефон или e-mail!"); 		
			return false; 
		}
		else return true; 
	}	
	else if(nameform=='frm_not_exist_product'){
		if	(chkSpace(fsel.email_user.value))	{ 
			alert("Введите e-mail!"); 		
			return false; 
		}
		else if(chkSpace(fsel.phone_user.value))	{ 
			alert("Введите телефон!"); 		
			return false; 
		}
		else return true; 
	}
	else if(nameform=='frm_check_exist'){
		if	(chkSpace(fsel.phone_user.value))	{ 
			alert("Введите телефон!"); 		
			return false; 
		}
		else return true; 
	}
	return true; 
}

function chkSpace(val) {
	if (val.match(/^\s*$/)) { return true; } else { return false; }
}

function chkRessPassForm() {
	var fsel = document.resetpassform;
	 if	(chkSpace(fsel.mail.value))	{ 
		alert("Не заполнено обязательное поле 'E-mail'"); return false; 
	}
	else xajax_ResetPass(xajax.getFormValues('resetpassform'));
	
}

function CheckAddComments() {
	var fsel = document.FrmComments;
	if	(chkSpace(fsel.comment_email.value))	{ 
		alert("Не заполнено обязательное поле 'E-mail'"); 		
		return false; 
	}	
	else if	(chkSpace(fsel.adv_com.value))	{ 
		alert("Опишите Преимущества товара!"); 		
		return false; 
	}
	else if	(chkSpace(fsel.disadv_com.value))	{ 
		alert("Опишите Недостатки товара!"); 		
		return false; 
	}
	else if	(chkSpace(fsel.comment.value))	{ 
		alert("Дабавьте свой комментарий!"); 		
		return false; 
	}	
	else {
		xajax_FrmCommentssubmit(xajax.getFormValues('FrmComments'));
	}
	
}

function myhideobj(obj_id) {

var robj = document.getElementById(obj_id); 
	robj.style.display = "none";
}

function myshowobj(obj_id) {
var robj = document.getElementById(obj_id); 
	robj.style.display = "block";
}


function showseliteminfo(item_id) {



	var tabid="itemsellinfo_"+item_id;
	var tabid1="tabselliteminfo_"+item_id;

	var result_bookdiv = document.getElementById(tabid); 
	if (result_bookdiv != null)	result_bookdiv.style.display = "block";
	var result_bookdiv1 = document.getElementById(tabid1); 
	if (result_bookdiv1 != null) result_bookdiv1.style.display = "block";
}

function hideseliteminfo(item_id) {

	var tabid="itemsellinfo_"+item_id;
	var tabid1="tabselliteminfo_"+item_id;
	var result_bookdiv = document.getElementById(tabid); 
	if (result_bookdiv != null)	result_bookdiv.style.display = "none";
	var result_bookdiv1 = document.getElementById(tabid1); 
	if (result_bookdiv1 != null) result_bookdiv1.style.display = "none";
}
