/* Author: Antoshen'ka Komkov, Reaktive Studio, Perm, Russia */

var time = 5000;

$(function() {
/* Боковые тени */
	if ($(self).width() > 1360) {
		$('.main_shadows').show();
	}
	if ($(self).height() > $('body').height()) {
		$('body').height($(self).height());
		$('#container').height($('body').height());
	}
/* 404 */
	if ($('#err404').length) {
		var em = $('#content').width()/1.6875;
		$('#err404').css({'font-size': em, 'line-height': em + 'px'});
		$('#main').css({'margin-bottom': 0, 'height': $(self).height() - 191});
		$(self).resize(function() {
			$('#main').css({'margin-bottom': 0, 'height': $(self).height() - 191});
		});
	}
/* Гугл карта */
	if ($('#map').length) {
		initMap();
	}
/* Инпуты  текстареи */
	$('input, textarea').focus(function() {
		$(this).addClass('focused');
		$(this).blur(function() {
			$(this).removeClass('focused');
		});
	});
	if ($(self).width() < 1150) {
		$('#to_deal p').css({'font-size': '.75em', 'padding-top': '26px'});
		$('#to_specification p').css({'font-size': '.75em', 'padding-top': '26px'});
	} else {
		$('#to_deal p').css({'font-size': '.875em', 'padding-top': '24px'});
		$('#to_specification p').css({'font-size': '.875em', 'padding-top': '24px'});
	}
/* Заказать каталог */
	$('#to_catalog').click(function() {
		$('#ld').show();
		$('#catalog').show();
		var wh = $(self).height(),
			fh = $('#form').height();
		if (fh > wh) {
			$('#form').css('top', $(this).position().top + 400);
		} else {
			var t = (wh - fh)/2;
			$('#form').css({'position': 'fixed', 'top': t});
		}
		$('#form').animate({marginLeft: '50%'}, 500);
	});
/* Задайте вопрос нашему специалисту */
	$('#to_quest').click(function() {
		$('#ld').show();
		$('#quest').show();
		var wh = $(self).height(),
			fh = $('#form').height();
		if (fh > wh) {
			$('#form').css('top', $(this).position().top + 100);
		} else {
			var t = (wh - fh)/2;
			$('#form').css({'position': 'fixed', 'top': t});
		}
		$('#form').animate({marginLeft: '50%'}, 500);
	});
/* Стать дилером */
	$('#to_deal').click(function() {
		$('#ld').show();
		$('#deal').show();
		var wh = $(self).height(),
			fh = $('#form').height();
		if (fh > wh) {
			$('#form').css('top', $(this).position().top + 400);
		} else {
			var t = (wh - fh)/2;
			$('#form').css({'position': 'fixed', 'top': t});
		}
		$('#form').animate({marginLeft: '50%'}, 500);
	});
/* Форма ТЗ */
	$('#specification, #to_specification').click(function() {
		$('#ld').show();
		$('#spec').show();
		var wh = $(self).height() - 100,
			fh = $('#form').height();
		if (fh > wh) {
			$('#form').css('top', $(this).position().top);
		} else {
			var t = (wh - fh)/2;
			$('#form').css({'position': 'fixed', 'top': t});
		}
		$('#form').animate({marginLeft: '50%'}, 500);
	});
/* Лейер дивайдер и клоус форм */
	$('#ld, .close_form').click(function() {
		$('#form').animate({marginLeft: '-50%'}, 500, function() {
			$('#form .form#'+$('#form .form:visible').attr('id')).hide();
			$('#ld').hide();
		});
	});
/* Визуал */
	if ($('#visual').length) {
		$('#im_'+num).fadeIn(200);
		$('#s_'+num).show();
		$('#visual .sign').animate({'height': '45px'}, 200);
		setTimeout(next_vis, time);
	}
/* Скроллер */
	if ($('#i_industries').length) {
		var scb = $('#i_industries .scrollbar'),
			scb_h = scb.height(),
			scr = scb.find('.scroller'),
			nfo = $('#i_industries .info');
		
		scr.draggable({
			containment: scb,
			drag: function(event, ui) {
				draging();
			}
		});
		
		scr.height(250/nfo.height()*scb_h);
		
		function draging() {
			var percent = scr.position().top / (scb_h - 20);
			nfo.css('top', -percent * nfo.height());
		}
		
		$(self).resize(function() {
			scr.height(250/nfo.height()*scb_h);
			draging();
		});
		
		$('#i_industries').mousewheel(function(event, delta) {
			var tp = scr.position().top-delta*20,
			pl = scb_h - scr.height();
			if (tp < 0) {
				tp = 0;
			} else if (tp > pl) {
				tp = pl;
			}
			scr.css('top', tp);
			draging();
			log(tp);
			return false;
		});
	}
/* Навигация */
	if ($('#isub').length) {
		$('#top a').mouseover(function() {
			if ($(this).attr('id')) open_sm($(this).attr('id'));
		});
		$('#top a').mouseout(function() {
			if ($(this).attr('id')) timeout_sm();
		});
		$('#isub .links').hover(function() {
			clearTimeout(timeout);
		}, function() {
			$(this).css({'bottom': 0}, 100);
			$('#isub .bg').css({'bottom': 0, 'height': 5, 'opacity': 1});
		});
	}
/* Слайдер с логотипами */
	if($('#partners').length){
		logoSlider();
	}
/* Реактив */
	$('#rktv a, #rktv #reaktive_block').hover(function() {
		ShowReaktiveStart();
	}, function() {
		HideReaktiveStart();
	});
/* Специальные товары */
	$('.blocks .block .img').each(function() {
		if ($(this).find('a img').height() < 150) {
			var t = (150 - $(this).find('a img').height())/2;
			$(this).find('a img').css('top', t);
		}
	});
});

