/*
 * skyscript.ru  skystudio.ru
 */

function tolkoCif(input) { 
    input.value = input.value.replace(/[^\d.]/g, '');
};

function showlayer(layer){
	var myLayer=document.getElementById(layer);
	if(myLayer.style.display=="none" || myLayer.style.display==""){
		myLayer.style.display="block";
	} else { 
		myLayer.style.display="none";
		}
}
function inputBG( obj, on )
 {
	if(on) obj.className='bginp1';
	 else if( !obj.value ) obj.className='bginp2';
 }

$(document).ready(function() { 

$("a.gallery").fancybox();
 
//показ подкатегорий

$('img[id*=otPodcat]').click(function(){
if($(this).attr('otkr')==0) { 
$('#Podcat'+$(this).attr('cat')).removeClass(); $(this).attr({'otkr':1,'src':'pic/cat-dt.gif'}); 
$.cookie('Podcat'+$(this).attr('cat'),1);
}
else { 
$('#Podcat'+$(this).attr('cat')).addClass('nevid'); $(this).attr({'otkr':0,'src':'pic/cat-cl.gif'}); 
$.cookie('Podcat'+$(this).attr('cat'), null);
}

	});


//вход в систему
$('a[id*=vhod]').click(function(e){
	
	e.preventDefault();
	$('#oknozab').dialog("close");
	$('#oknoreg').dialog("close");
		$('#oknovhod').dialog({
		height: 280,
		width: 300,
		modal: true,
		resizable: false,
		title: 'Вход в систему'
		});
	
	});
//отправить новый пароль
$('a[id*=zabPar]').click(function(e){
	e.preventDefault();
	$('#oknovhod').dialog("close");
	$('#oknoreg').dialog("close");
		$('#oknozab').dialog({
		width: 300,
		modal: true,
		resizable: false,
		title: 'Восстановить пароль'
		});
	
	});
//регистрация
$('a[id*=reg]').click(function(e){
	e.preventDefault();
	$('#oknovhod').dialog("close");
	$('#oknozab').dialog("close");
		$('#oknoreg').dialog({
		height: 440,
		width: 300,
		modal: true,
		resizable: false,
		title: 'Регистрация'
		});
	
	});



// Отправка данных о входе на сервер
$('#knVhod').click(function(e){
	
	var otprDan = {}; 
	e.preventDefault();
	
    otprDan.user_email = $('#poleEmail').val(); 
    otprDan.user_pass = $('#polePass').val();
	otprDan.a = 'login';
	
  $.post("d.php", otprDan, function(data){
			if(data)
            {   
			data = $.parseJSON(data); // Преобразовываем пришедшую строку JSON в объект JS 
                
	// Теперь в цикле пройдемся по всем ошибкам
			  var errors =''; 
			  $.each(data, function(i, val) {
			  errors += val+'\n';
	// alert(i); 
                  /* В i на каждой итерации цикла содержится имя поля, 
		в котором возникла ошибка, расскоментируйте alert() выше
                   и отправьте комментарий, заведомо содержащий ошибку.
                   Подумайте, как это можно использовать. */
                });
				$('#oshEmail').html('<div class="kr textsred al">' + errors + '</div>');  
				//alert(errors);                 
                        
            }
           else 
		   {
			   $('#oknovhod').dialog("close");
			   open($('#knVhod').attr('ssilka'),'_parent');
			   //open('skycat.php?mod=lich','_parent');
		   }
                          
          }
     );
  
});


// Отправить новый пароль
$('#knZab').click(function(e){
	var otprDan = {}; 
	e.preventDefault();
    otprDan.user_email = $('#poleEmailZab').val(); 
	otprDan.a = 'zab'; 
	
  $.post("d.php", otprDan, function(data){
			if(data)
            {   
			data = $.parseJSON(data); 

			  var errors =''; 
			  
			  $.each(data, function(i, val) {
			  errors += val+'\n';
                });
				$('#oshZab').html('<div class="ser textsred al">' + errors + '</div>');                   
            }
           else 
		   {
			$('#oknozab').dialog("close");
			$('#oshEmail').html('<div class="ser textsred ok">Вам на почтовый ящик был отправлен новый пароль</div>');
			$('#oknovhod').dialog("open");
		   }
                          
          }
     );
  
});

//кнопка прочитано
$('#sog').click(function(){

	if ($('#sog').attr('checked') == true) 
	{ $('#knReg').removeClass('ui-button-disabled').removeClass('ui-state-disabled').removeAttr('disabled').hover(function(){
		$(this).addClass('ui-state-hover');
		},function(){
			$(this).removeClass('ui-state-hover');
			}); 
	
	// Регистрация
	$('#knReg').click(function(e){
			e.preventDefault();
			var otprDan = {}; 
		
			otprDan.user_login = $('#poleNameReg').val();
			otprDan.user_email = $('#poleEmailReg').val();
			otprDan.user_pass = $('#polePassReg').val();
			otprDan.user_pass2 = $('#polePass2Reg').val();
			otprDan.a = 'reg'; 
			$.post("d.php", otprDan, function(data){
				  if(data)
				  {   
				  data = $.parseJSON(data); 
		
					var errors =''; 
					
					$.each(data, function(i, val) {
					errors += val+'\n';
					  });
					  $('#oshReg').html('<div class="kr textsred al">' + errors + '</div>');                   
				  }
				 else 
				 {
				//	 alert('удачно');
				$('#oknoreg').dialog("close");
			  	open($('#knVhod').attr('ssilka'),'_parent');
				 }
 
				
			});
		});
	
	}
	else 
	{ $('#knReg').addClass('ui-button-disabled').addClass('ui-state-disabled').attr('disabled','disabled'); }
	
	});





// корзина
		msg = new Array();
		var korzina = '';
		var vsegoCena = 0;
		var vsegoTov = 0;
		if (!$.cookie("korzina")) {$.cookie("korzina", '', {path: "/"});}
		korzina = decodeURI($.cookie("korzina"));
		korzinaArray = korzina.split(",");// Находим все товары
		for(var i=0; i<korzinaArray.length-1;i++) {
			tovId = korzinaArray[i].split(":"); // Находим id товара, цену и количество
			vsegoTov+=parseInt(tovId[1]);
			vsegoCena+=parseInt(tovId[1])*(tovId[2]);
		}
		if (vsegoCena > 0) {
			$('#ochKorz').show();
			$('#oformit').show();
			$('.korzPoln').show();
			$('.korzPust').hide();
			$('#korzPustPic').hide();
			
		}
		if (!vsegoCena) {vsegoCena = 0;}
		$('#totalPrice').text(vsegoCena.toFixed(2));
		$('#totalGoods').text(vsegoTov);
		
		
$('a.dobKorz').click(function() {
   d = $(this).attr('id').split('-');
   dobKorz(d[0], d[1], 1);
   return false;
  });
	
	
	function dobKorz(p1, p2, p3){
    if (!p3 || p3==0) {p3=1;}
    msg.id = p1; 
    msg.cena = p2;
    msg.kolich = parseInt(p3);
    var check = false;
    var cnt = false;
    var vsegoTov = 0;
    var vsegoCena = 0;
    var tovId = 0;
    var korzina = '';
    $('#ochKorz').show();
    $('#oformit').show();
	$('#korzPustPic').hide();
    $('.korzPoln').show();
    $('.korzPust').hide();
    korzina = decodeURI($.cookie("korzina"));
    if (korzina=='null') {korzina = '';}
    korzinaArray = korzina.split(",");
    for(var i=0; i<korzinaArray.length-1;i++) {
        tovId = korzinaArray[i].split(":");
	if(tovId[0]==msg.id)	// ищем, не покупали ли мы этот товар ранее
	{
        check = true;
	    cnt   = parseInt(tovId[1]);
		korzina=korzina.replace(msg.id+':'+(cnt)+':'+msg.cena, msg.id+':'+(cnt+1)+':'+msg.cena);
		$.cookie("korzina", korzina, {path: "/"});
	    break;
	}
    }
    if(!check) {
        korzina+= msg.id + ':' + msg.kolich + ':' + msg.cena + ',';
    } 
		else{
		korzina = decodeURI($.cookie("korzina"));

		}
		
	    korzinaArray = korzina.split(",");// Находим все товары
        for(var i=0; i<korzinaArray.length-1;i++) {
	    tovId = korzinaArray[i].split(":"); // Находим id товара, цену и количество
	    vsegoTov+=parseInt(tovId[1]);
	    vsegoCena+=parseInt(tovId[1])*(tovId[2]);
			}	
			
	$('#totalGoods').text(vsegoTov);
	$('#totalPrice').text(vsegoCena.toFixed(2));
	$.cookie("totalPrice", vsegoCena, {path: "/"});
	$.cookie("korzina", korzina, {path: "/"});
    
}



	function redKolTov(p1, p2){
	if (!p2 || p2==0) {p2=1;}
    msg.id = p1; 
    msg.red = p2;
    var cnt = false;
    var vsegoTov = 0;
    var vsegoCena = 0;
    var tovId = 0;
    var korzina = '';
    korzina = decodeURI($.cookie("korzina"));
    korzinaArray = korzina.split(",");
    for(var i=0; i<korzinaArray.length-1;i++) {
        tovId = korzinaArray[i].split(":");
		if(tovId[0]==msg.id)	// какой товар меняем
		{
			cnt   = parseInt(tovId[1]);
			if(msg.red=='bol'){ $('#mestoKolTov'+msg.id).val(cnt+1);
			korzina=korzina.replace(msg.id+':'+(cnt)+':'+tovId[2], msg.id+':'+(cnt+1)+':'+tovId[2]); }
			else if(msg.red=='men') { 
			if (cnt>1){	$('#mestoKolTov'+msg.id).val(cnt-1); korzina=korzina.replace(msg.id+':'+(cnt)+':'+tovId[2], msg.id+':'+(cnt-1)+':'+tovId[2]); }
				}
			else if(msg.red=='ud') { 
			$('#strokTov'+msg.id).addClass('nevid'); 
			korzina=korzina.replace(msg.id+':'+(cnt)+':'+tovId[2]+',', ''); 
				}	
			else { $('#mestoKolTov'+msg.id).val(msg.red);
			korzina=korzina.replace(msg.id+':'+(cnt)+':'+tovId[2], msg.id+':'+(msg.red)+':'+tovId[2]); }
			
			
			$.cookie("korzina", korzina, {path: "/"});
			break;
		}
    }
				if (!korzina) { 
				$('#tblTov').html('<tr><td>корзина пуста</td></tr>');	
				$('#tblKorz').hide();
				$('#totalPrice').text('0');
				$('#totalGoods').text('0');
				$('.korzPoln').hide();
				$('.korzPust').show();
				$('#oformit').hide();
				$('#korzPustPic').show();
				$.cookie("totalPrice", '', {path: "/"});
				$.cookie("korzina", '', {path: "/"}); 
				}
	    korzinaArray = korzina.split(",");// Находим все товары
        for(var i=0; i<korzinaArray.length-1;i++) {
	    tovId = korzinaArray[i].split(":"); // Находим id товара, цену и количество
	    vsegoTov+=parseInt(tovId[1]);
	    vsegoCena+=parseInt(tovId[1])*(tovId[2]);
			}	
			
	$('#totalGoods').text(vsegoTov);
	$('#totalPrice').text(vsegoCena.toFixed(2));
	$('#totalPriceKorz').text(vsegoCena.toFixed(2));
	$.cookie("totalPrice", vsegoCena, {path: "/"});
	$.cookie("korzina", korzina, {path: "/"});
    
}







$('#ochKorz').click(function() {
	$(this).hide();
	$('#totalPrice').text('0');
	$('#totalGoods').text('0');
	$('.korzPoln').hide();
	$('.korzPust').show();
	$('#oformit').hide();
	$('#korzPustPic').show();
	$('#tblKorz').hide();
	$('#tblTov').html('<tr><td>корзина пуста</td></tr>');
	$.cookie("totalPrice", '', {path: "/"});
	$.cookie("korzina", '', {path: "/"});
	return false;
});
	
	
$('img[id*=menTov]').click(function(){
	redKolTov($(this).attr('tov'), 'men');
	return false;
	
	});	
	
$('img[id*=bolTov]').click(function(){
	redKolTov($(this).attr('tov'), 'bol');
	return false;
	
	});		
	
$('input[id*=mestoKolTov]').keyup(function(){
	redKolTov($(this).attr('tov'), $(this).val());
	return false;
	
	});	
	
$('img[id*=udTov]').click(function(){
	redKolTov($(this).attr('tov'), 'ud');
	return false;
	
	});	
	



// Отправка заказа
$('#knZak').click(function(e){

	var otprDan = {}; 
	e.preventDefault();
	
	otprDan.user_reg = $('#pole_reg_user').text();
	otprDan.user_login = $('#pole_user_login').val(); 
	otprDan.user_tel = $('#pole_user_tel').val(); 
	otprDan.user_fax = $('#pole_user_fax').val(); 
	otprDan.user_email = $('#pole_user_email').val(); 
	otprDan.user_gorod = $('#pole_user_gorod').val(); 
	otprDan.user_obl = $('#pole_user_obl').val(); 
    otprDan.zak_prim = $('#pole_zak_prim').val(); 
	otprDan.a = 'ofzak';
	
  $.post("d.php", otprDan, function(data){
			if(data)
            {   
			data = $.parseJSON(data); 
			  var errors =''; 
			  $.each(data, function(i, val) {
			  errors += val+'\n';
	// alert(i); 
                });
				$('#oshZak').html('<div class="kr textsred al">' + errors + '</div>');  
           }
           else 
		   {
			   $('#oknovhod').dialog("close");
			   alert('Ваш заказ успешно отправлен.');
			   open('skycat.php','_parent');
			   //open('skycat.php?mod=lich','_parent');
		   }
                          
          }
     );
  
});


//таблицы
//$('.vib:even').css('background-color','#f2f2f2');


//вкладки пользователя
$(function() {
		$( "#tabs" ).tabs({
			cookie: {
				// store cookie for a day, without, it would be a session cookie
				expires: 1
			}
		});
	});


//изменение статуса заказа
$('select[id*=selZak]').change(function(e){
	var otprDan = {}; 
	e.preventDefault();
	otprDan.zak_id = $(this).attr('zak');
	otprDan.zak_stat = $(this).val();
	otprDan.a = 'smstat';
	$.post("d.php", otprDan);
	vrem=new Date();
	vremDate=vrem.getDate();
	if (vremDate<10) { vremDate='0'+vremDate; }
	vremMonth=vrem.getMonth();
	vremMonth+=1;
	if (vremMonth<10) { vremMonth='0'+vremMonth; }
	vremYear=vrem.getFullYear();
	//if 
	$('#vremStatRed'+$(this).attr('zak')).text(vremDate+'.'+vremMonth+'.'+vremYear);
	});

//Доп инфо пользователей
$('a[id*=dopInfo]').click(function(e){
	e.preventDefault();
	$('div[id*=dopInfoUser]').hide();
	$('#dopInfoUser'+$(this).attr('user')).show();
	});	
	
//отправить письмо пользователю
$('a[id*=otprPismoUser]').click(function(e) {
e.preventDefault();
var id = $(this).attr('href');	
var maskHeight = $(document).height();
var maskWidth = $(window).width();
$('#mask').css({'width':maskWidth,'height':maskHeight});
$('#mask').fadeIn(1000);
var winH = $(window).height();
var winW = $(window).width();
$('#poleLoginUser').text($(this).attr('title'));
$('#poleEmailUser').val($(this).text());
$(id).css('top', winH/2-$(id).height()/2);
$(id).css('left', winW/2-$(id).width()/2);
$(id).fadeIn(1000);
});	

//редактировать статус
$('#knStatRed').click(function(e) {
e.preventDefault();
var id = $(this).attr('href');	
var maskHeight = $(document).height();
var maskWidth = $(window).width();
$('#mask').css({'width':maskWidth,'height':maskHeight});
$('#mask').fadeIn(1000);
var winH = $(window).height();
var winW = $(window).width();
$('#poleStatNazv').val($('#poleStat :selected').text());
$('#poleStatId').val($('#poleStat').val());
$(id).css('top', winH/2-$(id).height()/2);
$(id).css('left', winW/2-$(id).width()/2);
$(id).fadeIn(1000);
});	

//удалить статус
$('#poleStat').change(function(){
	$('#poleUdStat').val($('#poleStat').val());
	});	


//стили для кнопок
$(function() {
	//	$("button, input:submit, input:reset", ".kn").button();
	//	$(".knop").button();
	//	$( "a", ".demo" ).click(function() { return false; });
});	
	
	
//новое издательство
$('#nov_izd').click(function(){
	$('#pole_nov_tov_izd').show(300);
	
	});	
	
	
	
	
	
	
}); //завершение

