// JavaScript Document
function linzShop() {
	el=this;
	$('.zakaz').click(function(){ el.addZakaz(this.id); return false; }); // кнопка заказать
	$('.rast-select').change(function(){ el.changeRastPrice(this); }); // список объемов растворов
	$('.rad-select').change(function(){ el.changeOptSila(this); el.validLinzForm(this); }); // список радиусов кривизны линз
	$('.opt-select, .count-select, .color-select, .os-select, .cil-select').change(function(){ el.validLinzForm(this); }); // проверка на заполнение полей
	$('.corz-sel').change(function(){ el.changeTovarCount(this); }); // список кол-ва заказанных ед в корзине
	$('.delete-zak').click(function(){ el.deleteTovar(this.id); return false; }); // удаление заказа
	$('#zak-end').click(function(){$('#zak-form').show(); return false;}); // переход к оформлению заказа
	$('#shop-us').css({ cursor:'pointer' }).click(function(){ document.location='/box/' }); // ссылка на диве с корзиной
	$('.sop-count-sel').change(function(){ el.changeCount(this.id); });
	$divShad=jQuery('<div></div>'); // настройки всплывающего слоя
  	$divShad.css({ background:'#000000', opacity:'0.8', position:'absolute', top:'0', left:'0', zIndex:'1000', width:'100%' }).hide();
  	$ShadCont=jQuery('<div></div>');
  	$ShadCont.css({ position:'absolute', background:'#fff', zIndex:'1001', padding:'15px', overflow:'hidden' }).attr('id','contShad').hide();
	$loading=jQuery('<div></div>');
	$loading.css({ position:'absolute', zIndex:'1001', background:'#fff', padding:'5px', border:'1px solid #ccc', display:'none' }).html('Loading...').hide();
	jQuery('body').append($divShad).append($ShadCont).append($loading);
	this.isLinz=0;
}

// цена растворов в зависимости от объема
linzShop.prototype.changeRastPrice=function(rast_select) {
	if (rast_select.value!='') $('#one-price-'+rast_select.id.substr(5)).html(rast_price[rast_select.value]);
	else $('#one-price-'+rast_select.id.substr(5)).html(' ');
	this.changeCount('cou-'+rast_select.id.substr(5));
}

// оптическая сила в зависимости от радиуса кривизны
linzShop.prototype.changeOptSila=function(rad_select) {
	if (rad_select.value!='') {
		sid=rad_select.id.substr(4);
		$('#opt-'+sid).html(lins_sila[rad_select.value]['sil']);
		
		if (typeof(lins_sila[rad_select.value]['col'])!="undefined") { $('#p-color-'+sid).show(); $('#col-'+sid).html(lins_sila[rad_select.value]['col']); }
		else $('#p-color-'+sid).hide();
		
		if (typeof(lins_sila[rad_select.value]['os'])!="undefined")  { $('#p-os-'+sid).show(); $('#oss-'+sid).html(lins_sila[rad_select.value]['os']); }
		else $('#p-os-'+sid).hide();
		
		if (typeof(lins_sila[rad_select.value]['cil'])!="undefined")  { $('#p-cil-'+sid).show(); $('#cil-'+sid).html(lins_sila[rad_select.value]['cil']); }
		else $('#p-cil-'+sid).hide();
	}
	else $('#opt-'+rad_select.id.substr(4)).html(lins_sila['sel']);
	if (sid.substr(0,1)=='l') { $('.linz-l').css({ height:'auto' }); $('.linz-r').css({ height:$('.linz-l').height() }); }
	else { $('.linz-r').css({ height:'auto' }); $('.linz-l').css({ height:$('.linz-r').height() }); }
}

// проверка на заполненость полей хотя бы для одной линзы при заказе
linzShop.prototype.validLinzForm=function(isselect) {
	sid=isselect.id.substr(5);
	isLeft=this.testLinzForm(sid,'l');
	isRight=this.testLinzForm(sid,'r');
	if (isLeft || isRight) $('#linz-'+sid).attr('disabled',0);
	else $('#linz-'+sid).attr('disabled',1);
}

