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

// ===	dyndata edit
	$(".dyndata").mouseenter( function() {
		$(this).css('margin','0 -1px').addClass('dynedit');
		$(this).find('.dyneditblock').addClass('dynactive');
	}).mouseleave( function() {
		$(this).css('margin','0 0').removeClass('dynedit');
		$(this).find('.dyneditblock').removeClass('dynedit');
	});
	$('.dyneditblock').mouseenter( function() {
		$(this).addClass('dynactivehover');
	}).mouseleave( function() {
		$(this).removeClass('dynactivehover');
	});

// === siteem-l
	$.get("/project/phpfiles/_ajax.php", {action:'siteemail'}, function(data) {
		$(".siteemail").html(data);		
	});

	// === sersearchTExt
	$(".setSearchText").click( function() {
		$("#searchfld").val( $(this).html() );
	});
	
// === 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();});
	});

	// === bookmarks
	$('ul.tabs').delegate('li:not(.current)', 'click', function() {
		$(this).addClass('current').siblings().removeClass('current')
			.parents('div.section').find('div.box').hide().eq($(this).index()).fadeIn(150);
	})

	// === qweek buy
	$(".pinner").mouseenter( function() {
		$qbuy = $(this).children('.qbuy');
		$qbuy.fadeIn(150);
	}).mouseleave( function() {
		$qbuy = $(this).children('.qbuy');
		$qbuy.fadeOut(150);
	});

	// === rating
	$('.auto-submit-star').rating({
  		callback: function(value, link){
			var id = $(this).attr("name").replace('rating','');
			$.get("/project/phpfiles/_ajax.php", { action: 'rating', rate: value, id: id }, function(data) {
				//
			});
 		}
 	});

	//$(".fixedbg").css('opacity','0.5');

	// ==== ZAYAV FORM
	$(".closeform").click( function(e) {
		closeForm();
		$("#showFormData").html("<div id=\"videocontainer\"></div>");
	});
	$(".video-link").mouseover( function() {
		$(this).find('img').css('opacity','0.2');
		$(this).css('cursor','pointer');
		$(this).addClass('video-hover');
	}).mouseout( function() {
		$(this).removeClass('video-hover');
		$(this).find('img').css('opacity','1.0');
	}).click( function(e) { 
		$("#showFormData").html("<div id=\"videocontainer\"></div>");
		swfobject.embedSWF("/project/flash/uppod.swf?file="+$(this).attr('video')+"&st=/project/flash/video1.txt", "videocontainer", "447", "403", "8.0.0", "/project/flash/expressInstall.swf", {mode:"main",rnd:Math.random()}, {menu:"false", wmode:"transparent"}, { id:"videocontainer", name:"flash-banner" });
		var $f = $(".showForm");
		var xy = getScrollXY();
		var size = [$f.width(),$f.height()];	
		var newLeft = ( w.width() - size[0] )/2;
    		var newTop = 150;// ( w.height() - size[1] )/2 ;
		$f.css({top: newTop, left: newLeft, visibility: 'visible'});
		$.get( "/project/phpfiles/_ajax.php", {action: 'statvideo', video: $(this).attr('video')});
	});

	// === инициализация галочки сборки
	$(".basket-comment:contains('разобранный')").addClass('info float');
	$(".basket-comment:contains('разобранный')").attr('anons','Внимание: данный товар поставляется в разобранном виде! Для сборки на месте на шаге <b>доставка и сборка</b> выберите галочку: Требуется сборка - или нажмите: включить сборку в заказ');
	$(".basket-comment:contains('разобранный')").append(" <a href=\"javascript: setform('sborcheck',0,1,'Сборка включена в ваш заказ!')\">[включить сборку в заказ]</a>");

	// === инициализация галереи
 	$('a.lightbox').lightBox();

	// === order roller
	$.each( $(".rol-order"), function(i,val) {
		if( $(this).attr('order') == '1' ) {
			$(this).css('background-position','-89px 50%');
			$(this).text('товар в корзине');
		}
		if( fmodel = $(this).attr('formodel') ) {
			$(".main-price" + fmodel).css('display','none');
		}		
	});
	$(".rol-order").mouseover( function() {
		if( $(this).attr('order') != '1' ) $(this).css('background-position','-89px 50%');
	}).mouseout( function() {
		if( $(this).attr('order') != '1' ) $(this).css('background-position','0px 50%');
	}).click( function() {
		$(this).attr('order','1');
		$(this).css('background-position','-89px 50%');
		$(this).text('товар в корзине');
		return true;
	});

	// === float links
	$.each( $(".float"), function() {
		if( !$(this).attr("anons") ) {
			$(this).removeClass("float");
			$(this).removeClass("info");
		}
	});
	$(".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>');
		if( fw = $(this).attr('fw')) {
			$("#float-text").css('width', fw );
			$("#shadow").css('width', fw-10 );
		}
		$("#shadow").dropShadow({left: 5, top: 5, opacity: 0.2, blur: 0}); 
		var px = ( e.pageX > w.width() - 400 ) ? w.width() - 400 : 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() - 400 ) ? w.width() - 400 : 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();
	});

	// === clear control panel if empty
	if( $(".controls").html() && $(".controls").html().length > 20){
		$(".controls").css('display','block');
		$(".controls").corner("round 10px");
	} else {
		$(".controls").css('display','none');
	}

	// === corner mainpage blocks

	if( !$.browser.msie) {
		$(".maincatalogblock").corner();
		$(".blockheader DIV").corner();
	}
	$(".block-header DIV.data").corner();	

	// === collection scrolling
	$(".coll-cont").mousemove( function(e) {
		var Div = $("#coll-cont"); 
		var lastDiv = $("#coll-move").find("div:last-child");
		var divWidth = Div.width();
		var ulPadding = 15;
		var ulWidth = lastDiv[0].offsetLeft + lastDiv.outerWidth() + ulPadding;
		var left = (e.pageX - Div.offset().left) * (ulWidth-divWidth) / divWidth;
		Div.scrollLeft(left);
	});

	// === control products width
	resizeCatalog();

	// ==== forms round
	$.each( $(".rf-fields P"), function(i,val) {
		if( $(this).attr('class').indexOf("label") == -1 && $(this).attr('class').indexOf("btn") == -1 && $(this).attr('class').indexOf("active") == -1 ) {
			$(this).html( "<p id=\"bp"+i+"\">" + $(this).html() + "</p>" );
			$("#bp"+i).css({'border':'1px solid #ddd','width':$(this).width()-8,'padding':'3px','background':'#f0f0f0','min-height':'15px'});
			$("#bp"+i).corner('3px');	
			$("#bp"+i).mouseover( function() {
				$(this).css({'border':'1px solid #f50000','background':'#f5f5f5'});
			}).mouseout( function() {
				$(this).css({'border':'1px solid #ddd','background':'#f0f0f0'});
			});
		}
		if( $(this).attr('class').indexOf("btn") != -1 ) {
			$(this).html( "<p id=\"bp"+i+"\">" + $(this).html() + "</p>" );
			$("#bp"+i).css({'border':'1px solid #308ed0','width':$(this).width()-8,'padding':'2px','background':'url(/project/img/bluetop.gif)'});
			$("#bp"+i).corner('3px');	
			$("#bp"+i).mouseover( function() {
				$(this).css({'border':'1px solid #61b0e7','background':'#61b0e7'});
			}).mouseout( function() {
				$(this).css({'border':'1px solid #308ed0','background':'url(/project/img/bluetop.gif)'});
			});
		}
	});
	$.each( $(".pricefield P"), function(i,val) {
		$(this).html( "<p id=\"bp"+i+"\">" + $(this).html() + "</p>" );
		$("#bp"+i).css({'border':'1px solid #ddd','width':$(this).width()-8,'padding':'3px','background':'#f0f0f0'});
		$("#bp"+i).corner('3px');	
	});

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

	$.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") == '';  
		}  
	}); 
	$.fn.outer = function(val){
   		if(val){
        		$(val).insertBefore(this);
        		$(this).remove();
    		}
    		else{ return $("<div>").append($(this).clone()).html(); }
	}

	$(".bm-bg-last").css( {'backgroundImage':'url(/project/img/bm-non.png)', 'background-position' : '100% 0'} );
	$(".bm-bg-i").css( {'backgroundImage':'url(/project/img/bm-non.gif)', 'background-position' : '100% 0' } );
	$(".bm-bg-first").css( {'backgroundImage':'url(/project/img/bm-act.gif)'} );
	$(".bm-bg-first A").css( {'color':'#2e4d60'} );
	var lid = $(".bm-bg-i:last").attr("id");


	$(".bm-link").click(function() {
		$(this).attr( "class", "bm-active" ); 

		var group = $(this).attr('group');
		$("#bm-container"+group+" .bm-area").css( 'display','none' );
		$("#bm-container"+group+" .bm-bg-i").css( 'backgroundImage','url(/project/img/bm-non.gif)' );
		$("#bm-container"+group+" .bm-bg-last").css('backgroundImage','url(/project/img/bm-non.png)');
		$("#bm-container"+group+" .bm-active").attr( 'class','bm-link' );
		$("#bm-container"+group+" .bm-bg-i A").css('color','#fff');
		$("#bm-container"+group+" .bm-bg-last A").css('color','#fff');

		var bmactive = $(this).attr("bm"); 
		$("#bm-container"+group+" #bm" + bmactive).css( {'display':'block'} );
		var acss = $("#bm-container"+group+" #bm-bg" + bmactive).attr('class');
		if( acss == "bm-bg-last" ) {
			$("#bm-container"+group+" #bm-bg" + bmactive).css( {'backgroundImage':'url(/project/img/bm-act.png)'} );
		} else {
			$("#bm-container"+group+" #bm-bg" + bmactive).css( {'backgroundImage':'url(/project/img/bm-act.gif)'} );
		}
		$("#bm-container"+group+" #bm-bg" + bmactive + " A").css( {'color':'#2e4d60'} );
	});
 //---
  var toUseSearch = 0;
  $("#searchfld").focus(function () {
       toUseSearch = "searchfld";
	if( $("#searchfld").val() == "Введите слово или фразу для поиска.." ) {
		$("#searchfld").val("");
	}	
  });
  $("#searchfld").blur(function () {
       toUseSearch = 0;
	if( $("#searchfld").val() == "" ) $("#searchfld").val("Введите слово или фразу для поиска..");	
  });