(function($){
	/* hoverIntent by Brian Cherne */
	$.fn.hoverIntent = function(f,g) {
		// default configuration options
		var cfg = {
			sensitivity: 7,
			interval: 100,
			timeout: 0
		};
		// override configuration options with user supplied object
		cfg = $.extend(cfg, g ? { over: f, out: g } : f );

		// instantiate variables
		// cX, cY = current X and Y position of mouse, updated by mousemove event
		// pX, pY = previous X and Y position of mouse, set by mouseover and polling interval
		var cX, cY, pX, pY;

		// A private function for getting mouse position
		var track = function(ev) {
			cX = ev.pageX;
			cY = ev.pageY;
		};

		// A private function for comparing current and previous mouse position
		var compare = function(ev,ob) {
			ob.hoverIntent_t = clearTimeout(ob.hoverIntent_t);
			// compare mouse positions to see if they've crossed the threshold
			if ( ( Math.abs(pX-cX) + Math.abs(pY-cY) ) < cfg.sensitivity ) {
				$(ob).unbind("mousemove",track);
				// set hoverIntent state to true (so mouseOut can be called)
				ob.hoverIntent_s = 1;
				return cfg.over.apply(ob,[ev]);
			} else {
				// set previous coordinates for next time
				pX = cX; pY = cY;
				// use self-calling timeout, guarantees intervals are spaced out properly (avoids JavaScript timer bugs)
				ob.hoverIntent_t = setTimeout( function(){compare(ev, ob);} , cfg.interval );
			}
		};

		// A private function for delaying the mouseOut function
		var delay = function(ev,ob) {
			ob.hoverIntent_t = clearTimeout(ob.hoverIntent_t);
			ob.hoverIntent_s = 0;
			return cfg.out.apply(ob,[ev]);
		};

		// A private function for handling mouse 'hovering'
		var handleHover = function(e) {
			// next three lines copied from jQuery.hover, ignore children onMouseOver/onMouseOut
			var p = (e.type == "mouseover" ? e.fromElement : e.toElement) || e.relatedTarget;
			while ( p && p != this ) { try { p = p.parentNode; } catch(e) { p = this; } }
			if ( p == this ) { return false; }

			// copy objects to be passed into t (required for event object to be passed in IE)
			var ev = jQuery.extend({},e);
			var ob = this;

			// cancel hoverIntent timer if it exists
			if (ob.hoverIntent_t) { ob.hoverIntent_t = clearTimeout(ob.hoverIntent_t); }

			// else e.type == "onmouseover"
			if (e.type == "mouseover") {
				// set "previous" X and Y position based on initial entry point
				pX = ev.pageX; pY = ev.pageY;
				// update "current" X and Y position based on mousemove
				$(ob).bind("mousemove",track);
				// start polling interval (self-calling timeout) to compare mouse coordinates over time
				if (ob.hoverIntent_s != 1) { ob.hoverIntent_t = setTimeout( function(){compare(ev,ob);} , cfg.interval );}

			// else e.type == "onmouseout"
			} else {
				// unbind expensive mousemove event
				$(ob).unbind("mousemove",track);
				// if hoverIntent state is true, then call the mouseOut function after the specified delay
				if (ob.hoverIntent_s == 1) { ob.hoverIntent_t = setTimeout( function(){delay(ev,ob);} , cfg.timeout );}
			}
		};

		// bind the function to the two event listeners
		return this.mouseover(handleHover).mouseout(handleHover);
	};
	
})(jQuery);



