// JavaScript Document
function linzShop() {
	var el=this;
	var cat=this;
	$('.item-zakaz').click(function(){ el.addZakaz(this.id); return false; }).css({ cursor:'pointer' }); // кнопка заказать
	$('.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;}); // переход к оформлению заказа
	$('#box').css({ cursor:'pointer' }).click(function(){ document.location='http://www.garantcom.ru/box/' }); // ссылка на диве с корзиной
	$('.sop-count-sel').change(function(){ el.changeCount(this.id); });
	$('.vol select').change(function(){ el.changeVolumPrice(this); }); // изменение цены в зависимости от объема
	$('.delme').click(function(){ el.adminDel(this.id); return false; });
	$('.loj').click(function(){ el.adminLoj(this.id); return false; });
	$('.tec').click(function(){ el.adminTec(this.id); return false; });
	$('.chstat').change(function(){ el.adminChngStat2(this.id); return false; });
	$('#enter-text, #gal-enter').click(el.openLoginDialog);
	$('#gal-enter2').click(function(){ document.location='http://www.garantcom.ru/private/' });
	$('#reg-email').click(function(){ cat.ClicOnField(this,'e-mail'); }).focusout(function(){ cat.ChangeField(this,'e-mail'); }).bind('keydown', 'return', function(){ document.loginform.submit(); });
	$('#reg-pass').click(function(){ cat.ClicOnField(this,'password'); }).focusout(function(){ cat.ChangeField(this,'password'); }).bind('keydown', 'return', function(){ document.loginform.submit(); });
	$('#f25').click(function(){if($(this).attr('checked')) { $('#persmanager').show(); } else { $('#persmanager').hide(); }});
	$divShad=jQuery('<div></div>'); // настройки всплывающего слоя
  	$divShad.css({ background:'#000000', opacity:'0.6', position:'absolute', top:'0', left:'0', zIndex:'1000', width:'100%' });
  	$ShadCont=jQuery('<div></div>');
  	$ShadCont.attr('id','contShad');
	$loading=jQuery('<div></div>');
	$logform=jQuery('<div></div>');
	$logform.attr('id','loginbg');
	$loading.css({ position:'absolute', zIndex:'1001', background:'#fff', padding:'5px', border:'1px solid #ccc', display:'none' }).html('Загрузка...');
	jQuery('body').append($divShad).append($ShadCont).append($loading).append($logform);
	$divShad.hide();
	$ShadCont.hide();
	$loading.hide();
	this.isLinz=0;
}

// добавление заказа в корзину в зависимости от типа товара
linzShop.prototype.addZakaz=function(click_id) {
	this.openShadow();
	this.showLoading(); // показываем надпись о загрузке
	sid=click_id.substr(3);
	this.lastSid=sid;
	el=this;
	$.get('/scripts/zakaz.php',{cat:'tov', tov:sid, count:1},function(data){el.addZakazComplete(data,1)});
}

// показываем изменения в корзине + надпись о добавлении товара
linzShop.prototype.addZakazComplete=function(data,flag) {
	eval(data);
	if(!document.getElementById('box')) {
		$('#keywords').html("<div id='box'><img src='/img/basket.png' alt=''> Корзина: <span id='box-text'></span></div>");
	}
	$('#box-text').html(korz_html);
	this.last_zak_id=zak_id;
	var el=this;
	if (flag==1) this.printMessage(tov_opis+'Укажите количество <input type="text" value="'+tov_count+'" style="width:50px;" id="closeCount"> <br clear="all"><br> <input type="button" value="перейти к оформлению заказа" onClick="el.changeCloseTovarCount(); document.location=\'http://www.garantcom.ru/box/\'" style="width:230px;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input type="button" value="продолжить выбор товара" onClick="el.changeCloseTovarCount(); el.closeMessage()" style="width:230px;">');
}

// изменение кол-ва ед товара
linzShop.prototype.changeCloseTovarCount=function() {
	var el=this;
	$.get('/scripts/zakaz.php',{zak_id:this.last_zak_id,count:$('#closeCount').val(),cat:'update'},function(data){ el.addZakazComplete(data); });
}

linzShop.prototype.refresh=function() {
	var upt=$('.count-zakaz').get();
	for(i=0;i<upt.length;i++) {
		$.get('/scripts/zakaz.php',{zak_id:upt[i].id.substr(6),count:upt[i].value,cat:'update'},function(data){});
	}
	document.location.reload();
}

// Подсчет стоимости товара с учетом скидки
linzShop.prototype.changeDiscontPrice=function() {
	if(document.getElementById('user-discont-per')) { // у пользователя есть накопительная скидка
		this.userDiscontPer=Number($('#user-discont-per').html());
		var totPrice=Number($('#itog-price').html());
		$('#itog-price-dicont').html(''+Math.ceil(totPrice-totPrice*this.userDiscontPer/100)+'');
	}
	this.setItogAfterBonus();
}

// Нажатие кнопки использовать бонус
linzShop.prototype.addBunusSum=function() {
	if(document.getElementById('hidden-bonus-itog').style.display=='none') {
		$('#hidden-bonus-itog').show();
		$('#form-usebonus').val('1');
		this.setItogAfterBonus();
	}
	else {
		$('#hidden-bonus-itog').hide();
		$('#form-usebonus').val('0');
	}
}

// подсчет стоимости товара с бонусом 
linzShop.prototype.setItogAfterBonus=function() {
	var itog_after_bonus=0;
	if(document.getElementById('user-discont-per')) itog_after_bonus=Number($('#itog-price-dicont').html());
	else itog_after_bonus=Number($('#itog-price').html());
	itog_after_bonus=itog_after_bonus-Number($('#user-bouns').html())
	if (itog_after_bonus<0) itog_after_bonus='0';
	$('#itog-after-bonus').html(itog_after_bonus);
}

// удаление товара из корзины
linzShop.prototype.deleteTovar=function(del) {
	var el=this;
	tov_name = $('#name-'+del.substr(3)).html();
	sid=del.substr(3);
	this.openShadow();
	this.showLoading();
	$.get('/scripts/zakaz.php',{show_info:sid},function(data){el.getInfoComplete(data)});
}

linzShop.prototype.getInfoComplete=function(data) {
	this.printMessage(''+data+'<br><b>Вы действительно хотите удалить этот товар из корзины?</b><br><br><input type="button" value="удалить" onClick="LinzShop.deleteTovarConfirm(\'\'+sid+\'\')" style="width:230px;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input type="button" value="продолжить оформление заказа" onClick="LinzShop.closeMessage()" style="width:230px;">');
}

linzShop.prototype.deleteTovarConfirm=function(del) {
	$.get('/scripts/zakaz.php',{zak_id:del,cat:'delete'},function(data){ document.location.reload(); });
}

linzShop.prototype.getLogForm=function() {
	this.openShadow();
	this.showLoading();
	var el=this;
	$.get('/system/private_login.php',{},function(data){el.getLogFormComplete(data)});
}

linzShop.prototype.getLogFormComplete=function(data) {
	$loading.hide();
	$logform.css({ left:(jQuery(document).width()-$logform.width())/2+'px', top:coords[2]+(coords[0]-$logform.height())/2+'px' }).html(data);
	if(data.indexOf("script")==-1) $logform.show();
	$('#logstart').click(function(){$logform.hide();$loading.show();$.get('/system/private_login.php',{log_form:1,login:$('#logemail').val(),pass:$('#logpass').val()},function(data){el.getLogFormComplete(data)});})
	$('#logclose').click(function(){ $logform.hide();el.closeMessage(); })
}

linzShop.prototype.adminDel=function(elem) {
	sid=elem.substr(4);
	this.openShadow();
	this.printMessage('<b>Вы действительно хотите удалить этот товар из заказа?</b><br><br><input type="button" value="удалить" onClick="LinzShop.deleteTovarConfirm(\'\'+sid+\'\')" style="width:230px;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input type="button" value="отмена" onClick="LinzShop.closeMessage()" style="width:230px;">');
}

linzShop.prototype.adminLoj=function(elem) {
	sid=elem.substr(4);
	this.openShadow();
	this.printMessage('<b>Вы действительно хотите переместить этот товар в лист ожидания?</b><br><br><input type="button" value="переместить" onClick="LinzShop.adminChngStat(\'\'+sid+\'\',2)" style="width:230px;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input type="button" value="отмена" onClick="LinzShop.closeMessage()" style="width:230px;">');
}

linzShop.prototype.adminTec=function(elem) {
	sid=elem.substr(4);
	this.openShadow();
	this.printMessage('<b>Вы действительно хотите переместить этот товар в текущие заказы?</b><br><br><input type="button" value="переместить" onClick="LinzShop.adminChngStat(\'\'+sid+\'\',1)" style="width:230px;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input type="button" value="отмена" onClick="LinzShop.closeMessage()" style="width:230px;">');
}

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

linzShop.prototype.adminChngStat2=function(elem) {
	sid=elem.substr(4);
	nstat=$('#'+elem).val();
	this.openShadow();
	this.printMessage('<b>Вы действительно хотите изменить статус этого заказа?</b><br><br><input type="button" value="изменить" onClick="LinzShop.adminChngStat2Confirm(\'\'+sid+\'\',\'\'+nstat+\'\')" style="width:230px;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input type="button" value="отмена" onClick="LinzShop.closeMessage()" style="width:230px;">');
}

linzShop.prototype.adminChngStat2Confirm=function(elem,nstat) {
	sid=elem.split("-");
	$.get('/sys/zakaz/',{tem:'7',zak_id:sid[1],ostat:sid[2],cat:'chngAll',nstat:nstat},function(data){ document.location.reload(); });
}

linzShop.prototype.openLoginDialog=function() {
	var el=this;
	if(typeof(this.openDialogFlag)=='undefined') {
		this.openDialogFlag=0;
		this.isOpenDialog=0;
	}
	if(this.openDialogFlag) return false;
	this.openDialogFlag=1;
	
	if(this.isOpenDialog) {
		this.isOpenDialog=0;
		$('#gal-enter').removeClass('enter-off').addClass('enter-on');
		$('#registr-cont').animate({height:'0px'},1000,function(){el.openDialogFlag=0});
	}
	else {
		this.isOpenDialog=1;
		$('#gal-enter').removeClass('enter-on').addClass('enter-off');
		$('#registr-cont').css({height:'0px'}).animate({height:'42px'},1000,function(){el.openDialogFlag=0});
	}
}

linzShop.prototype.ClicOnField=function(elem,text) {
	if(elem.value==text) {
		elem.value='';
		if(text=='password') elem.type='password';
	}
}

linzShop.prototype.ChangeField=function(elem,text) {
	if(elem.value=='') {
		elem.value=text;
		if(text=='password') elem.type='text';
	}
}

// показываем надпись о загрузке
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();
	$divShad.click(function(){ el.closeMessage(); $logform.hide(); });
}

// выводим сообщение в слое
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(); });
