




$(document).ready(function(){

	launchJ();

	var w = $(window);
	var selectActive = 0;
	var $dropshadow = null;
	var botMargin = 20;
	var golos = 0;

	$("img[align='left']").css('margin','0 10px 10px 0');
	$("img[align='right']").css('margin','0 0 10px 10px');

	$("#conf #sum").css('display','none');



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

	// запускаем баннеры в ротацию
	initSlider();

	// tags size modify
	$.each( $(".tags A"), function() {
		$(this).css('font-size', parseInt(10 + 0.1*parseInt($(this).attr('size'))) + 'px');
	});

	// прототип функции максинга зиндекса
	$.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") == '';  
		}  
	}); 



	// === truncate comment data
	$("textarea[name='comment']").focus( function() {
		if( $(this).val() == "Введите здесь свой комментарий") $(this).val('');
	});

	jQuery.fn.addtocopy = function(usercopytxt) {
    		var options = {htmlcopytxt: '<br><br>Подробнее смотри на сайте компании Сервер Юнит: <a href="'+window.location.href+'">'+window.location.href+'</a><br>', minlen: 25, 
		addcopyfirst: false}
    		$.extend(options, usercopytxt);
	var copy_sp = document.createElement('span');
	copy_sp.id = 'ctrlcopy';
	copy_sp.innerHTML = options.htmlcopytxt;
	return this.each(function(){
		$(this).mousedown(function(){$('#ctrlcopy').remove();});
		$(this).mouseup(function(){
			if(window.getSelection){	//good times
				var slcted=window.getSelection();
				var seltxt=slcted.toString();
				if(!seltxt||seltxt.length<options.minlen) return;
				var nslct = slcted.getRangeAt(0);
				seltxt = nslct.cloneRange();
				seltxt.collapse(options.addcopyfirst);
				seltxt.insertNode(copy_sp);
				if (!options.addcopyfirst) nslct.setEndAfter(copy_sp);
				slcted.removeAllRanges();
				slcted.addRange(nslct);
			} else if(document.selection){	//bad times
				var slcted = document.selection;
				var nslct=slcted.createRange();
				var seltxt=nslct.text;
				if (!seltxt||seltxt.length<options.minlen) return;
				seltxt=nslct.duplicate();
				seltxt.collapse(options.addcopyfirst);
				seltxt.pasteHTML(copy_sp.outerHTML);
				if (!options.addcopyfirst) {nslct.setEndPoint("EndToEnd",seltxt); nslct.select();}
			}
		});
  		});
	}

    	//$(document).addtocopy({htmlcopytxt: '<br><br>Подробнее смотри на сайте компании Сервер Юнит: <a href="'+window.location.href+'">'+window.location.href+'</a>', minlen:25, 
    	//$(document).addtocopy({htmlcopytxt: '<br><br>А самим никак написать нельзя, уродцы?', minlen:25, 
	//	addcopyfirst: 
	//false});

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

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


	$.each( $(".button"), function(i,val) {
		$(this).html( "<p id=\"bu"+i+"\">" + $(this).html() + "</p>" );
		$("#bu"+i).css({'border':'1px solid #20b35b','width':'100px','padding':'2px','background':'#20b35b'});
		$("#bu"+i).corner();
	});

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