;(function($){
	$.fn.superfish = function(op){

		var sf = $.fn.superfish,
			c = sf.c,
			$arrow = $([''].join('')),
			over = function(){
				var $$ = $(this), menu = getMenu($$);
				clearTimeout(menu.sfTimer);
				$$.showSuperfishUl().siblings().hideSuperfishUl();
			},
			out = function(){
				var $$ = $(this), menu = getMenu($$), o = sf.op;
				clearTimeout(menu.sfTimer);
				menu.sfTimer=setTimeout(function(){
					o.retainPath=($.inArray($$[0],o.$path)>-1);
					$$.hideSuperfishUl();
					if (o.$path.length && $$.parents(['li.',o.hoverClass].join('')).length<1){over.call(o.$path);}
				},o.delay);	
			},
			getMenu = function($menu){
				var menu = $menu.parents(['ul.',c.menuClass,':first'].join(''))[0];
				sf.op = sf.o[menu.serial];
				return menu;
			},
			addArrow = function($a){ $a.addClass(c.anchorClass).append($arrow.clone()); };
			
		return this.each(function() {
			var s = this.serial = sf.o.length;
			var o = $.extend({},sf.defaults,op);
			o.$path = $('li.'+o.pathClass,this).slice(0,o.pathLevels).each(function(){
				$(this).addClass([o.hoverClass,c.bcClass].join(' '))
					.filter('li:has(ul)').removeClass(o.pathClass);
			});
			sf.o[s] = sf.op = o;
			
			$('li:has(ul)',this)[($.fn.hoverIntent && !o.disableHI) ? 'hoverIntent' : 'hover'](over,out).each(function() {
				if (o.autoArrows) addArrow( $('>a:first-child',this) );
			})
			.not('.'+c.bcClass)
				.hideSuperfishUl();
			
			var $a = $('a',this);
			$a.each(function(i){
				var $li = $a.eq(i).parents('li');
				$a.eq(i).focus(function(){over.call($li);}).blur(function(){out.call($li);});
			});
			o.onInit.call(this);
			
		}).each(function() {
			var menuClasses = [c.menuClass];
			if (sf.op.dropShadows  && !($.browser.msie && $.browser.version < 7)) menuClasses.push(c.shadowClass);
			$(this).addClass(menuClasses.join(' '));
		});
	};

	var sf = $.fn.superfish;
	sf.o = [];
	sf.op = {};
	sf.IE7fix = function(){
		var o = sf.op;
		if ($.browser.msie && $.browser.version > 6 && o.dropShadows && o.animation.opacity!=undefined)
			this.toggleClass(sf.c.shadowClass+'-off');
		};
	sf.c = {
		bcClass     : 'sf-breadcrumb',
		menuClass   : 'sf-js-enabled',
		anchorClass : 'sf-with-ul',
		arrowClass  : 'sf-sub-indicator',
		shadowClass : 'podmenu_ten'
	};
	sf.defaults = {
		hoverClass	: 'sfHover',
		pathClass	: 'overideThisToUse',
		pathLevels	: 1,
		delay		: 800,
		animation	: {opacity:'show'},
		speed		: 'normal',
		autoArrows	: true,
		dropShadows : true,
		disableHI	: false,		// true disables hoverIntent detection
		onInit		: function(){}, // callback functions
		onBeforeShow: function(){},
		onShow		: function(){},
		onHide		: function(){}
	};
	$.fn.extend({
		hideSuperfishUl : function(){
			var o = sf.op,
				not = (o.retainPath===true) ? o.$path : '';
			o.retainPath = false;
			var $ul = $(['li.',o.hoverClass].join(''),this).add(this).not(not).removeClass(o.hoverClass)
					.find('>ul').hide().css('visibility','hidden');
			o.onHide.call($ul);
			return this;
		},
		showSuperfishUl : function(){
			var o = sf.op,
				sh = sf.c.shadowClass+'-off',
				$ul = this.addClass(o.hoverClass)
					.find('>ul:hidden').css('visibility','visible');
			sf.IE7fix.call($ul);
			o.onBeforeShow.call($ul);
			$ul.animate(o.animation,o.speed,function(){ sf.IE7fix.call($ul); o.onShow.call($ul); });
			return this;
		}
	});

})(jQuery);

	jQuery(function(){
			jQuery('ul.podmenu').superfish();
		});
