$(document).ready(function(){
	var w = $(window);
	var selectActive = 0;
	var $dropshadow = null;
	var botMargin = 20;
	var golos = 0;

	// поднимаем открытые сесси консультанта
	scanOpenSessions();

	// запускаем баннеры в ротацию
	setInterval( "slideSwitch()", 5000 );

	// прототип функции максинга зиндекса
	$.fn.tagName = function() { 
		return this.get(0).tagName; 
	} 
	$.fn.maxZIndex = function(opt) {
		var def = { inc: 10, group: "*" };
		$.extend(def, opt);    
		var zmax = 0;
		$(def.group).each(function() {
			var cur = parseInt($(this).css('z-index'));
			zmax = cur > zmax ? cur : zmax;
		});
		if (!this.jquery)
			return zmax;

		return this.each(function() {
			zmax += def.inc;
			$(this).css("z-index", zmax);
		});
	}
	$.extend($.expr[':'], {  
		noid: function(a) {  
			return $(a).attr("id") == '';  
		}  
	}); 

	// фикс события наведения мышки на селект, расположенный внтури активного дива
	$(".catalog .seldiv").children().mouseout( function(e) {
		e.stopPropagation();
	});

	// закругляем баннерочки
	$(".banner").corner("round 15px");
	//$(".consult").corner("round 15px");

	// консультант 
	//$(".fast div").css( {backgroundPosition: "0 20px"} );
	//refreshIcons();

	$(".consult").mouseover( function(){
		$(this).css( {backgroundPosition: "0 46"} );
	}).mouseout( function(){
		$(this).css( {backgroundPosition: "0 0"} );
	});

	$(".voting li").mouseover( function(){
		$(this).css( 'background', '#fd9494' );
	}).mouseout( function(){
		$(this).css( 'background', '#fff' );
	});

	// catalog sub-popup
	$(".catalog").mouseover( function() {
		$(".drops").remove();
		$("#sub" + $(this).attr('sub') ).css('visibility','visible');
		var $dropshadow = $("#sub" + $(this).attr('sub') ).dropShadow({left: 2, top: 2, opacity: 1, blur: 0});
		$dropshadow.attr('class','drops');
	}).mouseout( function() {
		$(".drops").remove();
		$("#sub" + $(this).attr('sub')).css('visibility','hidden');
	});

	// поменять тип выдачи таблицы данных
	$("#viewtype").change( function() {
		$.get("/project/phpfiles/_ajax.php", { action: 'changetype', type: $(this+":selected").val()}, function(data) {
			window.location.reload();
		});
	});


	// links around image hover
	$(".ilink").mouseover( function() {
		$(this).css('border','1px solid #c52100');
	}).mouseout( function() {
		$(this).css('border','1px solid #fff');
	});
	$(".filter-logo").mouseover( function() {
		$(this).css('border','1px solid  #c52100');
	}).mouseout( function() {
		$(this).css('border','1px solid #dedfde');
	});

	// configurator scroll
	$.each( $(".vendor"), function() {
		var vid = $(this).attr('id').replace('vendor','');
		if( vid != vid_ ) {
			$("#vendor" + vid_).scrollTop(0);			
		}
		var div = $("#vendor" + vid);
		var ul = $("#vendor-move" + vid);
		var lastLi = ul.find('p:last-child');
		var divHeight = div.height();
		var ulPadding = 15;
		var ulHeight = lastLi[0].offsetTop + lastLi.outerHeight() + ulPadding;
		if( divHeight > ulHeight ) { // non scroll
			$("#scroll" + vid).css('display','none');
		}
	});
	var vid_ = -1;
	$(".vendor").mousemove( function(e) {
		var vid = $(this).attr('id').replace('vendor','');
		if( vid != vid_ ) {
			$("#vendor" + vid_).scrollTop(0);	
			$("#scroll" + vid_).css('top','110px');
			$("#scroll" + vid_ + " img").css('top', '0px');
		}
		var div = $("#vendor" + vid);
		var ul = $("#vendor-move" + vid);
		var lastLi = ul.find('p:last-child');
		var divHeight = div.height();
		var ulPadding = 15;
		var ulHeight = lastLi[0].offsetTop + lastLi.outerHeight() + ulPadding;
		var top = (e.pageY - div.offset().top) * (ulHeight-divHeight) / divHeight;
		$("#scroll" + vid).css('top',(110+top)+'px');
		$("#scroll" + vid + " img").css('top', (90/(ulHeight-divHeight)*top)+'px');
		div.scrollTop(top);
		vid_ = vid;
	});

	// catalog sub-popup
	$(".menu P").mouseover( function() {
		$(this).addClass('active');
	}).mouseout( function() {
		$(this).removeClass('active');
	});

	// float links
	$("a.float").mouseover(function(e){
		var xy = getScrollXY();
		$("#float-text").remove();
		$("#float-container").append('<div id="float-text"><div id="shadow"><div>'+$(this).attr("anons")+'</div></div></div>');
		$("#shadow").dropShadow({left: 5, top: 5, opacity: 0.2, blur: 0});
		var px = ( e.pageX > w.width() - 255 ) ? w.width() - 255 : e.pageX;
		//var py = ( w.height() - $("#shadow").height() - botMargin < e.pageY - xy[1] ) ? w.height() - $("#shadow").height() + xy[1] - botMargin : e.pageY;
		var py = ( w.height() - $("#shadow").height() - botMargin < e.pageY - xy[1] ) ? e.pageY - $("#shadow").height() - botMargin : e.pageY;
		$("#float-text").css( {'position':'absolute','top': py,'left':px,'z-index':'250' } );
    }).mousemove(function(e){
		var xy = getScrollXY();
		var px = ( e.pageX > w.width() - 255 ) ? w.width() - 255 : e.pageX;
		var py = ( w.height() - $("#shadow").height() - botMargin < e.pageY - xy[1] ) ? e.pageY - $("#shadow").height() - botMargin : e.pageY;
		$("#float-text").css( {'position':'absolute','top': py,'left':px,'z-index':'250' } );
    }).mouseout(function(e){
		$("#float-text").remove();
	});

	// auto scaling catalog
	resizeCatalog();

	// scroll bar
	$("#block-service-move").css( {'margin-left' : '0px' } );
	$("#right-arrow").mouseover(function(e){
		var $paneOptions = $('#block-service');
		$paneOptions.stop().scrollTo( { top:0,left:800} , 800 );
		$("#right-arrow").css('color','#c52100');
		$("#left-arrow").css('color','#666');
	});
	$("#left-arrow").mouseover(function(e){
		var $paneOptions = $('#block-service');
		$paneOptions.stop().scrollTo( { top:0,left:0} , 800 );
		$("#left-arrow").css('color','#c52100');
		$("#right-arrow").css('color','#666');
	});

	// search
	var toUseSearch = 0;
	$("#searchfld").focus(function () {
		toUseSearch = "searchfld";
		$("#searchfld").val("");	
	});
	$("#searchfld").blur(function () {
		toUseSearch = 0;
		if( $("#searchfld").val() == "" ) $("#searchfld").val("введите слово или фразу");	
	});
	$("#searchfld1").focus(function () {
		toUseSearch = "searchfld1";
	});
	$("#searchfld1").blur(function () {
		toUseSearch = 0;
	});
	$("#sbutton1").click(function () {
		search("searchfld1");
	});
	$("#sbutton").click(function () {
		search("searchfld");
	});
});