// === FORM HOVERS ===
	$("#username").focus( function() {
		if( $(this).val() == "E-Mail" )  $(this).val(""); 
	}).blur( function() {
		if( $(this).val() == "" )  $(this).val("E-Mail"); 
	});

	$("#password").focus( function() {
		if( $(this).val() == "12345" )  $(this).val(""); 
	}).blur( function() {
		if( $(this).val() == "" )  $(this).val("12345"); 
	});

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

/***
 **	WINDOW RESIZE
 **/
	$(window).resize(function() {
		resizeCatalog();
	});

/***
 **	WINDOW SCROLL
 **/
	$(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();
	var win = $(window);
	var floatX = 300;
	var floatY = xy[1]+40;
	var floatendX = win.width() - 252;

	// delete shadow from container
	var i = $("#float-alert").attr("id");
	if( i != undefined ) {
    		var sid = $("#float-alert").shadowId();
    		$("#"+sid).remove();
		$("#float-alert").css( {'top': floatY });
		$("#float-alert").dropShadow({left: -4, top: 2, opacity: 0.1, blur: 1});
	}

	});

/***
 **	CUSTOM FUNCTIONS
 **/

function resizeCatalog() {
	var widthCat = $(".controls").width() + 20;  if(widthCat == 20) widthCat = $("#centerblock").width(); //alert(widthCat);
	if( $(".product").length < 2 ) return;
	var numCat =  Math.floor( widthCat / 460 ); // 420 + 10(margin)
	var widthPosition = parseInt( widthCat/numCat ); 
	var lackWidth = widthCat - widthPosition * numCat - 20*(numCat-1); //alert( widthCat+ " " + numCat + " " + widthPosition+" " + lackWidth );
	var n = 1;
	$.each( $(".product"), function(i,val) {
		if( $(this).attr("end") == "1" ) {
			$(this).css( {'width' : (widthPosition + lackWidth) + 'px', 'margin-right' : 0} );
			n = 0;
		} else 
		if( n == numCat ) {
			$(this).css( {'width' : (widthPosition + lackWidth) + 'px', 'margin-right' : 0} );
			n = 0;
		} else {
			$(this).css( {'width' : (widthPosition) + 'px', 'margin-right' : '20px'} );
		}
		n ++;		
	});
}

