(function($) {

	loader = new Image();
	loader.src = '/application/includes/images/ajax-loader.gif';
	sliderCounter = 0;
	var rotate_res_1 = false;
	var rotate_res_2 = false;
	var mouse_res_1 = 0;
	var mouse_res_2 = 0;
	
	$(document).ready(function() {
		
		$('#main').css('height', $('#main').innerHeight()+'px');
		
		$(document).mousemove(function(e) {
			if(rotate_res_1) {
				if(mouse_res_1) {
					rotate_res_1.rotate(e.pageX - mouse_res_1);
				}
				mouse_res_1 = e.pageX;
			}
			if(rotate_res_2) {
				if(mouse_res_2) {
					rotate_res_2.rotate(e.pageX - mouse_res_2);
				}
				mouse_res_2 = e.pageX;
			}
		});
	
		var width_models = $('#slide_line').width()-120;

		$('h2').not('.text h2').prepend('<span class="l_corner"></span>');
		$('h2').not('.text h2').append('<span class="r_corner"></span>');
		$('#footer').corner('round tr tl 10px');
		$('#corners_flash').corner('round br bl 10px');
		$('.text, #choise,.left_ul,.right_ul, #faqLast,.leaders ').corner('round br bl 10px');
		$('.box, #map,.corner').corner('round br bl 10px');

		$('#disks_list, #models_dress_line').corner('round 10px');
		
		$('h1').bind('click',function() {
			window.location="/";
		})
		
		$('#select_town').live('click',function() {
			var title = $(this).attr('title');
			$('#phone_number_box li').show();
			$('#phone_number_box a[title='+title+']').parent().hide();
			$('#phone_number_box').toggle('slow');
		})

		$('#phone_number_box').bind('mouseleave',function() {
			setTimeout(function() {
				$('#phone_number_box').fadeOut();			
			},1500);
		});
		
		$('#phone_number_box a').bind('click',function() {
			var title = $(this).attr('title');
			var text = $(this).text();
			$.ajax({
				url: '/pages/phones/'+title+'/',
				type:'GET',
				cache:true,
				success: function(response) {
					$('#phone').html(response);
					$('#phone_number_box').fadeOut();
					$('#select_town').html(text+' &#9660;');
					$('#select_town').attr('title',title);
				}
			})
		})
		
		$('#submenu .active').bind('click',function() {
			return false;
		})
		FF3 = (function x(){})[-5]=='x';
		FF2 = (function x(){})[-6]=='x';
		
		if(FF3) {
			$('.r_corner').css('margin-top','-24px');
			$('#company_h2 .r_corner').css('margin-top','-27px');
			$('#top_menu').css('width','97%');
		}
		
		if(FF2) {
			$('.leaders').css({'height':'auto !important','overflow':'hidden'});
			$('#top_menu li, .leaders li, #counters_block div,.vendors_image_list li,.marks_list li, #models_dress_line li, #disks_list li').css({'display':'block','float':'left'});
			$('.vendors_image_list li').css({'display':'block','height':'80px'});
			$('#top_menu li').css('margin','0 5%;');
			$('#right_head a').css({'display':'inline','padding':'0 0 0 17px'});
			$('#trash_top_box a').css({'padding-right':'5px'});
			$('#top_menu a').css('display','block');
			$('#disks_list').css({'display':'block','height':'auto !important','overflow':'hidden'});
			$('#disks_list li').css('height','120px');
			$('#company_h2 .r_corner').css('margin-top','-24px');
			$('.r_corner').css('margin-top','-24px');
		}
		
		if(jQuery.browser.msie) {
			if($('body').width() < 1000) {
				$('#main').css('width','995px');
			} else if ($('body').width() > 1000) {
				$('#main').css('width','1200px');
			}
		}

 		active_flash();
		
		$('#top_menu li').each(function() {
			var div = $(this).find('div');
			div.css('width', $(this).innerWidth());
		});
		
		$('#top_menu a').hover(function() {
			$(this).parent().addClass('active');
		},function() {
			$(this).parent().removeClass('active');
		})

		$('#l_arrow_scroll, #r_arrow_scroll').live('mouseout',function() {
			$('#gallery_slide div').stop();
		})

		$('#l_arrow_scroll').live('mouseover',function() {
			var offset = parseInt($('#gallery_slide div').css('left'));
			if (offset!==0) {
			$('#gallery_slide div').animate({
				left:'0px'
			},13000);
		}
		})

		$('#r_arrow_scroll').live('mouseover',function() {
			var scroll_img_count = $('#gallery_slide img').length;
			var scroll_img_width = $('#gallery_slide img').width();
			var scroll_div_width = scroll_img_count*scroll_img_width-$('#gallery_slide img').width()+60;

			var offset = parseInt($('#gallery_slide div').css('left'));

			if(Math.abs(offset) !== scroll_div_width) {
				$('#gallery_slide div').animate({
					left:'-'+scroll_div_width+'px'
				},15000);
			}
		})

		$('#shadow').live('click',function() {
			closeWin('gallery_ajax');
			$('.window_open').fadeOut();
		});
		$('.specify_count').live('click',function(){
		  $.ajax({
			url: $(this).attr('href'),
			type: 'POST',
			dataType: "html",
			success: function(data) {
				$('body').prepend(data);
				$('#shadow').show().css('height',$('body').height()+'px');
				vertical_centering($('#specify_count_form'));
			  }
			});
			return false;
		})
		
		$('#right_models_arrow').bind('click',function() {
			if(parseInt($('#slide_line ul li').length/5) == sliderCounter) sliderCounter = 0;
			else sliderCounter++;
			$('#models_dress_line ul').animate({
				marginLeft :'-'+(sliderCounter*width_models)+'px'
			},400);
		});
		
		$('#left_models_arrow').bind('click',function() {
			if(sliderCounter !== 0) sliderCounter--;
			else sliderCounter = parseInt($('#slide_line ul li').length/5);
			$('#models_dress_line ul').animate({
				marginLeft:'-'+(sliderCounter*width_models)+'px'
			},400);
		});
		
		$('#slide_line img, #slide_line a').live('click',function() {
			$('#main_dress_img_block').html('<img class="loader" src="'+loader.src+'" />');
			var directory = $(this).parent().attr('title');
			showCar(directory);
			showDisks(directory);
		})
				
		$('#disks_list img').live('click',function() {
			var source = $(this).attr('title');
			/*var inches = $('#type_dress_select input:checked').val();
			inches = inches.substr(7);*/
			var offsets = parseInt($('#main_dress_img').offset().left) - parseInt($('#main_dress_img').parent().offset().left);
			var inches = '16';
			var offset_l = parseInt($('#offset_left_disk').val())+offsets;
			var offset_r = parseInt($('#offset_right_disk').val())+offsets;
			var offset_t = parseInt($('#offset_top_disk').val())+29;
			$('#main_dress_img_block .dress_disk').remove();
			source = '/application/includes/images/d/'+source+'/'+inches+'.png';
			$('#main_dress_img_block').append('<div class="dress_disk" id="left_disk_block" style="left:'+offset_l+'px;top:'+offset_t+'px"></div>');
			$('#main_dress_img_block').append('<div class="dress_disk" id="right_disk_block" style="left:'+offset_r+'px;top:'+offset_t+'px"></div>');
			rotation(source,inches,'left_disk_block');
			rotation(source,inches,'right_disk_block');
		});
		
		/*$('#type_dress_select input[name="inches"]').live('change',function() {
			var inches = $(this).val();
			showDisks(inches);
		})*/
		
		$('#colors li').live('click',function() {
			var source = $('#main_dress_img').attr('src');
			arr = source.split('/');
			arr.pop();
			arr[arr.length] = (parseInt($('#colors li').index(this))+1)+'.jpg';
			source = arr.join('/');
			$('#main_dress_img').attr('src',source);
		})
		
		/*$('#podbor_form select').live('change',function() {
			var index = $('#podbor_form select').index($(object));
			$('#podbor_form select:gt('+index+')').html('<option value="null">Сделайте свой выбор</option>').attr('disabled','disabled');
			var param = $('#podbor_form select:eq('+(index+1)+')').attr('name');
			$('#podbor_form select:eq('+(index)+')').after('<img src="/application/includes/images/ajax-loader.gif" id="img_loader" style="float:right"/>');
			var where = $('#choise').serialize();
			
			if($('#modification').val() == 'null') $('#choise .inp_button').attr('disabled','disabled');
			else {
				$('#choise .inp_button').removeAttr('disabled');
				$('#img_loader').remove();			
			}
			if(param !== undefined) {
				$.ajax({
					url:  '/catalog/getPodborParametr/',
					type: 'POST',
					data: 'param='+param+'&'+where,
					success: function(response) {
						$('#podbor_form select:eq('+(index+1)+')').html(response).removeAttr('disabled');
						$('#img_loader').remove();
					}
				})
			}
		});*/
		
		$('#choise .no_border label').bind('click',function() {
			$(this).parent().find('input[type="checkbox"]').removeAttr('checked');
			$(this).prev().attr('checked','checked');
			var typeForm = $(this).prev().val();
			getForm(typeForm);
		})
	})	
	
	podborAuto = function(object) {
			var index = $('#podbor_form select').index($(object));
			$('#podbor_form select:gt('+index+')').html('<option value="null">Сделайте свой выбор</option>').attr('disabled','disabled');
			var param = $('#podbor_form select:eq('+(index+1)+')').attr('name');
			$('#podbor_form select:eq('+(index)+')').after('<img src="/application/includes/images/ajax-loader.gif" id="img_loader" style="float:right"/>');
			var where = $('#choise').serialize();
			
			if($('#modification').val() == 'null') $('#choise .inp_button').attr('disabled','disabled');
			else {
				$('#choise .inp_button').removeAttr('disabled');
				$('#img_loader').remove();			
			}
			if(param !== undefined) {
				$.ajax({
					url:  '/catalog/getPodborParametr/',
					type: 'POST',
					data: 'param='+param+'&'+where,
					success: function(response) {
						$('#podbor_form select:eq('+(index+1)+')').html(response).removeAttr('disabled');
						$('#img_loader').remove();
					}
				})
			}
	}
	
	showDisks = function(car_id) {
		$('#disks_list').html('<li><img src="'+loader.src+'" /></li>');
		$.ajax({
				url: '/dress/showDisks/'+car_id+'/',
				type: 'GET',
				success: function(response) {
					$('#disks_list').html(response);
					if(FF2) {
						$('#disks_list').css({'display':'block','height':'auto !important','overflow':'hidden'});
						$('#disks_list li').css({'display':'block','float':'left'});
					}
				}
			})
	}
	
	showCar = function(directory) {
		var source = '/application/includes/images/d/'+directory+'/1.jpg';
		//showDisks('inches_16');
			$.ajax({
				url: '/dress/getColors/'+directory+'/',
				type: 'GET',
				success:function(response) {
					$('#colors_column').html(response);
					$('#main_dress_img_block').html('<img src="'+source+'" id="main_dress_img"/>');
				}
			});
	}
	
	rotation = function(source,inches,id) {
		var proportions = parseInt(inches*4.2);
		var offset = parseInt((19-inches)*2);
		
		$('#'+id).html('');
		
		var R   = Raphael(id, 100, 100);
		var img = R.image(source, offset, offset, proportions, proportions);
		switch(id) {
			case 'left_disk_block':
				mouse_res_1 = 0;
				rotate_res_1 = img;
				break;
			case 'right_disk_block':
				mouse_res_2 = 0;
				rotate_res_2 = img;
				break;
		}
		/*
		var mouse;
		$('#'+id+'_m').mousemove(function (e) {
			if(mouse) {
				img.rotate(e.pageX - mouse);
			}
			mouse = e.pageX;
		});
		*/
		if ("orientation" in window) {
			var a = 0;
			document.ongesturechange = function (e) {
				var r = e.rotation % 360 - a;
				a += r;
				img.rotate(r);
			}
			document.ongestureend = function () {	a = 0;	}
		}
	}

	showForAuto = function(type,params) {
		$.ajax({
			url: '/catalog/getShowForAuto/'+type+'/'+str_replace('/', '++', params)+'/',
			type: 'GET',
			success:function(response) {
				$('#showForAuto').html(response);
				$('#showForAuto .text').corner('round br bl 10px');
			}
		});
	}
	
	showForAutoDisks = function(type,params,id) {
		$.ajax({
			url: '/catalog/getShowForAuto/'+type+'/'+str_replace('/', '++', params)+'/'+id+'/',
			type: 'GET',
			success:function(response) {
				$('#showForAuto').html(response);
				$('#showForAuto .text').corner('round br bl 10px');
			}
		});
	}
	
	gallery_ajax = function(id,object) {
		scrollTo(0,0);
		var off = $(object).offset();
		var heightShadow = $('#main').innerHeight();
		var widthGallery = $('#gallery_ajax').innerWidth();
		$('#shadow').css('height',heightShadow+'px').show();
		replace_img(id);
		$('#choise select').css('visibility','hidden');
		$('#gallery_slide div').css('left','0px');
		$('#gallery_ajax').css('margin-left','-'+parseInt(widthGallery/2)+'px').show();
	}

	closeWin = function(id) {
		$('#'+id).hide();
		$('#shadow').hide();
		$('#choise select').css('visibility','visible');
	}

	replace_img = function(id) {
		setTimeout(function() {
			$('#main_img img').attr("src","/application/includes/img/b/"+id+".jpg");
			$('#main_img img').attr("title",id);
		},200);
	}
	replace_img_m = function() {
		var next_id;
		var id = $('#main_img img').attr('title');
		$('#gallery_slide img').each(function(i) {
			if($(this).attr('title') == id) next_id = (i+1);
		})
		replace_img($('#gallery_slide img').get(next_id).title);
	}

	check = function(id) {
		value = $('#'+id).val();
		if (value != '') 
			return 1;
		else {
			$('#'+id+'_error').html('Проверьте введенные данные').show();
			return 0;
		}
	}

	send_form = function(name) {
		var error = 0;
		var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
		$('form[name="'+name+'"] *[required]').each(function() {
			if ($(this).val()=='') {
				error ++;
				$(this).addClass('notValid');
			} else if($(this).attr('name') == 'email' && !reg.test($(this).val())) {
				error++;
				$(this).addClass('notValid');
			}			
			else $(this).removeClass('notValid');
		});
		if(error !== 0) {
			$('form[name="'+name+'"] .error').remove();
			$('form[name="'+name+'"]').prepend('<span class="error">Проверьте введеные данные</span>');
		} else {
			setTimeout(function() {
				$('form[name="'+name+'"]').submit();
				},10);
		}
	}

	active_flash = function() {
		document.getElementById('flash_box').innerHTML = ''+
		'<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0" width="100%" align="left">'+
				'<param name="movie" value="/application/includes/swf/3d.swf" />'+
				'<param name="quality" value="high" />'+
				'<param name="wmode" value="opaque" />'+
				'<embed src="/application/includes/swf/3d.swf" wmode="opaque" menu="false" quality="high" scale="scale" width="100%" align="left" allowScriptAccess="sameDomain" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" /></object>';
	}

	getForm = function(type) {
		if (type == 'podbor') {
			$('#choise').attr('action','/catalog/podborAuto/');
			$('.inp_button').attr('disabled','disabled');
		}
		else {
			$('#choise').attr('action','/catalog/search/');
			$('#choise .inp_button').removeAttr('disabled');
		}
		
		
		$('#type_choose_form').html('<img src="/application/includes/images/ajax-loader.gif"/>');
		$.ajax({
			url: '/catalog/getForm/'+type+'/',
			type:'GET',
			cache:true,
			success: function(response) {
				$('#type_choose_form img').remove();
				$('#type_choose_form').html(response);
			}
		});
	}
	
	getParametr = function(type,field,object) {
		var value = $(object).val();
		var select = $(object).attr('name');
		$(object).after('<img src="/application/includes/images/ajax-loader.gif" id="img_loader" style="float:right"/>');
		$.ajax({
			url: '/catalog/getParametrs/'+type+'/',
			type: 'POST',
			data: 'select='+select+'&value='+value+'&field='+field,
			cache:false,
			success: function(response) {
				$('#img_loader').remove();
				$('#'+field).html(response);
				$('#'+field).removeAttr('disabled');
			}
		})
	}
	
	newSearch = function() {
		$.ajax({
			url: '/catalog/clear_session/',
			type:'GET',
			success: function() {}
		});
		$('#type_choose_form select').each(function() {
			if($(this).attr('title') !== 'new') {
				$(this).children('option:first').attr('selected','selected');
				$(this).attr('disabled','disabled');
			}
		});
		
	}
	
	index_image = function(direction) {
		var key = parseInt($('#image_main img').attr('title'));
		var src;
		if(direction == 'left') {
			key = key - 1; 
			src = index_images_array[key];
			if(src == undefined) {
				key = (index_images_array.length-1);
				src = index_images_array[key];
			}
		} else {
			key = key+1;
			src = index_images_array[key];
			if(src == undefined) {
				key = 0;
				src = index_images_array[key];
			}
		}
		$('#image_main img').attr('title',key);
		$('#image_main img').attr('src','/application/includes/main/'+(src));
	}
	
	add_to_trash = function(id,type) {
		count = prompt('Введите количество товара','1');
		if(count){
			$.ajax({
				url: '/catalog/add_to_trash/'+type+'/'+id+'/'+count,
				type:'GET',
				success: function(response) {
					$('#trash_top_box a').html(response);
					$('#trash_top_box a').attr('href','/catalog/trash/');
					$('#trash_top_box a').removeClass('no_link');
					$('#trash_top_box a').css('cursor','pointer');
					alert('Товар добавлен в корзину');
				}
			});
		}
	}

	check_trash = function(object) {
		var id = $(object).prev().text();
		if ($(object).attr('class') == 'trash_checkbox_checked') {
			$(object).addClass('trash_checkbox');
			$(object).next('input').remove();
		}
		else {
			$(object).removeClass('trash_checkbox');
			$(object).after('<input type="hidden" name="order[]" value="'+id+'" />');
		}
	}
	
	edit_cost = function(object) {
		var count = parseInt($(object).val());
		var cost_obj = $(object).parent().prev('td');
		var cost = parseInt(cost_obj.text());
		cost = (cost == 'undefined' || isNaN(cost))?0:cost;
		var total = 0;
        if(count > 10000) {
            return alert('Нельзя заказывать столько много. Исправьте количество');
        } else if(count == 'undefined' || isNaN(count)) {
			return alert('Исправьте количество');
		}
		$(object).parent().find('input[type="hidden"]:last').attr('value',(count*cost));
		$('.trash_table input[name="cost[]"]').each(function() {
			total += parseInt($(this).val());
		});
		$('#total var').html(total);
	}
	
	$('.trash_table .delete_button').live('click',function(){
	  var item = $(this);
	  if(confirm('Удалить из корзины?')){
	    $.ajax({
			url:   $(this).attr('href'),
			type:  'POST',
			cache: false,
			success: function(response) { 
				$(item).parent().parent().remove();
			}
		}); 
	  }
	  return false;
	})
	
	str_replace = function(search, replace, subject) {
		if(!(replace instanceof Array)){
			replace=new Array(replace);
			if(search instanceof Array){//If search    is an array and replace    is a string, then this replacement string is used for every value of search
				while(search.length>replace.length){
					replace[replace.length]=replace[0];
				}
			}
		}
		if(!(search instanceof Array))search=new Array(search);
		while(search.length>replace.length){//If replace    has fewer values than search , then an empty string is used for the rest of replacement values
			replace[replace.length]='';
		}
		if(subject instanceof Array){//If subject is an array, then the search and replace is performed with every entry of subject , and the return value is an array as well.
			for(k in subject){
				subject[k]=str_replace(search,replace,subject[k]);
			}
			return subject;
		}
		for(var k=0; k<search.length; k++){
			var i = subject.indexOf(search[k]);
			while(i>-1){
				subject = subject.replace(search[k], replace[k]);
				i = subject.indexOf(search[k],i);
			}
		}
		return subject;
	}
	specify_count_send = function(){
	  $.ajax({
			url: $('#specify_count_form').attr('action'),
			type: 'POST',
			data: $('#specify_count_form').serialize(),
			dataType: "json",
			success: function(data) {
				alert(data.message);
				if(data.status>0) {$('#specify_count_form').remove();$('#shadow').hide();}
			  }
			});
			return false;
	}
	
})(jQuery);

function vertical_centering(el){
  var elTop  = Math.round($(document).scrollTop()+($(window).height()-$(el).height())/2)+'px';
  $(el).css('top',elTop).show();
}