$(window).resize(function() {
	resizeCatalog();
});

$(window).scroll(function() {
	if( dropshadow[1] ) {
		dropshadow[1].remove(); 
		var xy = getScrollXY();
		$clone.css('top', 30 + xy[1] );
		dropshadow[1] = $clone.dropShadow({left: 10, top: 10, opacity: 0.2, blur: 0, color: "black" });
	}
});

$(document).keyup(function(event){
	if (event.keyCode == 13 && toUseSearch != 0 ) {
		search( toUseSearch );
	}
});

/**
 *	функция автомасштабирования блоков каталога
 */
function resizeCatalog() {
	var w = $(window);
	if( w.width() < 1280 ) {
		$("#logo img").attr('src','/project/img/i-logo-s1.png');
		$("#logo img").css('margin-top','47px');
	} else {
		$("#logo img").attr('src','/project/img/i-logo-m.png');
		$("#logo img").css('margin-top','0');
	}

	//alert( $(".col80").width() );
	//alert( parseInt( 0.9 * 0.7 * w.width() ) );

	var widthCat = $(".col80").width()-2; //parseInt( 0.9 * 0.7 * w.width() ); //  90% * 70%
	var numCat = Math.floor( widthCat / 170 ); // 140 + 10(margin)
	var widthPosition = parseInt( (widthCat - 10*(numCat-1) - 2 * numCat )/numCat );
	var lackWidth = widthCat - widthPosition * numCat - 10*(numCat-1) - 2 * numCat;
	var n = 1;
	$.each( $(".catalog"), function(i,val) {
		if( $(this).attr("end") == "1" ) {
			$(this).css( {'width' : (widthPosition + lackWidth - 20) + 'px', 'margin-right' : 0} );
			n = 0;
		} else 
		if( n == numCat ) {
			$(this).css( {'width' : (widthPosition + lackWidth - 20) + 'px', 'margin-right' : 0} );
			n = 0;
		} else {
			$(this).css( {'width' : (widthPosition - 20) + 'px', 'margin-right' : '10px'} );
		}
		n ++;
	});
}