function search( toUseSearch ) {
	var addurl = "";
       var s = document.getElementById(toUseSearch ).value;
	s = s.replace("(", "");
	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 SetOrder( id, param, price, spec, oid, mancount, nodynamic ){
	closeAlert();
	if( mancount ) {
		var count = mancount;
	} else 
	if( spec ) {
		var count = parseInt( document.getElementById('count' + spec + '_' + price).value );
	} else 
	if( oid ) {
		var count = parseInt( document.getElementById('count' + oid).value );
	} else {
		var count = parseInt( document.getElementById('count' + id).value );
	}
	if( !count ) count = 0;
	var sum = parseInt($("#sum").text());

	if( count == 0) {
		alert("Число элементов равно нулю");
		return false;
	}
	if( obj = document.getElementById("imagebasket" + id)) {
		obj.src = "/_page/img/fullbasket.gif";
	}

	if( param == 0) {
		if( confirm( "Вы действительно хотите удалить позицию из корзины?" )) {
			$("#orderid" + oid + " TD").css('display','none');
			$("#sum").text( sum - count * price );
			$.get("/project/phpfiles/_ajax.php", { id_cat: id, action: 'order', param: param, count: count, price: price }, function( data ) {
				return;
			});
		} else {
			alert( "Удаление отменено" );
			return false;
		}
	} else {
		if( param == 2) {
			//alert( "Позиция сохранена в количестве " + count + " элементов");
			document.getElementById( 'sum' ).innerHTML = sumBetter( sum + count * price - parseInt( document.getElementById('sum' + oid).innerHTML ));
			document.getElementById('sum' + oid).innerHTML = count * price;
       		$.get("/project/phpfiles/_ajax.php", { id_cat: id, action: 'order', param: param, count: count, price: price }, function( data ) {
				//
       		});
		} else {
			var xy = getScrollXY();
			var win = $(window);
			var floatX = 300;
			var floatY = xy[1]+70;
			var floatendX = win.width() - 252;
       			$.get("/project/phpfiles/_ajax.php", { id_cat: id, action: 'order', param: param, count: count, price: price, spectxt: $("#spectxt"+spec).text() }, function( data ) {
				var output = data.split("=|=");
				$(".panel-basket").html(output[1]);
				if( !nodynamic ) {
					$("#body").prepend("<div class=\"float-alert\" id=\"float-alert\"><div class=\"inner\">"+output[0]+"</div></div>");
					$("#float-alert").css( { 'position':'absolute','top': floatY, 'left': floatX, 'visibility' : 'visible', 'opacity': 0, 'background':'#fff' } );
					$("#float-alert").animate( {left: floatendX, opacity:1 }, 500, function() { 
						$("#float-alert").dropShadow({left:-4, top: 2, opacity: 0.2, blur: 1});
 					});
				}
       			});
		}
	}
}

function closeAlert() {
	var i = $("#float-alert").attr("id");
	if( i != undefined ) {
		var sid = $("#float-alert").shadowId();
		$("#"+sid).remove();
		$("#float-alert").remove();
	}
	return true;
}

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 ];
}
/**
*  CONSULT
**/
var global = 0;
var opensess = [];
sess = new Array();
var clones = [];
var textarea = [];
var messages = [];
var shadow = [];
var dropshadow = [];
var operator = [];
var icall = [];
var heads = [];
var btnclps = [];
var hds = [];
var face = [];