$(self).resize(function() {
	/*if ($('#ld').css('display') == 'block') {
		var wh = $(self).height(),
			fh = $('#form').height();
		if (fh > wh) {
			$('#form').css('top', $(this).position().top + 400);
		} else {
			var t = (wh - fh)/2;
			$('#form').css({'position': 'fixed', 'top': t});
		}
	}*/
	if ($(self).width() < 1150) {
		$('#to_deal p').css({'font-size': '.75em', 'padding-top': '26px'});
		$('#to_specification p').css({'font-size': '.75em', 'padding-top': '26px'});
	} else {
		$('#to_deal p').css({'font-size': '.875em', 'padding-top': '24px'});
		$('#to_specification p').css({'font-size': '.875em', 'padding-top': '24px'});
	}
/* 404 */
	if ($('#err404').length) {
		var em = $('#content').width()/1.6875;
		$('#err404').css({'font-size': em, 'line-height': em + 'px'});
	}
/* Боковые тени */
	var ms = $('.main_shadows');
	$(self).width()>1360?ms.show():ms.hide();
	if ($(self).height() > $('body').height()) {
		$('body').height($(self).height());
		$('#container').height($('body').height());
	} else {
		$('body').height('auto');
		$('#container').height('auto');
	}
});

/* Реактив */
var ShowReaktiveFlag = false;
function ShowReaktiveStart() {
	ShowReaktiveFlag = true; setTimeout("ShowReaktive()", 50);
}
function ShowReaktive() {
	if ((ShowReaktiveFlag) && ($("#reaktive_block").css('display')=='none')) {
		$("#reaktive_block").css({display: "block"});
		$("#reaktive_block img").css({width: 0, height: 0, left: 206, top: 0});
		$("#reaktive_block img").animate({width: 274, height: 131, left: 0, top: -125}, 200);
	}
}
function HideReaktiveStart() {
	ShowReaktiveFlag = false; setTimeout("HideReaktive()",50);
}
function HideReaktive() {
	if ((!ShowReaktiveFlag) && ($("#reaktive_block").css('display')!='none')) {
		if ($.browser.msie) $("#reaktive_block").css('display','none');
		else $("#reaktive_block").fadeOut(300);
	}
}