// == voting 
	var bglength = 408; 
	$(".voting li").mouseover( function(){
		if( !$(this).attr('voting') ) $(this).css({'cursor': 'pointer', 'background-color': '#f0f0f0'});
	}).mouseout( function(){
		if( !$(this).attr('voting') ) $(this).css({'cursor': 'pointer', 'background-color': '#fff'});
	}).click( function() {
		if( !$(this).attr('voting') ) {
			$(".voting li").attr('voting','1');
			$(".voting li").css({ background: 'url(/project/img/bgi-voting.gif) no-repeat', backgroundPosition: "-" + bglength + "px 0px" });
			var vid = $(this).parent('ul').attr('vid');
			showVot( $(this).children('p').html(), vid);
		}
	});


	// catalog sub-popup
	//$(".catalog").corner();
	$(".catalog").mouseenter( function(e) {
		$(".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'); e.stopPropagation();
	}).mouseleave( function(e) {
		$(".drops").remove();
		$("#sub" + $(this).attr('sub')).css('visibility','hidden');e.stopPropagation();
	});

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

	// === snow block
	$(".snowswitch DIV").dropShadow({top: 5, left: -5, opacity: 0.2, blur: 0});
	$(".snowswitch P").click( function() {
		$.get("/project/phpfiles/_ajax.php",{action:'snow'}, function() {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');
	});

	// 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
	$("#searchfld").focus( function() {
		if( $(this).val() == "введите слово или фразу" ) $(this).val("");
	}).blur( function() {
		if( $(this).val() == "" ) $(this).val("введите слово или фразу");
	}).keypress(function(event) {
  		if (event.which == '13') {
			if( !$(this).val() ) {
				alert("Введите фразу  для поиска!");
				return false;
			}
			search("searchfld");
     			event.preventDefault();
		}
   	});
	$("#sbutton").click(function () {
		search("searchfld");
	});
	$("#searchfld1").focus( function() {
		if( $(this).val() == "введите слово или фразу" ) $(this).val("");
	}).blur( function() {
		if( $(this).val() == "" ) $(this).val("введите слово или фразу");
	}).keypress(function(event) {
  		if (event.which == '13') {
			if( !$(this).val() ) {
				alert("Введите фразу  для поиска!");
				return false;
			}
			search("searchfld1");
     			event.preventDefault();
		}
   	});
	$("#sbutton1").click(function () {
		search("searchfld1");
	});
});


$(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" });
	}
	var xy = getScrollXY();
	$(".snowswitch").css( {'top': xy[1]+140 });
});


////////////////////////////////////////////////////////////////////
/////////////////	MAIN JQUERY
////////////////////////////////////////////////////////////////////

    function launchJ() {
	var w = $(window);
	var $dropshadow = null;
	var botMargin = 20;

	// ==== forms round
	$.each( $(".rf-fields P"), function(i,val) {
		if( !$(this).attr('formed')) {
		var data = $(this).html();
		if( $(this).attr('class').indexOf('label') == -1 && $(this).attr('class').indexOf('btn') == -1 ) {
			var cls = ($(this).html().indexOf('TEXTAREA')!==-1 || $(this).html().indexOf('textarea')!==-1)?'areaformfield':'formfield'; 
			$(this).html( "<p id=\"bp"+i+"\">" + data + "<span class=\""+cls+"_\"></span></p>" );
			$(this).attr('formed','1');
			$("#bp"+i).css({'width':(parseInt($(this).css('width'))-16)+'px'});
			$("#bp"+i).addClass( cls );
			$("#bp"+i).attr('formed','1');
			$("#bp"+i).mouseover( function() {
				$(this).css('background-position', (cls=='formfield'?'0 -31px':'0 -120px') );
			}).mouseout( function() {
				$(this).css('background-position','0 0');
			});
		}
		if( $(this).attr('class').indexOf('btn') !== -1 ) {
			$(this).html( "<p id=\"bp"+i+"\">" + data + "</p>" );//
			$("#bp"+i).css({'border':'1px solid #ac1818','width':(parseInt($(this).css('width'))-10)+'px','padding':'4px','background':'#ac1818'});
			$("#bp"+i).corner('6px');	
			$(this).attr('formed','1');
			$("#bp"+i).attr('formed','1');
		}}		
	});

	// ==== float links
	$(".float").css('cursor','pointer');
	$(".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] ) ? 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();
	});

	// === tables
	$.each( $(".contentarea table"), function() {
		if( $(this).attr('class').indexOf('calendar')==-1 && $(this).attr('class').indexOf('service')==-1 && $(this).attr('class').indexOf('nojs')==-1) {
			$(this).css('width','100%');
			$.each( $(this).find('tr'), function(i) { 
				if( Math.floor(i/2) == i/2 ) 	$(this).addClass('tr1');
				else				$(this).addClass('tr2');
			});
		}
	});

    }