function scanOpenSessions() {
	$.get("/project/phpfiles/_consult.php", { action: 'showactive', r: Math.random()}, function(data) {
		if( data.indexOf('exit') ==-1 ) {
			params = [];
			if(data) 	params = data.split("::"); 
			scanopen = window.setTimeout( "scanOpenSessions()", 4000 );
			if( data && !opensess[1] ){
				openConsult( 1, "" ); // cookie & ip
			}
			if( params[1] ) {
				$("#face1").css('background-image','url('+params[1]+')');
				face[1].html(params[2]);
			}
		} else {
			clearTimeout(scanopen);
		}
	});
}

function openConsult( id, page) {
	$w = $(window);
	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' : ($w.width()-500)+'px','top' : (90 + 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');   
	});
	$.each( $(".form-header:noid:first"), function(i,val) {
		heads[id] = $(this);
		$(this).css({backgroundPosition: "50% 50%"});
	});
	$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.2, 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);
			});
			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() });
			clearTimeout(scanopen);
		});
	});

	$.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: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( $(".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( $(".messages:noid:first"), function(i,val) {
		messages[id] = $(this);
		refreshMess( id );
	});
	$.each( $(".face:noid:first"), function(i,val) {
		$(this).attr("id", "face"+id);
		face[id] = $(this);
	});
	$.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);
			});
		});
	});

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


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