linzShop.prototype.testLinzForm=function(sid,col) {
	this.isLinz=0;
	if ($('#opt-'+col+sid).val()!='' && $('#rad-'+col+sid).val()!='' && $('#cou-'+col+sid).val()!='') this.isLinz=1;
	if($('#p-color-'+col+sid).css('display')!='none' && $('#col-'+col+sid).val()=='') this.isLinz=0;
	if($('#p-os-'+col+sid).css('display')!='none' && $('#oss-'+col+sid).val()=='') this.isLinz=0;
	if($('#p-cil-'+col+sid).css('display')!='none' && $('#cil-'+col+sid).val()=='') this.isLinz=0;
	
	tot_price=0;
	
	if (this.isLinz) tot_price=linz_price*$('#cou-'+col+sid).val();
	$('#price-'+col+sid).html(''+tot_price+'');
	$('#linz-tot-price').html(''+(Number($('#price-l'+sid).html())+Number($('#price-r'+sid).html()))+'');
	//alert(tot_price);
	
	return this.isLinz;
}

linzShop.prototype.changeCount=function(sel) {
	$('#itogg-'+sel.substr(4)).html(Number($('#one-price-'+sel.substr(4)).html())*Number($('#'+sel).val()));
}

// добавление заказа в корзину в зависимости от типа товара
linzShop.prototype.addZakaz=function(click_id) {
	this.openShadow();
	this.showLoading(); // показываем надпись о загрузке
	sid=click_id.split("-");
	this.lastId=sid[1];
	el=this;
	if (sid[0]=='othe') $.get('/sys/zakaz/',{tem:'7',cat:'other',tov:sid[1],count:$('#cou-'+sid[1]).val()},function(data){el.addZakazComplete(data,1)});
	if (sid[0]=='rasv') $.get('/sys/zakaz/',{tem:'7',cat:'rast',tov:sid[1],obem:$('#rast-'+sid[1]).val(),count:$('#cou-'+sid[1]).val()},function(data){el.addZakazComplete(data,1)});
	if (sid[0]=='linz') {
		linz_param={ tem:'7',cat:'linz',tov:sid[1] };
		if (this.testLinzForm(sid,'l')) {
			linz_param['radl']=$('#rad-l'+sid[1]).val();
			linz_param['optl']=$('#opt-l'+sid[1]).val();
			linz_param['countl']=$('#cou-l'+sid[1]).val();
			if($('#p-color-l'+sid[1]).css('display')!='none') linz_param['colorl']=$('#col-l'+sid[1]).val();
			if($('#p-os-l'+sid[1]).css('display')!='none') linz_param['osl']=$('#oss-l'+sid[1]).val();
			if($('#p-cil-l'+sid[1]).css('display')!='none') linz_param['cill']=$('#cil-l'+sid[1]).val();
		}
		if (this.testLinzForm(sid,'r')) {
			linz_param['radr']=$('#rad-r'+sid[1]).val();
			linz_param['optr']=$('#opt-r'+sid[1]).val();
			linz_param['countr']=$('#cou-r'+sid[1]).val();
			if($('#p-color-r'+sid[1]).css('display')!='none') linz_param['colorr']=$('#col-r'+sid[1]).val();
			if($('#p-os-r'+sid[1]).css('display')!='none') linz_param['osr']=$('#oss-r'+sid[1]).val();
			if($('#p-cil-r'+sid[1]).css('display')!='none') linz_param['cilr']=$('#cil-r'+sid[1]).val();
		}
		$.get('/sys/zakaz/',linz_param,function(data){ el.addZakazComplete(data,1)});
	}
}

// показываем изменения в корзине + надпись о добавлении товара
linzShop.prototype.addZakazComplete=function(data,flag) {
    $('#shop-us').html(data);
	if (flag==1) this.printMessage('<img src="/img/box.jpg" alt=""> <span style="position:relative; left:15px; top:-10px;">Товар "'+$('#name-'+this.lastId).html()+'" добавлен в корзину</span> <br><br> <input type="button" value="перейти к оформлению заказа" onClick="document.location=\'/box/\'" style="width:230px;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input type="button" value="продолжить выбор товара" onClick="LinzShop.closeMessage()" style="width:230px;">');
}