/* Визуал */
var num = 1,
	nums = $('#visual .pictures img').length;

function next_vis() {
	$('#im_'+num).fadeOut(200, function() {
		$('#s_'+num).hide();
		num += 1;
		if (num > nums) num = num - nums;
		$('#im_'+num).fadeIn(200);
		$('#s_'+num).show();
		$('#visual .sign').animate({'height': '5px'}, 200);
		setTimeout(next_vis, time);
	});
	$('#visual .sign').animate({'height': '5px'}, 200, function() {
		$('#visual .sign').animate({'height': '45px'}, 200);
	});
}

/* Слайдер с логотипами */
function logoSlider(){
	var $logoSlider = $('#partners .logos'),
		slWidth = $logoSlider.width(),
		itWidth = 0,
		$rC = $('.arrows.right'),
		$lC = $('.arrows.left'),
		$cont = $('#partners ul'),
		offset = 0;
	
	$cont.css('left', 0);
	$('#partners ul li').each(function(){
		itWidth += $(this).width()+1;
	});
	offset = slWidth - itWidth;
	if(offset > 0){
		$lC.hide();
		$rC.hide();
		$cont.width(itWidth);
		$cont.css('margin', '0 auto');
	}else{
		$lC.hide();
		$rC.show();
	}
	$lC.mousedown(function(){
		$rC.show();
		var time = Math.round(Math.abs($cont.position().left)*1);
		$cont.animate({left:0}, time, function(){$cont.stop(true);$lC.hide();});
	});
	$lC.mouseup(function(){$cont.stop(true);});
	$rC.mousedown(function(){
		$lC.show();
		var time = Math.round(Math.abs(($cont.position().left) - offset)*1);
		$cont.animate({left:offset}, time, function(){$cont.stop(true);$rC.hide();});
	});
	$rC.mouseup(function(){$cont.stop(true);});
	$(self).resize(function(){
		$cont.css('left', 0);
		slWidth = $logoSlider.width();
		offset = slWidth - itWidth+2;

		if(offset > 0){
			$lC.hide();
			$rC.hide();
			$cont.width(itWidth);
			$cont.css('margin', '0 auto');
		}else{
			$lC.hide();
			$rC.show();
		}
	});
}

/* Гугл карта */
function initMap() {
	var latLng = new google.maps.LatLng(57.984581, 56.258132);
	var map = new google.maps.Map(document.getElementById("map"), {
		zoom: 15,
		center: latLng,
		mapTypeId: google.maps.MapTypeId.ROADMAP,
		scrollwheel: false
	});
	var markerLatLng = new google.maps.LatLng(57.983215, 56.254892);
	var marker = new google.maps.Marker({
		position: markerLatLng,
		map: map
	});
	var contentString = "<p style='font-size: .75em'><strong>Кама-МСМ</strong><br>Комсомольский проспект 98<br>телефон/факс: (342) 241–01–54<br>e-mail: <a href='mailto:info@kama-msm.perm.ru'>info@kama-msm.perm.ru</a></p>";
	var infowindow = new google.maps.InfoWindow({
		content: contentString
	});
	google.maps.event.addListener(marker, 'click', function() {
		infowindow.open(map, marker);
	});
}