function URLDecode(str){
    str2 = "";
    for(k=0;k<str.length;k++){
        str2 += '%' + chr[str.charAt(k)];
    }
    return str2;
}
function BasketOut(obj) {
	if(obj.src.indexOf("fullbasket.gif") > 0) {
		obj.src = "/_page/img/fullbasket.gif";
	} else {
		obj.src = "/_page/img/emptybasket.gif";
	}
}
function BasketOver(obj) {
	if(obj.src.indexOf("emptybasket.gif") > 0) {
		obj.src = "/_page/img/putinbasket.gif";
	}
}

	function setBrand( value ) {
		window.location.href = '/brand/f,' + value + '/' ;
	}

function GP(x)
{
	if(x)	document.location.href = x;
	else	alert("страница отсутствует!");
}

function sumBetter (sum) {
	return sum;
	sum = sum.toString();
	newSum = "";
	n = sum.length;
	for( i=3; i < n; i +=3 ) {
		newSum += sum.Substr(n-i, 3);
	}
	return newSum;
}

/**
 **  СРАВНЕНИЕ ТОВАРОВ
 **/
	function addCompare(id) {
		$.get( "/project/phpfiles/_ajax.php", { action: 'compare', id: id }, function( data ) {
			$("#compareimage"+id).attr('src','/project/img/btn-compare-active.gif');
			$(".panel-compare").html(data);
		});
	}
	// функция удаляет товар из сравнения
	function removeCompare(id) {
		$.get("/project/phpfiles/_ajax.php", { id: id, action: 'removecompare' }, function( data ) {
			$("#compare" + id).css('display','none');
			$(".panel-compare").html(data);
		});
	}