////////////////////////////////////////////////////////////////////
/////////////////	CONFIGURATOR
////////////////////////////////////////////////////////////////////

	var scanlimit = 1;
	function refreshJQuery() {
		launchJ();
		$(".select").change( function() {
			scanConf(1);
		});
	$(".w2.label").css('border-top','1px solid #f0f0f0');
	$("P:contains('поддерживается')").css('background','yellow');

	$(".addcart").click( function() {
		$i = $(this);
		var order = $i.attr("order").replace('\"','');
		if( !$i.attr("status") ) {
			$.get( "/project/phpfiles/_ajax.php", { action: 'config', spec: encodeURIComponent(order), price: $(this).attr("price") }, function(data) {
				//
			});
		} else {
 			//confStep();
		}
		$i.attr('src','/project/img/conf/btn-addoffer-add.png?i='+Math.random());
		$i.attr("status",1);
	});

	$(".countspec").blur( function() {
		$i = $(this);
		var sid = parseInt($i.attr("id").replace('speccountid',''));
		$.get( "/project/phpfiles/_ajax.php", { action: 'chgconfig', sid: sid, cnt: $i.val() }, function(data) {
			//	
		});
	});

	$("p.logos").find("img").mouseenter(function() {
		$(this).addClass("sbox");
	}).mouseleave(function() {
		$(this).removeClass("sbox");
	});
	}

	function scanConf(refresh) {
		var sheet = $("#1").children('option:selected').attr('sheet');
		$(".select").attr('disabled','disabled');
		var col = []; var sid = [];
		$.each( $(".select"), function(i,val) {
			if( refresh || i<1) {
				col[i] = $(this).attr('id');
				sid[i] = $(this).val();
			}
		});
		var scanagain = ( $(".logos IMG").length < 2 ) ? 1 : 0;
		$.get("/project/phpfiles/xls-conf-ajax2.php?rand="+Math.random(),{ col: col.join("~"), sid: sid.join("~"), sheet: sheet, refresh: refresh, scanagain: scanagain }, function(data){ 
			var print = data.split('-separator-');
			$("#result").html(print[0]);
			$("#selectors").html(print[1]);
			$(".select").attr('disabled','');
			refreshJQuery();
			if(!refresh || $(".logos IMG").length < 2 ) {
				scanConf(1);
			} 
		});
	}

////////////////////////////////////////////////////////////////////
/////////////////	OPEN FORMS
////////////////////////////////////////////////////////////////////

	function closeForm(form) {
		var $f = $("."+form);
		$f.css({visibility: 'hidden'});
	}
	function openForm(form) {
		var w = $(window);
		$f = $("."+form);
		var xy = getScrollXY();
		var size = [$f.width(),$f.height()];	
		var newLeft = ( w.width() - size[0] )/2;
    		var newTop =  ( w.height() - size[1] )/2 ;
		$f.css({top: newTop, left: newLeft, visibility: 'visible'});

		// save fact
		//$.get("/project/phpfiles/_ajax.php", { action: 'openform', url: window.location.href }, function(data) {
			//
		//});
	}