/**
 *	пробегаем по всем иконкам, подсвечивая их
 */
function refreshIcons() {
	$(".fast-icq").animate({backgroundPosition: "(0 0)"}, 100, function() {
		$(this).css( {backgroundPosition: "0 20px"} );
		$(".fast-skype").animate({backgroundPosition: "(0 0)"}, 100, function() {
			$(this).css( {backgroundPosition: "0 20px"} );
			$(".fast-hi").animate({backgroundPosition: "(0 0)"}, 100, function() {
				$(this).css( {backgroundPosition: "0 20px"} );
				window.setTimeout( "refreshIcons()", 5000 );
			});			
		});		
	});
}

/**
 *	слайдер на баннеры
 */
function slideSwitch() {
    var $active = $('#slide-banner DIV.active');
    if ( $active.length == 0 ) $active = $('#slide-banner DIV:last');
 
    // use this to pull the images in the order they appear in the markup
    var $next =  $active.next().length ? $active.next()
        : $('#slide-banner DIV:first');
    $active.addClass('last-active');
    $next.css({opacity: 0.0})
        .addClass('active')
        .animate({opacity: 1.0}, 1000, function() {
            $active.removeClass('active last-active');
        });
}


/**
 *	функция определения размеров экрана с учетом скроллингов
 */
function getScrollXY() {
       var scrOfX = 0, scrOfY = 0;
       if( typeof( window.pageYOffset ) == 'number' ) {
               //Netscape compliant
               scrOfY = window.pageYOffset;
               scrOfX = window.pageXOffset;
       } else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
               //DOM compliant
               scrOfY = document.body.scrollTop;
               scrOfX = document.body.scrollLeft;
       } else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
               //IE6 Strict
               scrOfY = document.documentElement.scrollTop;
               scrOfX = document.documentElement.scrollLeft;
       }
       return [ scrOfX, scrOfY ];
}


/**
 *	функция поиска
 */
function search( toUseSearch ) {
	var addurl = "";
       var s = document.getElementById(toUseSearch ).value;
	s = s.replace("(", "");
	s = s.replace(")", "");
	s = encodeURIComponent(s);
	s = s.replace(/%20/g, "+");
	if( s != '') {
		var url = "/searchtext/search," + s + "/" + addurl;
		window.location.href = url;
	}
    return false;
}

/**
 *	функция печати
 */
function openPrint() {
	window.open("print/", "print","location=0,status=0,scrollbars=1,width=650,height=650");
}

/**
 *	функция заморозки кнопки отправления
 */
function preventSend( flag ) {
	$("#submit-button").attr( "disabled", (flag?'disabled':'') );
	$("#submit-text").html( (flag?'<font color=red>Заявка отправляется.. Пожалуйста, дождитесь отправки!</font>':'') );
}

/**
 *	функция раскрытия дерева
 */
