var ax_err_show=true;

//hs.align = 'center';
hs.marginLeft = 500;
hs.transitions = ['expand', 'crossfade'];
hs.fadeInOut = true;
hs.outlineType = 'rounded-white';
hs.wrapperClassName = 'white';
hs.captionEval = 'this.a.title';
hs.width = 600;
hs.height = 470;
hs.easing = 'easeOutBack';
hs.easingClose = 'easeInBack';
var hsSlideOpt={
	interval: 5000,
	repeat: true,
	useControls: true,
	fixedControls: 'fit',
	overlayOptions: {
		position: 'top center',
		opacity: .75,
		offsetY:-50,
		hideOnMouseOut: false
	},
	thumbstrip: {
		position: 'bottom center',
		mode: 'horizontal',
		relativeTo: 'expander'
	}
}

var gOpt1 = {
	thumbnailId: 'thumb1',
	slideshowGroup: 1
}

function hsGalInit(){
	hs.dimmingOpacity = 0.8;
	hs.marginLeft = 0;
	hs.useBox = true;
	hs.numberPosition = 'heading';
	hs.addSlideshow(hsSlideOpt);
	hs.align = 'center';
}


function setCookie (cookieName, cookieContent, ses)
{
if(isNaN(ses)){
 	var expDate=new Date();
 	expDate.setTime(expDate.getTime()+8640000000000);
 	var expires=expDate.toGMTString();
}else var expires='';

document.cookie=cookieName+"="+escape(cookieContent)+"; path="+escape('/')+"; expires="+expires;
}

function delCookie (cookieName)
{
 var expDate=new Date();
 expDate.setTime(expDate.getTime()-1000);
 var expires=expDate.toGMTString();
 document.cookie=cookieName+"=; path="+escape('/')+"; expires="+expires;
}

function getCookie(name)
{ var cname = name + "=";               
  var dc = document.cookie;             
  if (dc.length > 0) 
  { begin = dc.indexOf(cname);       
    if (begin != -1) 
    { begin += cname.length;       
      end = dc.indexOf(";", begin);
      if (end == -1) end = dc.length;
      return unescape(dc.substring(begin, end));
    } 
  }
  return null;
}

function Err(XMLHttpRequest, textStatus, errorThrown){
	if(ax_err_show) msg('Ошибка при загрузке данных ('+textStatus+'). Попробуйте обновить страницу и повторить запрос');
}

function _alert(msg){
	if(ax_err_show) window.alert(msg);
}
function msg(msg){
	jQuery.facebox(msg);
//window.alert(msg);
}

var loading='<img id="loading" src="/images/loading.gif" width="16" height="16" align="absmiddle" hspace="5">';

function substr_count( haystack, needle, offset, length ) { // в ие 6 не работает
   var pos = 0, cnt = 0;
   if(isNaN(offset)) offset = 0;
   if(isNaN(length)) length = 0;
   offset--;
   while( (offset = haystack.indexOf(needle, offset+1)) != -1 ){
       if(length > 0 && (offset+needle.length) > length){
           return false;
       } else{
           cnt++;
       }
   }

   return cnt;
}

String.prototype.trim = function() {
	return this.replace(/^\s+|\s+$/g,"");
}