/**
 *	функция автомасштабирования блоков каталога
 */
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 initSlider() {
		$.each( $("#slide-banner DIV"), function(i,val) {
			$("#numero").append("<p id=\"sn"+i+"\" class=\"sn\">" + (i+1) + "</p>");
			$("#sn"+i).css({'border':'2px #fff','border-style':'none none solid solid','width':'27px','height':'27px','padding':'25px 20px 15px 20px','background':'#555','opacity':'0.2'});
			//$("#sn"+i).corner('10px');	
			$("#sn"+i).click( function() {
				slideSwitch(i+1);	
			});
		});
		$('#slide-banner DIV:first').addClass('active');
		$('#slide-banner DIV:last').addClass('last-active');
		$("#sn0").css({'opacity':'1.0'});
		slider = setInterval( "slideSwitch(0)", 15000 );
	}
	function slideSwitch(i) {
		// all banners
		var $active = $('#slide-banner DIV.active');
    		var $next =  $active.next().length ? $active.next() : $('#slide-banner DIV:first');
    		var $prev =  $active.prev().length ? $active.prev() : $('#slide-banner DIV:last');

		// click button
		if( i ) {
			clearInterval(slider);
    			var $next = $("div[num='"+i+"']");
		}

		// css
		$active.addClass('last-active');
		$next.css({opacity: 0.0})
       		.addClass('active')
       		.animate({opacity: 1.0}, 1000, function() {
            			$active.removeClass('active last-active');
    				$(".sn").css({'opacity':'0.2'});
				$("#sn" + (parseInt( $next.attr('num') ) - 1)).css({'opacity':'1.0'});
       		});

		// deactivate timer
		if( i ) {
			slider = setInterval( "slideSwitch(0)", 10000 );
		}
		return;
	}


/**
 *	функция определения размеров экрана с учетом скроллингов
 */
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 showVot( name, vid  ) {
		$(".voting li").css({ background: 'url(/project/img/bgi-voting.gif) no-repeat', backgroundPosition: "-408px 0px" });
		$(".voting .radio").html("");
		$.get( "/project/phpfiles/_ajax.php?t"+Math.random(), {action:'vot', name: name, vid: vid }, function(data) { 
			var mx = data.split("="); 
			var vot = mx[0].split(","); 
			for( v in vot ) {
				var vdata = vot[v].split('|');
				if( vdata[1] ) {
					$(".voting li:contains('"+vdata[0]+"')").animate({backgroundPosition:"(" + ( 200/mx[1]*parseInt(vdata[1])-408) +"px 0px)"}, {duration:1000});
					$(".voting li:contains('"+vdata[0]+"')").append('<p class="radio" style="text-decoration: none;">'+parseInt(vdata[1])+'</p>');
				}
			}
			$(".votmessage").html("На каждой странице сайта есть возможность оставить комментарий или предложение: мы выслушаем и учтем ваши замечания!");
		});
	}

/**
 *	функция печати
 */
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 setReseller(resell) {
    $("#resell").val(resell);
}  
function openFloatForm( id, name, resell, text ) {
    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 );
    if(text) {
	$("#question").val("Хотел бы приобрести " + text );
    	$("#tovarname").val( text );
    }
    $("#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( "Отправляем сообщение.. Пожалуйста, подождите..." );
}

/**
*  COMMENTS
**/
	function addComment() {
		var pageid = $("#commid").val();
		var comment = $("#comment"+pageid).val(); 
		if( comment.length < 7 || comment == "Введите здесь свой комментарий" ) {
			alert("Введите, пожалуйста, текст отзыва!");
			return;
		}
		var answer = $("#answer").val(); 
		$.get("/project/phpfiles/_ajax.php", { action: 'comment', pageid: pageid, comment: comment, answer: answer }, function(data) {
			//
		});
		alert( "Сообщение добавлено!" );
		window.location.reload();
	}
	function commCite(data, date) {
		var pageid = $("#commid").val();
		$("#comment"+pageid).val( "-----------------------------<br>Цитирую "+date+"<br>----------------------------<br>"+data+"<br>----------------------------<br>" ); 
		return;
	}

	function commAnswer(id) {
		$("#answer").val( id ); 
		$("#to-answer").html("Отвечаем на пост # " + id); 
		return;
	}