function ModTree( image, id, area, selected, type ) {
	$("#tree" + area + "" + id).html('<img src="/_page/img/load.gif">');
	$.get("/project/phpfiles/_ajax.php", { action: 'modtree', id: id, type: type, selected: selected }, function(data) {
		$("#tree" + area + "" + id).html(data);	
		$("#tree" + area +""+ id).css('display', ($("#tree" + area +""+ id).css('display') == 'none' ? 'block' : 'none') );
		$("#image"+id).attr( 'src', ( $("#image"+id).attr('src').indexOf('close')==-1 ? "/_img/catalog/tree_close.gif" : "/_img/catalog/tree_open.gif") );
		$("min"+id).attr( 'src', ( $("#image"+id).attr('src').indexOf('close')==-1 ? "/_img/catalog/min.gif" : "/_img/catalog/plus.gif") );
	});
}

/**
 *	всплывающие форм-окошки
 */
function openFloatForm( id, name ) {
    var xy = getScrollXY();
    var elem = $(window);
    var floatX = parseInt( 0.05 * elem.width() ); //( elem.width() - 450 ) / 2;
    var floatY = ( elem.height() / 2 - 200) + xy[1] ;
    $("#form-header").html( name );
    $("#tovarname").val( name );
	$("#form-shadow").css( {'top': floatY,'left': floatX, 'z-index': 99999 } );
    $("#form-shadow").dropShadow({left: 10, top: 10, opacity: 0.2, blur: 0});
    $("#form-shadow").css({'visibility':'visible'});
}
function closeFloatForm( id ) {
    $("#form-progress").html(" ");
    $("#form-" + id ).css({'visibility':'hidden'});
    var sid = $("#form-" + id).shadowId();
    $("#"+sid).remove();
}
function floatProgress() {
    $("#form-progress").html( "Отправляем сообщение.. Пожалуйста, подождите..." );
}

/**
*  CONSULT
**/
function scanOpenSessions() {
	$.get("/project/phpfiles/_consult.php", { action: 'showactive', r: Math.random()}, function(data) {
		if( data && !opensess[1] ){	
			//if( confirm("Мы можем помочь Вам с выбором интересующего Вас продукта!\nРазрешите открыть сеанс связи с оператором?") ) {
				openConsult( 1, "" ); // cookie & ip
			//}
		}
	});
	scanopen = window.setTimeout( "scanOpenSessions()", 2000 );
}

var global = 0;
var opensess = [];
var sess = [];
var clones = [];
var textarea = [];
var messages = [];
var shadow = [];
var dropshadow = [];
var operator = [];
var icall = [];
var heads = [];
var hds = [];