$(document).ready(function(){
						   
	$.ajaxSetup({
		type:'POST',
		global: true,
		cache:false,
		dataType: 'json',
		error: Err
	}); 
	
	jQuery('a[rel*=facebox]').facebox();
						   
	$('.highslide').click(function(){
		if(!hs.slideshows.length) hs.marginLeft=400+Math.round(Math.random()*200); else hs.marginLeft=0;
	});
	$('#openGal').click(function(){
		$('#thumb1').trigger('click');
		return false;
	});
	
	function tsf1(){
		setCookie('tsf1',$('#ts_form').serialize());	
		
	}
	function tsf2(){
		setCookie('tsf2',$('#ds_form').serialize());	
	}
	$('#ts_form *').change(tsf1);
	$('#ds_form *').change(tsf2);
	
	$('#c_filter input').change(function(){
		$("#ts_form input[name='"+$(this).attr('name')+"']").attr('checked',$(this).attr('checked'));
		tsf1();
	});

	$('div.sf tr').hover(
		function(){ if($(this).children('td[colspan=]').is('td')) $(this).children().css('background','#ffbb15') }, 
		function(){ if($(this).children('td[colspan=]').is('td')) $(this).children().css('background','#eeeeee') } 
	);
	
	$('input[class=cmp1], input[class=cmp2]').change(function(){
		var gr=$(this).attr('class').substring(3,4);
		var cat_id=$(this).val();
		if(getCookie('cmp'+gr+'_'+cat_id)!=null) {delCookie('cmp'+gr+'_'+cat_id);}
			else setCookie('cmp'+gr+'_'+cat_id,'true');
	});
	
	$('.go_cmp1').click(function(){
		var c=substr_count(document.cookie, 'cmp1_');
		if(c>1) location.href='/compare/tyres.html?'+Math.random(); else msg('Выберите как минимум две шины для сравнения. <br>Сейчас выбрано '+c);
		return false;
	});
	$('.go_cmp2').click(function(){
		var c=substr_count(document.cookie, 'cmp2_');
		if(c>1) location.href='/compare/wheels.html?'+Math.random(); else msg('Выберите как минимум два диска для сравнения. <br>Сейчас выбрано '+c);
		return false;
	});
		
	$("div.parth div.parthin p.name").hover(function(){
		$(this).css('background','url(/images/mbg.gif) repeat-x top');
	},function(){
		$(this).css('background','#979797');
	});
	
	$('#main_cart').click(function(){
		location.href='/cart.html?'+Math.random();
		return false;
	});
	
	// CART control
	
	$('.buy').click(function(){
		msg('Добавляем в корзину....');
		$.ajax({
			url: '/ajx/cart.html',
			type: 'GET',
			data: { act: 'add', cat_id: $(this).attr('cat_id'), amount:4 },
			success: function(d){
				if(d.fres) msg(d.fres_msg); else msg(d.err_msg);
			}
		});
		return false;
	});
		
	$('.cart_tbl .cart_del').click(function(){
		var cat_id=$(this).attr('cat_id');
		$.ajax({
			url: '/ajx/cart.html',type: 'GET', data: { act: 'del', cat_id: $(this).attr('cat_id')},
			success: function(d){
				$('#summa').text(d.summa);
				$('#itog').text(d.itog);
				$('#dcost').text(d.dcost);
				$('#tr_'+cat_id).fadeOut('slow',function(){
					$('#tr_'+cat_id).remove();
					if($("tr[id^='tr_']").length<1) {
						$('.cart_tbl').hide();
						$('#cart_bot').hide();
					}
				});
			}
		});
	});
	$('.cart_tbl input[class=colvo]').bind('keyup',function(e){
		var cat_id=$(this).attr('cat_id');
		var colvo=Math.abs(Math.ceil(parseInt($(this).val())))+'';
		if(colvo=='NaN') colvo=0;
		var price=$('#price_'+cat_id).html();
		$('#sum_'+cat_id).html((colvo*price)+'');
		$('#sum_'+cat_id).parent().fadeOut(20).fadeIn(20);
		var s=0;
		$("span[id^='sum_']").map(function(){
			s+=parseInt($(this).text());
		});
		$('#summa').text(s);
		$('#itog').text(s+parseInt($('#dcost').text()));
	});
	$('.cart_tbl input[class=colvo]').change(function(e){
		var colvo=$(this).val();
		var cat_id=$(this).attr('cat_id');
		var price=$('#price_'+cat_id).text();
		$.ajax({
			url: '/ajx/cart.html',type: 'GET', data: { act: 'change_amount', amount:colvo, cat_id: cat_id},
			success: function(d){
				if(d.amount!=colvo) msg('ОШИБКА. Не верное значение кол-ва товара. Исправляю на исходное значение');
				$('input[cat_id='+cat_id+']').val(d.amount);
				$('#sum_'+cat_id).text((d.amount*price)+'');
				$('#summa').text(d.summa);
				$('#itog').text(d.itog);
				$('#dcost').text(d.dcost);
			}
		});
	});
	
	$('#cart_show_form').click(function(){
		$(this).hide();
		$('.cart_form').fadeIn('slow');
	});
	
	$('#cart_send').click(function(){
		var m='';
		if($("#cart_frm input[name=name]").val().trim().length<4) m+='<li>Имя</li>';
		if($("#cart_frm input[name=city]").val().trim().length<6) m+='<li>Город</li>';
		if($("#cart_frm input[name=tel]").val().trim().length<7) m+='<li>Телефон</li>';
		if($("#cart_frm [name=addr]").val().trim().length<10) m+='<li>Адрес доставки</li>';
		if(m!='') msg('<p><b>Не заполнены следующие поля:</b> </p><ul>'+m+'</ul>');
		else{
			$.ajax({
				url: '/ajx/cart.html',type: 'POST', data: { act: 'send', f:$('#cart_frm').serialize()},
				success: function(d){
					if(d.fres) {
//						$('.sf').slideUp('slow');
						$('#cart_form1').html(d.html);
						$('.cart_tbl input').attr('disabled','disabled');
						return false;
					}else msg(d.err_msg);
				}
			});
		}
		return false;
	});
});