/**
*  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;
	}


function ShowHide(idname)
{
 if (document.getElementById(idname).style.display == "none")
 {
  document.getElementById(idname).style.display = "block";
 }
 else
 {
  document.getElementById(idname).style.display = "none";
 }
}


function ModTree( image, id, area, selected, type ) {
		var ajax = new sack();
       	ajax.requestFile = "/_page/phpfiles/_ajax.php";
		ajax.setVar("action", "modtree");	
		ajax.setVar("id", id);
		ajax.setVar("type", type);
		ajax.setVar("selected", selected);
		//ajax.setVar("treetype", type );	
       	ajax.method = "GET"; 
		//ajax.onCompletion = whenCompletedModTree;	
        	ajax.element = "tree" + area + "" + id; 
		document.getElementById("tree" + area + "" + id).innerHTML = '<img src="/_page/img/load.gif">';
       	ajax.runAJAX();

		ShowHide("tree" + area +""+ id);
		//var imgsrc = document.getElementById("image"+id).src.toString();
		if( imagesrc = document.getElementById("image"+id) ) {
			imagesrc.src = (imagesrc.src.indexOf('close')==-1) ? "/_img/catalog/tree_close.gif" : "/_img/catalog/tree_open.gif";
			document.getElementById("min"+id).src = (image.src.indexOf('plus')==-1) ? "/_img/catalog/plus.gif " : "/_img/catalog/min.gif ";
		}
}
function OpenVendor( page, id, name ) {
		var ajax = new sack();
       	ajax.requestFile = "/_page/phpfiles/_ajax.php";
		ajax.setVar("action", "openvendor");	
		ajax.setVar("vendor", id);
		ajax.setVar("page", page );
		ajax.setVar("name", name);
       	ajax.method = "GET"; 
        	ajax.element = "vendor" + id; 
		document.getElementById("vendor" + id).innerHTML = '<img src="/_page/img/load.gif">';
       	ajax.runAJAX();
		ShowHide( "vendor" + id );
		if( imagesrc = document.getElementById( "vimage" + id ) ) {
			imagesrc.src = (imagesrc.src.indexOf('plus')==-1) ? "/_img/catalog/plus.gif " : "/_img/catalog/min.gif ";
		}
}

function calc_dalee(imgid,host)
{
  minus=host+'/images/'+imgid+'_on.jpg'; 
  plus=host+'/images/'+imgid+'_off.jpg';
  	if(document.getElementById(imgid).src==plus) {
	document.getElementById(imgid).src='/images/'+imgid+'_on.jpg';
	} else {
	document.getElementById(imgid).src='/images/'+imgid+'_off.jpg';
	}
}

function fixPNG(element, type)
{
  //???? ??????? IE ?????? 5.5-6
  if (/MSIE (5\.5|6).+Win/.test(navigator.userAgent))
  {
    var src;
    if (element.tagName=='IMG') //???? ??????? ??????? ???????? (??? IMG)
    {
      if (/\.png$/.test(element.src)) //???? ???? ???????? ????? ?????????? PNG
      {
        src = element.src;
        element.src = "/_img/serv/1x1.gif"; //???????? ??????????? ?????????? gif-??
      }
    }
    else //?????, ???? ??? ?? ???????? ? ?????? ???????
    {
	  //???? ? ???????? ?????? ??????? ????????, ?? ??????????? ???????? ???????? background-?mage ?????????? src
      src = element.currentStyle.backgroundImage.match(/url\("(.+\.png)"\)/i);
      if (src)
      {
        src = src[1]; //????? ?? ???????? ???????? background-?mage ?????? ????? ????????
        element.runtimeStyle.backgroundImage="none"; //??????? ??????? ???????????
      }
    }
    //????, src ?? ????, ?? ????? ????????? ??????????? ? ??????? ??????? AlphaImageLoader
	type = (type == 1) ? "crop" : "scale";

  if (src) element.runtimeStyle.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + src + "',sizingMethod='"+type+"')";
  }
}

function getElements(tag, name) {
     
     var elem = document.getElementsByTagName(tag);
     var arr = new Array();
     for(i = 0,iarr = 0; i < elem.length; i++) {
          att = elem[i].getAttribute("name");
          if(att == name) {
               arr[iarr] = elem[i];
               iarr++;
          }
     }
     return arr;
}
function makePrice( index ) {
	var price = new Array();
	var p = getElements("input", "pricetrue"); 
	for(i=0; i<p.length;i++) {
		price[i] = p[i].value;
	}
	var p = getElements("span", "icoprice");
	for(i=0; i<p.length;i++) {
		p[i].innerHTML = '<img src="' + curimages[index] + '">';
	}
	var p = getElements("span", "price");
	for(i=0; i<p.length;i++) {
		p[i].innerHTML = Math.floor(100*price[i]/currents[index])/100;
	}
}

function switchMainBookmark(a, num, group) {
	try {
		var td, tr = a, div;
		var node, i, remJ = [], curTD = 0;
		var rbArray = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17];
		if (div = document.getElementById(group + num)) {
			div.style.display = "";
			for (i = 0; i < rbArray.length; i++) if (rbArray[i] != num){
				if(document.getElementById(group + rbArray[i])) {
					document.getElementById(group + rbArray[i]).style.display = "none";
				}
			}
		} else return false;
		if (!num) return false;
		while (tr.parentNode && tr.nodeName.toLowerCase() != "tr") {
			if (tr.nodeName.toLowerCase() == "td") td = tr;
			tr = tr.parentNode;
		}
		for (i = 0; i < tr.childNodes.length; i++) {
			node = tr.childNodes[i];
			if (node.nodeType != 1) continue;
			if (node.nodeName.toLowerCase() != "td") continue;
	                if (node.firstChild.className != "lft" && node.firstChild.className != "lft first" && node.firstChild.className != "lst") continue;
			if (node == td) {node.className = "act"; curTD = 1;} 
			else {node.className = curTD ? "aftact" : "pas"; curTD = 0;}
		}
		return false;
	} catch(e) {
		return false;
	}
}

function AddBack( ){
// проверка полей
	var must = Array('varc_0','varc_7','txt_2');
	var fld = new Array( 'varc_0','varc_1','varc_7','txt_2','id' );
	var bad = 0;
	for ( var i = 0; i < must.length; i++ ) {
		if(document.getElementById(must[i]).value == "" || document.getElementById(must[i]).value == "0") {
			var bad = 1;
		}
	}
	if( bad ) {
		alert("Не все обязательные поля заполнены!");
		return false; 
	}
// отправка формы
	var ajax = new sack();
    	ajax.requestFile = "/_page/phpfiles/_ajax.php";
	ajax.setVar("action", "addback");

	for ( var i = 0; i < fld.length; i++ ) {
	    ajax.setVar( fld[i], URLDecode( document.getElementById(fld[i]).value ));
	}
	if(document.getElementById("str")) {
		ajax.setVar( "configurator", URLDecode( document.getElementById("str").innerHTML ));
	}
	ajax.method = "GET";
   	ajax.runAJAX(); 
 	alert("Запрос отправлен!");
	tb_remove();
}

/***
 **	FORM WINDOWS ==================================
 **/
	function closeFloatForm( id ) {
    		$("#form-" + id ).css({'left' : '-1000px'});
	}
	function submitProgress(status) {
    		if( status) {
			$("#sendquest" ).text('Обработка...');
    			$("#sendquest" ).attr('disabled','disabled');
		} else {
			$("#sendquest" ).text('Отправить запрос.');
    			$("#sendquest" ).attr('disabled','');
		}
		return true; 
	}
	function openAskWindow( id, name, type, prodid ) {
		closeFloatForm( id );
		var sid = $("#form-shadow").shadowId();
		$("#"+sid).remove();
		$("#form-" + id ).find('td').addClass('hidden');
		$("#form-" + id ).find('tr.'+type).children('td').removeClass('hidden');
		
		if( type == "fquest" ) {
			$(".form-header").text("Задать вопрос по товару");
			$("input[name='mailsubject']").val("Вопрос по товару");
		}
		if( type == "fqbuy" ) {
			$(".form-header").text("Быстрый заказ");	
			$("input[name='mailsubject']").val("Быстрый заказ");
			$("select[name='variant']").html("");
			// calc specs
			$.each( $(".tovar"+prodid).find(".smalltext"), function(i,val) {
				$("select[name='variant']").append("<option>"+$(this).html()+"</option>");
			});
			if( $("select[name='variant']").html() == "" ) $(".variant").find('td').addClass('hidden');
		}
		if( type == "ftender" ) {
			$(".form-header").text("Предложить свою цену");	
			$("input[name='mailsubject']").val("Предложение цены");
			$(".question").text("Где Вам была предложена цена ниже, чем наша, на этот товар или аналог (название фирмы или адрес сайта и т. д.)");
			$(".question").click( function() {
				$(this).text("");
			});
		}
		
		// show window
    		var xy = getScrollXY();
    		var elem = $(window);
   		var floatX = ( elem.width() - 450 ) / 2;
    		var floatY =  (elem.height() / 2 - 200);// + xy[1] ;
    		$("#form-header").html( name );
    		$("#tovarname").val( name );
    		$("#form-question").css( {'top': floatY,'left':floatX,'z-index':'200' } );
    		$("#form-shadow").dropShadow({left: 10, top: 10, opacity: 0.2, blur: 0});
	}