function openConsult( id, page) {
	if( opensess[id] ) return;
	opensess[id] = 1;
	$clone = $("#form-container").clone().removeAttr("id");
	clones[id] = $clone;
	$clone.attr("id", "form-container" + id);
 	$("#consult-container").append($clone);
	var xy = getScrollXY();
   	$clone.css({'position':'absolute','visibility':'visible','left' : (global*300 + 30) + "px",'top' : (global*30 + 30 + xy[1]) + "px"});
	$clone.maxZIndex({ inc: 5 });
	dropshadow[id] = $clone.dropShadow({left: 10, top: 10, opacity: 0.2, blur: 0, color: "black" });

	$.each( $(".ip:noid:first"), function(i,val) {
		$(this).attr("id", "ip"+id);
		$(this).html("<span>Сеанс связи</span>");
		hds[id] = $(this);
		document.getElementById("ip"+id).onselectstart = function() { return false; };
		$(this).unselectable = "on";
		$(this).css('-moz-user-select', 'none');   
		$(this).dblclick(function(e) { 
			var idc = $(this).attr("id").replace('ip','');
 			dropshadow[idc].remove();
			if( clones[idc].data('roll') == null ) {
				clones[idc].css({'overflow':'hidden', 'height':'470px'});
				clones[idc].stop().animate({'height' : '35px'},500, function() {
					dropshadow[idc] = clones[idc].dropShadow({left: 10, top: 10, opacity: 0.2, blur: 0});
				});

				clones[idc].data('roll',1);
			} else {
				clones[idc].stop().animate({'height' : '470px'},500, function() {
					dropshadow[idc] = clones[idc].dropShadow({left: 10, top: 10, opacity: 0.2, blur: 0});
					messages[idc].css({ 'width' : '100%', 'height' : ($(this).height()-335)+'px'});
				});
				clones[idc].data('roll',null);
			}
		});
	});

	$clone.draggable({ cursor: "move", handle: hds[id],
		start: function(event, ui) { dropshadow[id].remove(); },
		stop: function(event, ui) { dropshadow[id] = $(this).dropShadow({left: 10, top: 10, opacity: 0.3, blur: 0}); }
	});

	$clone.resizable({
		minHeight: 480,
		minWidth: 400,
   		start: function(event, ui) { dropshadow[id].remove(); },
		resize: function(event, ui) { 
			messages[id].css({ 'width' : '100%', 'height' : ($(this).height()-335)+'px'});
			textarea[id].css({ 'width' : '100%' });
		},
		stop: function(event, ui) { 
			dropshadow[id] = $(this).dropShadow({left: 10, top: 10, opacity: 0.3, blur: 0});
			messages[id].css({'width':'100%'});
			textarea[id].css({'width':'100%'});
		}
	});
	var isCtrl = false;
	$clone.keyup(function (e) {
		if(e.keyCode == 17) isCtrl=false;
	}).keydown(function (e) {
		if(e.keyCode == 17) isCtrl=true;
		if(e.keyCode == 13 && isCtrl == true) {
			var idc = $(this).attr("id").replace('form-container','');
			var txt = textarea[idc].val();
			textarea[idc].val("");
			$.get("/project/phpfiles/_consult.php", {message: txt}, function(data) {
				messages[idc].html(data);
				messages[idc].stop().scrollTo( { top: 70000, left: 0 } , 100 );
			});
			return false;
		}
	});
	$.each( $(".btn-close:noid:first"), function(i,val) {
		$(this).attr("id", "close"+id);			
		$(this).click( function() {
			var idc = $(this).attr("id").replace('close','');
			clones[idc].remove();
			dropshadow[idc].remove();
			opensess[idc] = 0;
			// terminate call
			$.get("/project/phpfiles/_consult.php", { action: 'terminate', r: Math.random() });
		});
	});

	$.each( $(".symple:noid:first"), function(i,val) {
		$(this).attr("id", "textarea"+id);
		textarea[id] = $(this);
	});
	$.each( $(".input-call:noid:first"), function(i,val) {
		$(this).attr("id", "icall"+id);
		icall[id] = $(this);
	});
	$.each( $(".btn-call:noid:first"), function(i,val) {
		$(this).attr("id", "bcall"+id);
		$(this).click( function() {
			var idc = $(this).attr("id").replace('bcall','');
			var abonent = icall[idc].val();
			$(this).val("Соединяем...");
			$.get("/project/phpfiles/_consult.php", {abonent: abonent, action: 'call', page: page, r: Math.random()}, function(data) {
				var res = data.split("|");
				icall[idc].val(res[0]);
				if( res[1] == 1 ) {
					$(this).attr("disabled","disabled");
					$(this).val("Установлено соединение!");
				}
			});
		});
	});
	$.each( $(".messages:noid:first"), function(i,val) {
		messages[id] = $(this);
		refreshMess( id );
	});
	$.each( $(".form-header:noid:first"), function(i,val) {
		heads[id] = $(this);
		$(this).css({backgroundPosition: "50% 50%"});
	});
	$.each( $(".btn-send:noid:first"), function(i,val) {
		$(this).attr("id", "send"+id);
		$(this).click( function() {
			var idc = $(this).attr("id").replace('send','');
			var txt = textarea[idc].val();
			textarea[idc].val("");
			$.get("/project/phpfiles/_consult.php", {message: txt}, function(data) {
				messages[idc].html(data);
				messages[idc].stop().scrollTo( { top: 70000, left: 0 } , 100 );
			});
		});
	});

	// activate call
	$.get("/project/phpfiles/_consult.php", { action: 'activate', r: Math.random() }, function(data) {
		//
	});
}

function refreshMess( idc, start  ) {
	//heads[idc].css({'background':'url(/project/img/c-header-animate.png)'});
	//heads[idc].animate({backgroundPosition:"(1000px 0)"}, {duration:1500});
	$.get("/project/phpfiles/_consult.php", { start: start, write: 1, message: textarea[idc].val(), r: Math.random() }, function(data) {
		if( data ) {
			messages[idc].html(data);
			messages[idc].stop().scrollTo( { top: 70000, left: 0 } , 100 );
		}
		messtimer = setTimeout( "refreshMess("+idc+", 0)", 4000 );
	});
}