// изменение кол-ва ед товара
linzShop.prototype.changeTovarCount=function(count) {
	sid=count.id.substr(3);
	new_tot_price=Number(count.value)*Number($('#price'+sid).html());
	if(new_tot_price) $('#totprice'+sid).html(new_tot_price);
	else $('#totprice'+sid).html('0');
	$.get('/sys/zakaz/',{tem:'7',zak_id:sid,count:count.value,cat:'update'},function(data){el.addZakazComplete(data); $('#itog-price').html($('#korz-price').html()); });
}

// удаление товара из корзины
linzShop.prototype.deleteTovar=function(del) {
	tov_name = $('#name-'+del.substr(3)).html();
	tov_br=tov_name.split("<br>");
	count_br=tov_br.length; 
	sid=del.substr(3);
	this.openShadow();
	$ShadCont.css({ width:'400px' });
	this.printMessage('<img src="/img/box.jpg" alt="" style="float:left; margin-right:10px;'+(count_br<3?"":"margin-top:10px;")+'"> <span>Вы действительно хотите удалить товар <br> "'+tov_name+'" ?</span> <br><br> <div style="text-align:center"> <input type="button" value="ok" onClick="LinzShop.deleteTovarConfirm(\'\'+sid+\'\')" style="width:100px;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input type="button" value="отмена" onClick="LinzShop.closeMessage()" style="width:100px;"></div>');
}

linzShop.prototype.deleteTovarConfirm=function(del) {
	$.get('/sys/zakaz/',{tem:'7',zak_id:del,cat:'delete'},function(data){el.addZakazComplete(data); document.location.reload(); });
}

// показываем надпись о загрузке
linzShop.prototype.showLoading=function() {
	coords=this.getPage();
	$loading.css({ left:(jQuery(document).width()-$loading.width())/2+'px', top:coords[2]+(coords[0]-$loading.height())/2+'px' }).show();
}

// выводим сообщение в слое
linzShop.prototype.printMessage=function(data) {
	coords=this.getPage();
	$ShadCont.html(data);
   	hei=$ShadCont.height();
	marg=coords[2]+(coords[0]-hei)/2;
    if (hei>=coords[0]) marg=coords[2];
    if ((hei+marg)>=coords[1]) $divShad.css({ height:hei+marg+50+'px' });
	$loading.hide();
   	$ShadCont.css({ left:(jQuery(document).width()-$ShadCont.width())/2+'px', top:marg }).show();
	el=this;
	$divShad.click(function(){el.closeMessage()});
}

// закрываем слой с сообщением
linzShop.prototype.closeMessage=function() {
	$ShadCont.hide();
	$divShad.hide();
	sel=document.getElementsByTagName('select');
	sel_count=sel.length;
	for (i=0;i<sel_count;i++) {
		sel[i].style.visibility = "visible";
	}
}

// закрываем слой с сообщением
linzShop.prototype.openShadow=function() {
	$divShad.css({ height:jQuery(document).height() }).show(); // показываем фоновый слой
	sel=document.getElementsByTagName('select');
	sel_count=sel.length;
	for (i=0;i<sel_count;i++) {
		sel[i].style.visibility = "hidden";
	}
}

// расчет координат экрана
linzShop.prototype.getPage=function () {
  var coords = [0, 0, 0]; // height of window, document, scroll pos
  // all except IE
  if (window.innerHeight) { coords[0] = window.innerHeight; coords[2] = window.pageYOffset; }
  // IE 6 Strict
  else if (document.documentElement && document.documentElement.clientHeight != 0) { coords[0] = document.documentElement.clientHeight; coords[2] = document.documentElement.scrollTop; }
  else if (document.body) { coords[0] = document.body.clientHeight; coords[2] = document.body.scrollTop; }
  var test1 = document.body.scrollHeight; 
  var test2 = document.body.offsetHeight;
  if (test1 > test2) { coords[1] = document.body.scrollHeight; }
  else { coords[1] = document.body.offsetHeight; }
  if (coords[1] < coords[0]) coords[1] = coords[0];
  return coords;
}

jQuery(document).ready(function() { LinzShop= new linzShop(); });