//==== ПЕЧАТЬ ДИВА
	function printThis(id){
		str=document.getElementById(id).innerHTML
		newwin=window.open('','printwin','left=100,top=100,width=800,height=600')
		newwin.document.write('<HTML>\n<HEAD>\n')
		newwin.document.write('<TITLE>Print Page</TITLE>\n')
		newwin.document.write('<script>\n')
		newwin.document.write('function chkstate(){\n')
		newwin.document.write('if(document.readyState=="complete"){\n')
		newwin.document.write('window.close()\n')
		newwin.document.write('}\n')
		newwin.document.write('else{\n')
		newwin.document.write('setTimeout("chkstate()",2000)\n')
		newwin.document.write('}\n')
		newwin.document.write('}\n')
		newwin.document.write('function print_win(){\n')
		newwin.document.write('window.print();\n')
		newwin.document.write('chkstate();\n')
		newwin.document.write('}\n')
		newwin.document.write('<\/script>\n')
		newwin.document.write('</HEAD>\n')
		newwin.document.write('<BODY onload="print_win()">\n')
		newwin.document.write(str)
		newwin.document.write('</BODY>\n')
		newwin.document.write('</HTML>\n')
		newwin.document.close()
	}

 //==== управление формой
	function setform( name, value, checked, mess ){
		if( mess) alert(mess);
		if( checked ) {
			$("*[name='"+name+"']").attr('checked','checked');
			return;
		}
		$("*[name='"+name+"']").val(value);
		return;
	}

 //==== создание уникального массива
	function unique(arrayName)  {
                var newArray=new Array();
                label:for(var i=0; i<arrayName.length;i++ )
                {  
                    for(var j=0; j<newArray.length;j++ )
                    {
                        if(newArray[j]==arrayName[i]) 
                            continue label;
                    }
                    newArray[newArray.length] = arrayName[i];
                }
               return newArray;
	}

	function closeForm() {
		var $f = $(".showForm");
		$f.css({visibility: 'hidden'});
	}




