$(function () {
	initPopup(".reg-popup", "a.reg-popup-opener");
    initPopup(".reg-popup", "a.auth-popup-opener");
    initPopup(".popup", "a.mob-office-opener");
    initPopup(".reg-popup", "a.recommend");
	initPopup(".popup", "a.cart-popup-opener");
	initPopup(".popup", "a.buy-popup-opener");
	initPopup(".popup", "a.btn-order-car");
	initPopup(".popup", "a.get_price");
	initPopup(".popup", "a.btn-red"); 
	initPopup(".popup", "a#order-form-opener"); 
	initPopup(".car-popup", "a.car-info-popup-opener");
    initPopup(".reg-popup", "a.btn-ask-question");
    initPopup(".reg-popup", "a.btn-ask-question2");
    initPopup(".reg-popup", "a.btn-black"); 
    initPopup(".popup", "a.btn-black"); 
    initPopup(".reg-popup", "a.btn-leave-your-feedback");
    initPopup(".reg-popup", "a.btn-leave-your-feedback2");
    initPopup(".car-popup", "a.auctions-show");
    initPopup(".popup", "a.mob-office-order");
    initPopup(".popup", "a.barter-link");
	initTabs();
	initMenu();
	hideFormText();
	initLinks();
	fixTrans();
	initAutoScalingNav({
		menuId: "nav",
		tag: "strong",
		sideClasses: true,
		spacing:12,
		constant: 18
	});
	$('.main-gallery-holder').galleryScroll({
		btPrev: 'a.btn-prev',
		btNext: 'a.btn-next',
		holderList: 'div.overflower',
		scrollElParent: 'ul.gallery2, ul.gallery3',
		scrollEl: 'li',
		slideNum: false,
		duration : 1000,
		step: false,
		circleSlide: false,
		disableClass: 'disable',
		funcOnclick: null
	});
	$('.wrapper-block-holder').galleryScroll({
		btPrev: 'a.btn-prev',
		btNext: 'a.btn-next',
		holderList: 'div.overflower',
		scrollElParent: 'ul.gallery',
		scrollEl: 'li',
		slideNum: false,
		duration : 1000,
		step: false,
		circleSlide: false,
		disableClass: 'off',
		funcOnclick: null
	});
	$('.product-gallery').galleryScroll({
		btPrev: 'a.btn-prev',
		btNext: 'a.btn-next',
		holderList: 'div.overflower',
		scrollElParent: 'ul.gallery',
		scrollEl: 'li',
		slideNum: false,
		duration : 1000,
		step: false,
		circleSlide: false,
		disableClass: 'disable',
		funcOnclick: null
	});
    $('a.btn-prev, a.btn-next').click(function () {
        return false;
    });
	$('ul.current-vacancyes').accordion({
		active: ".active",
		autoHeight: false,
		header: ".opener",
		collapsible: true,
		event: "click"
	});
	$(window).keypress(function(event) {
		if (event.keyCode == '27') {
			$(".overlayer").click();
		}
	});
	$.ajaxSetup({
        type: 'POST',
        dataType: 'json'
    });
	$('form').each(function () {
		if (!$(this).hasClass('notCheck')) {
			$(this).validForm({errorContainer: '#errors'});
		}
		if ($(this).hasClass('ajax')) {
			//$(this).ajaxSubmit({errorContainer: '#errors'});
		}	
	});
    
    /*
    $.ajax({
        url: '/auth/get-user',
        success: function(res) {
            console.log(res);
            if (res.data == false) {
                console.log($('#user-login-form'));
                //$('#user-login-form').css('display', 'block');
            } else {
                $('#user-name').text(res.data['user-name']);
                $('#user-logout-form').css('display', 'block');
            }
        }
    });
    */
    // Login
    $('#user-login').click(function () {
    	$('#errors').html('<span>Проверка данных...</span>');
    	$('#errors').slideDown();
        $.ajax({
            url: '/auth/login',
            data: {
                user_email: $('#user-email').val(),
                user_password: $('#user-password').val()
            },
            success: function (res) {
                if (res.success) {
                	$('#errors').html('<strong>OK!</strong>');
                    $('#user-name').text(res.data['user-name']);
                    $('#user-logout-form').css('display', 'block');
                    $('#user-login-form').css('display', 'none');
                    window.location.reload();
                } else {
                    if (res.data && res.data.messages) {
                    	$('#errors').html(res.data.messages);
                        //alert('Ошибка: ' + res.data.messages);
                        $('#user-email').addClass('inputError');
                        $('#user-password').addClass('inputError');
                    } else {
                        $('#errors').html('Произошла ошибка.');
                        //alert('Произошла ошибка.');
                    }
                }
            }
        });
        return false;
    });
    $('#user-logout').click(function () {
    	$('#errors').html('<span>Проверка данных...</span>');
    	$('#errors').slideDown();
        $.ajax({
            url: '/auth/logout',
            success: function (res) {
                if (res.success) {
                	$('#errors').html('<strong>OK!</strong>');
                    $('#user-logout-form').css('display', 'none');
                    $('#user-login-form').css('display', 'block');
                    window.location.reload();
                } else {
                	if (res.data && res.data.messages) {
                        //alert('Ошибка: ' + res.data.messages);
                        $('#errors').html(res.data.messages);
                    } else {
                        $('#errors').html('Произошла ошибка.');
                        //alert('Произошла ошибка.');
                    }
                }
            }
        });
        return false;
    });

    $('#login-link').click(function () {
        $('#user-login-form').css('display', 'block');
        $('#user-registration-form').css('display', 'none');
        $('#empty-field').css('display', 'block');
        return false;
    });

    // Register
    $('#registration-link').click(function () {
        $('#user-registration-form').css('display', 'block');
        $('#user-login-form').css('display', 'none');
        $('#empty-field').css('display', 'block');
        return false;
    });

    // Restistration submit button click
    $('#register-submit').click(function () {
        var i, email, password, passwordConfirm, id, input;

        $('#errors').html('<span>Проверка данных...</span>');
        $('#errors').slideDown();
        email = $('#register-email').val();
        password = $('#register-password').val();
        passwordConfirm = $('#register-password-confirm').val();
        id = $('#id').val();
        input = $('reg-input-value').val();
        if (password !== passwordConfirm) {
            //alert('Пароли не совпадают');
            $('#errors').html('Пароли не совпадают');
            $('#register-password-confirm').addClass('inputError');
            $('#register-password').addClass('inputError');
            return false;
        }

        $.ajax({
            url: '/auth/registration',
            data: {
                email: email,
                password: password,
                id: $('input[name=id].captha-id').val(),
                input: $('#reg-input-value').val()
            },
            success: function (res) {
                console.log(res);
                if (res.success) {
                	$('#errors').html('<strong>OK!</strong>');
                    window.location.reload();
                } else {
                	if (res.data && res.data.messages) {
                		$('#errors').html(res.data.messages);
                        //alert('Ошибка: ' + res.data.messages);
                        if (res.data.errors.length) {
                        	for (i = 0; i < res.data.errors.length; i++) {
                        		$(res.data.errors[i]).addClass('inputError');
                        	}
                        }	
                    } else {
                        $('#errors').html('Произошла ошибка.');
                        //alert('Произошла ошибка.');
                    }
                }
            }
        });
        return false;
    });

    // Blog

    // Confirm deletion of post
    $('a.blog-post-delete').click(function () {
        return confirm('Вы действительно хотите удалить этот пост?\n' +
                'Это действие нельзя будет отменить.');
    });

    // Delete comment button click
    $('a[href=/blog/delete-comment]').click(function () {
        var id, postId;
        id = this.id.split('-')[3];
        postId = $('#blog-post-id').val();
        $.ajax({
            url: '/blog/delete-comment',
            data: {
                'comment-id': id,
                'post-id': postId
            },
            success: function (res) {
                if (res.success) {
                    document.location.reload();
                } else {
                    alert(res.data);
                }
            }
        });
        return false;
    });

    // Submit comment button click
    $('#comment-submit').click(function () {
        var text, postId;

        text = $('#comment-content').val();
        postId = $('#blog-post-id').val();

        $.ajax({
            url: '/blog/comment',
            data: {
                'comment': text,
                'post-id': postId
            },
            success: function (res) {
                if (res.success) {
                    document.location.reload();
                } else {
                    alert(res.data);
                }
            }
        });
    });

    // Quick links
    $('#quick-links-show').click(function () {
        $('#empty-field').css('display', 'block');
        $('#quick-links').css('display', 'table');
    });

    $('#auction-select').click(function () {
        $('#empty-field').css('display', 'block');
        $('#auctions-field').css('display', 'table');
    });

    $('.auction-link').click(function () {
        $('#auction').attr('value', $(this).html().lower);
        $('#auction-select').html($(this).html());
        $('#empty-field').css('display', 'none');
        $('#auctions-field').css('display', 'none');
    });

    $('#empty-field').click(function () {
        $('#empty-field').css('display', 'none');
        $('#quick-links').css('display', 'none');
        $('#user-login-form').css('display', 'none');
        $('#user-registration-form').css('display', 'none');
        $('#auctions-field').css('display', 'none');
    });

    var tmp = new Array(),		// два вспомагательных
    	tmp2 = new Array(),		// массива
    	getParams = new Array();

    var get = decodeURIComponent(location.search);	// строка GET запроса
    if(get != '') {
    	tmp = (get.substr(1)).split('&');	// разделяем переменные
    	for (var i = 0; i < tmp.length; i++) {
    		tmp2 = tmp[i].split('=');		// массив param будет содержать
    		getParams[tmp2[0]] = tmp2[1];		// пары ключ(имя переменной)->значение
    	}
    }
    
    $('#auction').change(function () {
    	var url = '/ajax/makes',
    		selected = '';
        $('#make').attr('disabled', true);
        $('#make').html('<option value="">- Загрузка... -</option>');
        $.ajax({
            url: url,
            data: {
                auction: $('#auction').val()
            },
            success: function (res) {
                if (res.success) {
                    var options, makes, i;

                    options = '<option value="">- Все марки -</option>';
                    makes = (typeof res.data) === 'string' ? eval('(' + res.data + ')') : res.data;
                    for (i = 0; i < makes.length; i += 1) {
                    	if (getParams.makeid == makes[i].v && $('#auction').val() == getParams.auction) {
                    		selected = 'selected="selected"';
                    	} else {
                    		selected = '';
                    	}
                        options += '<option value="' + makes[i].v + '" ' + selected + '>' + makes[i].t + '</option>';
                    }
                    $('#make').html(options);
                    $('#make').change();
                } else {
                    if (res.data && res.data.messages) {
                        alert('Ошибка: ' + res.data.messages);
                    } else {
                        alert('Произошла ошибка.');
                    }
                }
            }
        });
        $('#make').attr('disabled', false);
    });
    
     $('#auction_1').change(function () {
    	auction_1();
    });



    $('#auction_2').change(function () {
        auction_2();
    });
    $('#auction_3').change(function () {
        auction_3();
    });



    $('#make').change(function () {
    	var url = '/ajax/models',
    		selected = '';
    	
    	if ($('#make').val() != '') {
	        $('#model').attr('disabled', true);
	        $('#model').html('<option value="">- Загрузка... -</option>');
	        if ($(this).hasClass('auto')) {
	        	url = '/ajax/auto-models';
	        }
	        $.ajax({
	            url: url,
	            data: {
	                make: $('#make').val(),
	                auction: $('#auction').val()
	            },
	            success: function (res) {
	                if (res.success) {
	                    var options, models, i;
	                    options = '<option value="">- Все модели -</option>';
	                    models = (typeof res.data) === 'string' ? eval('(' + res.data + ')') : res.data;
	                    for (i = 0; i < models.length; i += 1) {
	                    	if (getParams.modelid == models[i].v && $('#auction').val() == getParams.auction && $('#make').val() == getParams.makeid) {
	                    		selected = 'selected="selected"';
	                    	} else {
	                    		selected = '';
	                    	}
	                        options += '<option value="' + models[i].v + '" ' + selected + '>' + models[i].t + '</option>';
	                    }
	                    $('#model').html(options);
	                } else {
	                    if (res.data && res.data.messages) {
	                        alert('Ошибка: ' + res.data.messages);
	                    } else {
	                        alert('Произошла ошибка.');
	                    }
	                }
	            }
	        });
	        $('#model').attr('disabled', false);
    	} else {
    		$('#model').html('<option value="">- Все модели -</option>');
    	}
    });
    
    $('#prod_make_id').change(function () {
        $('#prod_model_id').attr('disabled', true);
        $('#make-label').html($('#prod_make_id option:selected').html());	
        $('#prod_model_id').html('<option value="">- Загрузка... -</option>');
        $.ajax({
            url: '/ajax/product-models',
            data: {
                make: $('#prod_make_id').val()
            },
            success: function (res) {
                if (res.success) {
                    var options, models, i;
                    options = '';
                    models = (typeof res.data) === 'string' ? eval('(' + res.data + ')') : res.data;
                    for (i = 0; i < models.length; i += 1) {
                        options += '<option value="' + models[i].v + '">' + models[i].t + '</option>';
                    }
                    $('#prod_model_id').html(options);
                } else {
                    if (res.data && res.data.messages) {
                        alert('Ошибка: ' + res.data.messages.join('\n'));
                    } else {
                        alert('Произошла ошибка.');
                    }
                }
            }
        });
        $('#prod_model_id').attr('disabled', false);
    });

    $('.img-link').hover(function () {
        $('.img-main').attr('src', this.href);
    });

    $('a#save-request-link').click(function () {
        $('#save-request').html('Сохранение запроса...');
        $.ajax({
            url: this.href,
            data: {},
            success: function (res) {
                if (res.success) {
                    $('#save-request').html('Запрос сохранен!');
                } else {
                    $('#save-request').html('Ошибка: ' + res.data.messages.join('\n'));
                }
            }
        });
        return false;
    });

    $('a.delete-request-link').click(function () {
        $(this).parent().parent().slideToggle('slow');
        //$(this).parent().html('<span>Удаление запроса...</span>');
        $.ajax({
            url: this.href,
            data: {},
            success: function (res) {
                if (res.success) {
                    //JQuery.remove($(this).parent());
                } else {
                    alert('Ошибка: ' + res.data.messages.join('\n'));
                }
            }
        });
        return false;
    });

    $('div#pagecontent').hover(
        function () {
            $('span.edit').addClass('show');
        },
        function () {
            $('span.edit').removeClass('show');
        }
    );

    $('a.del-from-favorites').click(function () {
        $('a#favorite-del').attr('style', 'display: none');
        $('a#favorite-add').attr('style', 'display: block');
        $('a#favorite-del1').attr('style', 'display: none');
        $('a#favorite-add1').attr('style', 'display: block');
        $.ajax({
            url: this.href,
            data: {},
            success: function (res) {
                if (res.success) {
                } else {
                    alert('Ошибка: ' + res.data.messages.join('\n'));
                }
            }
        });
        return false;
    });

    $('a.add-to-favorites').click(function () {
        $('a#favorite-add').attr('style', 'display: none');
        $('a#favorite-del').attr('style', 'display: block');
        $('a#favorite-add1').attr('style', 'display: none');
        $('a#favorite-del1').attr('style', 'display: block');
        $.ajax({
            url: this.href,
            data: {},
            success: function (res) {
                if (res.success) {
                } else {
                    alert('Ошибка: ' + res.data.messages.join('\n'));
                }
            }
        });
        return false;
    });

    $('div.toolbar').parent().hover(
        function () {
            $(this).children('div.toolbar').addClass('show');
        },
        function () {
            $(this).children('div.toolbar').removeClass('show');
        }
    );

    $('div.review').hover(
        function () {
            $(this).children('div.toolbar').addClass('show');
        },
        function () {
            $(this).children('div.toolbar').removeClass('show');
        }
    );

    $('a.delete-link').click(function () {
        if (confirm('Удалить?')) {
            return true;
        }
        return false;
    });

    $('#show-question-form').click(function () {
        $('div#add-question').addClass('show');
    });

    $('input[type=button].refresh').click(function () {
        $('div.captcha-pic').html('<img src="/images/loading.gif" class="center" />');
        $.ajax({
            url: '/ajax/captcha',
            data: {},
            success: function (res) {
                if (res.success) {
                    $('div.captcha-pic').html(res.data.img);
                    $('input[name=id].captha-id').attr('value', res.data.id);
                } else {
                	$('#errors').html(res.data.messages);
                	$('#errors').slideUp();
                    alert('Ошибка: ' + res.data.messages);
                }
            }
        });
    });

    $('#close-question-form').click(function () {
        $('div#add-question').removeClass('show');
    });

    $('#show-review-form').click(function () {
        $('div#add-review').addClass('show');
    });

    $('#close-review-form').click(function () {
        $('div#add-review').removeClass('show');
    });
    
    $('#add-make').click(function () {
    	var makeName, makeId, newOption;
    	
    	makeName = $('#make-name').val().replace(/(^\s+)|(\s+$)/g, "");
    	if (makeName === '') {
    		alert('Введите имя производителя');
    	} else {
    		 $.ajax({
    			 url: '/ajax/product-add-make',
    	         data: {make: makeName},
    	         success: function (res) {
    	            if (res.success) {
    	            	makeId = res.data.id;
    	                newOption = '<option value="' + makeId + '" selected="selected">' + makeName + '</option>';
    	                $('#prod_make_id option:selected').attr('selected', '');
    	                $('#prod_make_id').append($(newOption));
    	                $('#model-name').val('');
    	                $('#prod_make_id').change();
    	            } else {
    	            	$('#errors').html(res.data.messages);
    	                $('#errors').slideUp();
    	                alert('Ошибка: ' + res.data.messages);
    	            }
    	        }
    	     });
    	}
    });
    
    $('#add-model').click(function () {
    	var makeId, modelName, modelId, newOption;
    	
    	makeId = $('#prod_make_id').val();
    	modelName = $('#model-name').val().replace(/(^\s+)|(\s+$)/g, "");
    	if (modelName == '') {
    		alert('Введите имя модели и выберите производителя');
    	} else {
    		 $.ajax({
    	            url: '/ajax/product-add-model',
    	            data: {make:makeId , model:modelName},
    	            success: function (res) {
    	                if (res.success) {
    	                	modelId = res.data.id;
    	                	newOption = '<option value="' + modelId + '" selected="selected">' + modelName + '</option>';
    	                	$('#prod_model_id option:selected').attr('selected', '');
    	                	$('#prod_model_id').append($(newOption));
    	                	$('#model-name').val('');
    	                } else {
    	                	$('#errors').html(res.data.messages);
    	                	$('#errors').slideUp();
    	                    alert('Ошибка: ' + res.data.messages);
    	                }
    	            }
    	     });
    	}
    });
    
    $('#next').click(function () {
        $('#form-step-1').addClass('hidden');
        $('#form-step-2').removeClass('hidden');
        $('#step-2').addClass('active');
        $('#step-1').removeClass('active');
        if (!$('div.captcha-pic').html()) {
    		$('input[type=button].refresh').click();
    	}
        return false;
    });
    $('#prev').click(function () {
        $('#form-step-2').addClass('hidden');
        $('#form-step-1').removeClass('hidden');
        $('#step-1').addClass('active');
        $('#step-2').removeClass('active');
        return false;
    });
    $('input[type=radio]#radio-jur').click(function () {
        $('#nat').addClass('hidden');
        $('#jur').removeClass('hidden');
    });
    $('input[type=radio]#radio-nat').click(function () {
        $('#jur').addClass('hidden');
        $('#nat').removeClass('hidden');
    });
    
   /* $('#price-popup-submit').click(function () {
    	if (($('#price-phone').val() == '') && ($('#price-email').val() == '')) {
    		$('#errors').html('Пожалуйста, заполните одно из выделенных полей');
    		$('#errors').slideDown('slow');
    		return false;
    	}
    	$('#price-form-submit').click();
    });*/
    
    $('div.submit-holder a span.c span.bullet').click(function () {
    	var submit = $(this).parents('form').find('input[type=submit]');
    	
    	if (!submit.hasClass('not-submit')) {
    		submit.click();
    	} else {
    		if ($(this).parent().parent().attr('id') == 'price-popup-submit') {
    			if (($('#price-phone').val() == '') && ($('#price-email').val() == '')) {
    				$('#price-phone').addClass('inputError');
    				$('#price-email').addClass('inputError');
    	    		$('#errors').html('Пожалуйста, заполните одно из выделенных полей');
    	    		$('#errors').slideDown('slow');
    	    		return false;
    	    	}
    	    	$('#price-form-submit').click();
    		}
    	}
    	
    	return false;
    });
    $('div.submit-holder1 a span.c span.bullet').click(function () {
    	var submit = $(this).parents('form').find('input[type=submit]');
    	
    	if (!submit.hasClass('not-submit')) {
    		submit.click();
    	}
    	
    	return false;
    });
    
    $('div.product-gallery li a').click(function () {
        //$('img#product-full-img').attr('src', $(this).attr('href'));
        var src = $(this).attr('href');
        $("div#product-img-container").fadeOut("fast", function () {
            $("img#product-img").attr('src', src);
            $("div#product-img-container").fadeIn("slow");
        });
        //$("img#product-full-img").attr("src", $(this).attr('href'));
       
        return false;
    });
    
    $('#basket-add-1').click(function () {
    	$('#basket-add-1').parent().html('<h3>Товар в корзине</h3>');
    	$('#basket-add-2').parent().html('<h3>Товар в корзине</h3>');
    	return addToBasket($(this).attr('href'));
    });
    
    $('#basket-add-2').click(function () {
    	$('#basket-add-1').parent().html('<h3>Товар в корзине</h3>');
    	$('#basket-add-2').parent().html('<h3>Товар в корзине</h3>');
    	return addToBasket($(this).attr('href'));
    });
    
    $('#basket-del').click(function () {
    	if (confirm('Удалить данные товары?')) {
    		delFromBasket($(this).attr('href'));
    	}
    	return false;
    });
    
    $('#submit-search-car-form').click(function () {
    	$('form#search-car-form').submit();
    	return false;
    });
    
    $('a.show-history').click(function () {
    	$($(this).attr('rel')).addClass('hidden');
    	$($(this).attr('rel') + '-more').addClass('hidden');
    	$($(this).attr('rel') + '-li').removeClass('active');
    	$($(this).attr('href')).removeClass('hidden');
    	$($(this).attr('href') + '-more').removeClass('hidden');
    	$($(this).attr('href') + '-li').addClass('active');
    	return false;
    });
    
    $('a.auction-choose').click(function () {
    	$('input[type=hidden]#auction').val($(this).attr('id'));
    	$('strong.auctions-show').html($(this).attr('rel'));
    	$('#auction-image').attr('src', $('#' + $(this).attr('id') + '-image').attr('src'));
    	$('div.overlayer').click();
    });
    
    $('#sent-email').click(function () {
    	$('#messages').html('Проверка...');
    	$.ajax({
    		url: '/ajax/send-auto-email',
    		data: {
    			send: $('#auto-send').val(),
    			name: $('#send-name').val(),
    			mailfrom: $('#send-email-from').val(), 
    			mailto: $('#send-email-to').val(), 
    			lot: $('#send-lot').val(),
    			id: $('#captcha-id').val(),
    			input: $('#captcha-input').val()
    		},
    		success: function (res) {
    			$('#messages').html(res.data.messages);
    			alert(res.data.messages);
    			if (res.success) {
    				$('div.overlayer').click();
    			}
    	    }
    	});
    	return false;
    });
    
    $('.sent-auto-comment').click(function () {
    	var lot = $(this).attr('rel');
    	$('#messages-' + lot).html('Сохранение...');
    	$.ajax({
    		url: $(this).attr('href'),
    		data: {
    			lot: lot,
    			comment: $('#comment-' + lot).val()
    		},
    		success: function (res) {
    			$('#messages-' + lot).html(res.data.messages);
    			alert(res.data.messages);
    	    }
    	});
    	return false;
    });
    
    $('a.box').click(function () {
    	var i;
    	for (i = 1; i < 8; i++) {
    		$('#step' + i + '-content' + '-' + $(this).attr('rel')).addClass('hidden');
    		$('a[href=#step' + i + '].box').attr('style', '');
    	}
    	$($(this).attr('href') + '-content' + '-' + $(this).attr('rel')).removeClass('hidden');
    	$(this).attr('style', 'background:url("../images/bg-gallery-container-hover.png") no-repeat scroll 0 0 ');
    	return false;
    });
    
    $('div.index-visual li').hover(
    	function () {
    		$(this).find('a').click();
    	},
    	function () {
    		$(this).click();
    	}
    );
    
    $('ul#cities a').click(function () {
    	$.each($('ul#cities a'), function () {
    		$(this).removeClass('bold');
    	});
    	$(this).addClass('bold');
    	
    	$.each($('div.dealer'), function () {
    		$(this).slideUp('slow');
    	});
    	$($(this).attr('href')).slideDown('slow');
    	
    	return false;
    });
    
    /*$('input[name=phone]').change(function () {
    	$('input[name=company-phone]')
    });*/
    
    $('input[type=text]').change(function () {
    	var current = $(this);
    	if (current.attr('alt')) {
	    	$('input[alt=' + $(this).attr('alt') + ']').each(function () {
	    		$(this).val(current.val());
	    	});
    	}
    });
    
    $('select.year').change(function () {
    	var current = $(this);
    	$('select[name=' + current.attr('name') + ']').each(function () {
    		$(this).val(current.val());
    	});
    });
    
    $('#errors').dblclick(function () {
    	$(this).slideDown();
    	$(this).html('');
    });
    
    $('#order-popup a.tab').click(function () {
    	var tabLink = $(this);
    	$('input[type=hidden]#type').val(tabLink.attr('rel'));
    	$('#order-popup div.tab').each(function () {
    		$(this).addClass('hidden');
    	});
    	$(tabLink.attr('href')).removeClass('hidden');
    });

    $('#price-popup a.tab').click(function () {
    	var tabLink = $(this);
    	$('input[type=hidden]#type').val(tabLink.attr('rel'));
    	$('#price-popup div.tab').each(function () {
    		$(this).addClass('hidden');
    	});
    	$(tabLink.attr('href')).removeClass('hidden');
    });

    $('ul.main-tabset li').hover(function () {
    	var current = $(this);
    	$('ul.main-tabset li').each(function () {
    		$(this).removeClass('active');
    		$($(this).find('a').attr('rel')).addClass('hidden');
    	});
    	current.addClass('active');
    	$(current.find('a').attr('rel')).removeClass('hidden');
    });
    
    $('#search-car-form').submit(function () {
    	var cext = new Array(), cint = new Array();
    	if (!$('#color_ext_empty').attr('checked')) {
    		$('input[type=checkbox].color_ext').each(function () {
    			if ($(this).attr('checked')) {
    				cext.push($(this).val());
    			}
    		});
    	}
    	$('#color_ext').val(cext.join(','));
    	if (!$('#color_int_empty').attr('checked')) {
    		$('input[type=checkbox].color_int').each(function () {
    			if ($(this).attr('checked')) {
    				cint.push($(this).val());
    			}
    		});
    	}
    	$('#color_int').val(cint.join(','));
    	return true;
    });
    
    $('#switch-cat').click(function () {
    	var id = $('#cat').val();
    	window.location = '/products/edit-category/cat/' + id;
    });
    
    $('div.holder-r > a.btn-next').click(function () {
        document.location = $(this).attr('href');
    });
    
    $('div.holder-r > a.btn-prev').click(function () {
        document.location = $(this).attr('href');
    });
    
    $('form.survey input[type=submit]').click(function () {
    	var url = $('form.survey').attr('action'), 
    		data = {0:0}, collection, element;
		$('#errors').html('<span>Отправка данных...</span>');
		$('#errors').slideDown('slow');
        
		$('form.survey').find('input[type=radio]').each(function () {
        	if ($(this).attr('checked')) {
        		data['var'] = $(this).val(); 
        	}
        });
        
        $.ajax({
            url: url,
            data: data,
            success: function (res) {
                if (res.success) {
                	$('#errors').html('<strong>' + res.data.messages + '</strong>');
                	$('#errors').slideDown('slow');
                	$('#survey-content').html(res.data.results);
                	setTimeout(function () {
                		$('#errors').slideUp('slow');
                	}, 5000);
                } else {
                	$('#errors').html(res.data.messages);
                }
            }
        });
        return false;
    });
    
    $('#auto-show-all').click(function () {
    	$('#auto-details').slideDown('slow');
    	$(this).addClass('hidden');
    	return false;
    });
    
    $('#auto-hide').click(function () {
    	$('#auto-show-all').removeClass('hidden');
    	$('#auto-details').slideUp('slow');
    	return false;
    });
    
    $('.refresh').click();
    if ($('.message').html() != '') {
    	$('.message').css('text-decoration', 'blink');
    	setTimeout(function () {
    		$('.message').css('text-decoration', 'none');
    	}, 3000);
    }

    $('#tab_usa').click();

});



function auction_1(){
    $('#auction').val($('#auction_1').val());
    $('#auction_radios').show();
    $('#auction_1').attr('checked', true);
    //$('#make').change();
    $('#auction').change();
}

function auction_2(){
    $('#auction').val($('#auction_2').val());
    $('#auction_2').attr('checked', 'checked');
    $('#auction_radios').show();
    
    //$('#make').change();
    $('#auction').change();

}

function auction_3(){
    $('#auction').val($('#auction_3').val());
    $('#auction_radios').hide();
    $('#auction_3').attr('checked', true);
    //$('#make').change();
    $('#auction').change();
}