////////////////////////////////////////////////////////////////////
/////////////////	CONSULT
////////////////////////////////////////////////////////////////////
function scanOpenSessions() {
	$.get("/project/phpfiles/_consult.php", { action: 'showactive', r: Math.random()}, function(data) {
		if( data.indexOf('exit') ==-1 ) {
			scanopen = window.setTimeout( "scanOpenSessions()", 2000 );
			if( data && !opensess[1] ){	
				openConsult( 1, "" ); // cookie & ip
			}
		} else {
			clearTimeout(scanopen);
		}
	});
}

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

function openConsult( id, page) {
//alert("Консультант временно в отпуске)");
//return false;
	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.1, blur: 0, color: "black" });

	$.each( $(".ip:noid:first"), function(i,val) {
		$(this).attr("id", "ip"+id);
		$(this).html("<span>Онлайн Консультант Server-Unit</span>");
		hds[id] = $(this);
		document.getElementById("ip"+id).onselectstart = function() { return false; };
		$(this).unselectable = "on";
		$(this).css('-moz-user-select', 'none');   
	});

	$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.1, blur: 0}); }
	});

	$clone.resizable({
		minHeight: 480,
		minWidth: 400,
   		start: function(event, ui) { dropshadow[id].remove(); },
		resize: function(event, ui) { 
			messages[id].css({ 'width' : ($clone.width() - 100)+'px' , 'height' : ($(this).height()-335)+'px'});
			textarea[id].css({ 'width' : '100%' });
		},
		stop: function(event, ui) { 
			dropshadow[id] = $(this).dropShadow({left: 10, top: 10, opacity: 0.1, blur: 0});
			messages[id].css({ 'width' : ($clone.width() - 100)+'px' , 'height' : ($(this).height()-335)+'px'});
			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( $(".btn-collapse:noid:first"), function(i,val) {
		$(this).attr("id", "btncpls"+id);	
		btnclps[id] = $(this);			
		$(this).click( function() {
			var idc = $(this).attr("id").replace('btncpls','');
 			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.1, blur: 0});
					messages[idc].css({ 'width' : '10px' , 'height' : '10px' });
				});
				clones[idc].data('roll',1);
				clones[idc].data('mesheight',messages[idc].css('height'));
				btnclps[idc].attr('src', '/project/img/btn-expand.gif');
			} else {
				clones[idc].stop().animate({'height' : '470px'},500, function() {
					dropshadow[idc] = clones[idc].dropShadow({left: 10, top: 10, opacity: 0.1, blur: 0});
					messages[idc].css({ 'width' : (clones[idc].width() - 100)+'px' , 'height' : '150px' });
				});
				clones[idc].data('roll',null);
				btnclps[idc].attr('src', '/project/img/btn-collapse.gif');
			}
		});
	});
	$.each( $(".symple:noid:first"), function(i,val) {
		$(this).attr("id", "textarea"+id);
		textarea[id] = $(this);
		$(this).click( function() {
			var idc = $(this).attr("id").replace('textarea','');	
			textarea[idc].css('background','none');	
		});
		$(this).blur( function() {
			var idc = $(this).attr("id").replace('textarea','');	
			textarea[idc].css('background','url(/project/img/bgi-textarea.gif) no-repeat 50% 50%');	
		});
	});
	$.each( $(".input-call-1:noid:first"), function(i,val) {
		$(this).attr("id", "icall_1"+id);
		icall_1[id] = $(this);
	});
	$.each( $(".input-call-2:noid:first"), function(i,val) {
		$(this).attr("id", "icall_2"+id);
		icall_2[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 = "8" + icall_1[idc].val() + icall_2[idc].val();
			$(this).val("Соединяем...");
			$.get("/project/phpfiles/_consult.php", {abonent: abonent, action: 'call', r: Math.random()}, function(data) {
				var res = data.split("|"); 
				//icall_1[idc].val(res[0]);
				if( res[1] == 1 ) {
					$("#bcall"+idc).attr("disabled","disabled");
					$("#bcall"+idc).val("Ждите звонка!");
				} else {
					$("#bcall"+idc).attr("disabled","");
					$("#bcall"+idc).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 );
	});
}