/* Навигация */
var timeout;
function open_sm(id) {
	$('#top a').unbind();
	clearTimeout(timeout);
	$('#isub .links').css('bottom', 0);
	$('#isub .bg').css({'bottom': 0, 'height': 5, 'opacity': 1});
	var nums = [];
	nums = id.split('_');
	var num = nums[1];
	var t = $('#sm_'+num).height() - 5;
	$('#sm_'+num).css({'bottom': -t});
	$('#isub .bg').css({'height': t, 'opacity': .85, 'bottom': -t}, t);
	$('#top a').mouseover(function() {
		if ($(this).attr('id')) open_sm($(this).attr('id'));
	});
	$('#top a').mouseout(function() {
		if ($(this).attr('id')) timeout_sm($(this).attr('id'));
	});
}
function timeout_sm(id) {
	var nums = [];
	nums = id.split('_');
	var num = nums[1];
	var t = $('#sm_'+num).height() - 5;
	timeout = setTimeout("close_sm("+num+", "+t+")", 500);
}
function close_sm(num, t) {
	$('#sm_'+num).css({'bottom': 0}, t);
	$('#isub .bg').css({'height': 5, 'opacity': 1, 'bottom': 0}, t);
}


$(function() {
	var y;
	$('#form button').click(function() {

        function close() {
            $('#form').animate({marginLeft: '-50%'}, 500, function() {
                $('#form .form#'+$('#form .form:visible').attr('id')).hide();
                $('#ld').hide();

                if(y == 1)
                    $('.form_sended').hide();
                else
                    $('.form_error').hide();
                
                 $('#techForm')[0].reset();
				 $('#techForm').find('.f_files').html('')
                 $('#catalogForm')[0].reset();
                 $('#dilerForm')[0].reset();
                 $('#questionForm')[0].reset();

                $('#form').css({'height': 'auto'});
            });
        }

        function next() {
            if(y == 1) {
                $('.form_sending').hide();
			} else {
                $('.form_error').hide();
			}
			$('.form_sended').show();
			setTimeout(close, 2000);
        }


        var formID = $(this).parent().parent().parent().attr('id');
        var error = 0;

        if( formID == 'dilerForm'){

            $('#dilerForm input').each(function(){
               if($(this).val() == ''){
                   $(this).addClass('in_error');
                   $(this).prev().addClass('error');
                   error = 1;
               } else {
                   $(this).removeClass('in_error');
                   $(this).prev().removeClass('error');
               }
            });

            if(error  == 0){

                $('#form').css('height', $('#form').height());
                $('.form').hide();
                $('.form_sending').show();

                var city = $("#dilerForm").find("#f1_city").val();
                var org = $("#dilerForm").find("#f1_org").val();
                 var name = $("#dilerForm").find("#f1_name").val();
                var contact = $("#dilerForm").find("#f1_cont").val();
                var category = $("#dilerForm").find("#f1_cat").val();

                    $.ajax({
                        type: "POST",
                        url: "/ajax/type/dilerForm",
                        data:{
                            "city" : city,
                            "contact" : contact,
                            "name" : name,
                             "category" : category,
                             "org" : org
                        },
                        cache: false,
                        success: function(){
							y=1;
                            setTimeout(next, 2000);
                        },
                        failure: function(){
							y=0;
                            setTimeout(next, 2000);
                        }
                    });

            }
        } else if(formID == 'techForm'){

            $('#techForm input').each(function(){
               if($(this).val() == '' && $(this).attr('id') != 'f2_mssg' && $(this).attr('id') != 'f2_file'){
                    $(this).addClass('in_error');
                   $(this).prev().addClass('error');
                   error = 1;
               } else {
                   $(this).removeClass('in_error');
                   $(this).prev().removeClass('error');
               }
            });

            if(error  == 0){

                $('#form').css('height', $('#form').height());
                $('.form').hide();
                $('.form_sending').show();

                var mail = $("#techForm").find("#f2_mail").val();
                var org = $("#techForm").find("#f2_org").val();
                var message = $("#techForm").find("#f2_mssg").val();
                var name = $("#techForm").find("#f2_name").val();
                var appointment = $("#techForm").find("#f2_appointment").val();
                var phone = $("#techForm").find("#f2_phone").val();
                var file = $("#techForm").find(" #f2_file").val();

                $.ajax({
                    type: "POST",
                    url: "/ajax/type/techForm",
                    data:{
                        "mail" : mail,
                        "name" : name,
                        "org" : org,
                        "message":  message,
                        "appointment": appointment,
                        "phone": phone,
                        "file":  file
                    },
                    cache: false,
					success: function(){
						y=1;
						setTimeout(next, 2000);
					},
					failure: function(){
						y=0;
						setTimeout(next, 2000);
					}
                });

            }

        } else if(formID == 'questionForm'){


            $('#questionForm input').each(function(){
               if($(this).val() == '' && $(this).attr('id') != 'f3_mssg'){
                    $(this).addClass('in_error');
                   $(this).prev().addClass('error');
                   error = 1;
               } else {
                   $(this).removeClass('in_error');
                   $(this).prev().removeClass('error');
               }
            });

            if(error  == 0){


                $('#form').css('height', $('#form').height());
                $('.form').hide();
                $('.form_sending').show();

                var city = $("#questionForm").find("#f3_city").val();
                var contact = $("#questionForm").find("#f3_cont").val();
                 var message = $("#questionForm").find("#f3_mssg").val();

                $.ajax({
                    type: "POST",
                    url: "/ajax/type/questionForm",
                    data:{
                        "city" : city,
                        "contact" : contact,
                        "message" : message
                    },
                    cache: false,
					success: function(){
						y=1;
						setTimeout(next, 2000);
					},
					failure: function(){
						y=0;
						setTimeout(next, 2000);
					}
                });

            }

        } else if (formID == 'catalogForm'){


            $('#catalogForm input, #catalogForm  textarea').each(function(){
               if($(this).val() == ''){
                    $(this).addClass('in_error');
                   $(this).prev().addClass('error');
                   error = 1;
               } else {
                   $(this).removeClass('in_error');
                   $(this).prev().removeClass('error');
               }
            });

            if(error  == 0){

                $('#form').css('height', $('#form').height());
                $('.form').hide();
                $('.form_sending').show();

                var catalogs = $("#catalogForm").find("#f4_cats").val();
                var org = $("#catalogForm").find("#f4_org").val();
                var addr = $("#catalogForm").find("#f4_adr").val();
                var name = $("#catalogForm").find("#f4_name").val();
                var appointment = $("#catalogForm").find("#f4_appointment").val();
                var phone = $("#catalogForm").find("#f4_phone").val();

                    $.ajax({
                        type: "POST",
                        url: "/ajax/type/catalogForm",
                        data:{
                            "catalogs" : catalogs,
                            "name" : name,
                            "org" : org,
                            "addr":  addr,
                            "appointment": appointment,
                            "phone": phone
                        },
                        cache: false,
                        success: function(){
							y=1;
                            setTimeout(next, 2000);
                        },
                        failure: function(){
							y=0;
                            setTimeout(next, 2000);
                        }
                    });

            }

        }


        
		return false;
	});


    var btnUpload=$('#upload');
    var status=$('#status');
    new AjaxUpload(btnUpload, {
    action: '/ajax/type/uploadFile',
    //Имя файлового поля ввода
    name: 'uploadfile',
        onSubmit: function(file, ext){
        if (! (ext && /^(doc|docx|odt|txt|jpg|png|jpeg|gif|png|pdf|rar|zip|tif|xls|xlsx|djvu)$/.test(ext))){
            // Валидация расширений файлов
            status.html('<span style="color: red;">Данный тип файлов не подходит для загрузки.</span>');
            return false;
        }
            status.html('<span style="color: green;">Загрузка...</span>');
        },
        onComplete: function(file, response){
        //Очищаем текст статуса
        status.text('');
        //Добавляем загруженные файлы в лист
            if(response==="success"){
                $('#f2_file').val(file);
                $('#files').html('<p class="f_files"><i></i>'+file+'</p>').addClass('success');
            } else{
                $('#files').html('<p class="f_files">Ошибка при загрузке файла</p>').addClass('error');
            }
        }
    });

});

