var IsIE = (window.navigator.appName.toLowerCase().indexOf('microsoft') != -1) ? true : false;
var isIE_OLD = (/MSIE (5\.5|6).+Win/.test(navigator.userAgent));
var IE_Ver = (window.navigator.appVersion.toLowerCase().indexOf('msie 7')!=-1)?7:6;
var RND=parseInt(Math.random()*100000);
var cat_cur_color="#CC0000";
var cat_cur_bgcolor="";
var	s_ch='';
var ShopLogin = ''; 
var pathID = new Array();

function myAddFavorite(url) {
    var city = "";
    if (url=="http://www.kns.ru")
        city = "digital solutions";
    if (url=="http://www.knsneva.ru")
        city = "Санкт-Петербург";
    if (url=="http://www.knsvolga.ru")
        city = "Волгоград";
    if (url=="http://www.knsburg.ru")
        city = "Екатеринбург";
    if (url=="http://www.knskrasnodar.ru")
        city = "Краснодар";
    if (url=="http://www.knssibir.ru")
        city = "Новосибирск";
    if (url=="http://www.knsgrad.ru")
        city = "Нижний Новгород";
    if (url=="http://www.knsrostov.ru")
        city = "Ростов-на-Дону";
    if (url=="http://www.knssamara.ru")
        city = "Самара";
    if (url=="http://www.knssochi.ru")
        city = "Сочи";
    if (url=="http://www.knsural.ru")
        city = "Челябинск";
    if (url=="http://www.knsrussia.ru")
        city = "другие города";
    if (city!="")
        window.external.addFavorite(url, 'KNS ' + city + ' - весь спектр компьютерного оборудования');
    else
	    alert("myAddFavorite: неизвестный url=" + url);
}


function close_basket() {
    var f = parent.document.getElementById("fr_bask_id");
    if (f != null) f.style.display = "none";
}

function keypress(event, obj)
{
    if ((event.ctrlKey) && ((event.keyCode == 0xA) || (event.keyCode == 0xD)))
    {
		var str = getSelectionText();
		if (str!='') {
		    show_fr(400, 300, "fr_bask", "/error_send.aspx?url=" + document.location + "&text=" + str);
		}
    }
}

// быстрый заказ
function QuickOrder(idgoods, price) {
    //if (fr_obj == null) return false;
    fr_obj = new FrameObj("fr_main", 520, 380, "Быстрый заказ", false);
    return fr_obj.Show('/qorder.aspx?idg=' + idgoods + "&price=" + price, "Быстрый заказ");
}

function show_fr(width, height, className, url) {
    //fr_obj = new FrameObj("fr_main", width, height, "Диалоговое окно", false, className);
    //return fr_obj.Show(url, "Диалоговое окно");

    var _fr_div = document.getElementById("fr_bask_id");
    if (fr_bask != null && _fr_div != null) {
        fr_bask.document.location = "about:blank";
        if (className != null && className != "") {
            _fr_div.setAttribute("className", className);
            _fr_div.className = className;
        }
        var p_top = (window.screen.height - height - 200) / 2;
        var p_left = (window.screen.width - width) / 2;

        fr_bask.document.location = url;

        _fr_div.style.width = width + "px";
        _fr_div.style.height = height + "px";

        _fr_div.style.top = p_top + "px";
        _fr_div.style.left = p_left + "px";

        _fr_div.style.display = "block";
        //alert("show_fr width = " + width + ", height = " + height);
    }
    return false;
}


function show_call_send() {
    //show_fr(400, 220, "fr_call_send", "/call_send.aspx?url=" + document.location);
    show_fr(400, 320, "fr_call_send", "/call_send.aspx?url=" + document.location);
}
function show_call_send10() {
    show_fr(400, 320, "fr_call_send", "/call_send10.aspx?status=10&url=" + document.location);
}

function getSelectionText() {
	var str = "";
	if (document.getSelection) 
	{
		str = document.getSelection();
	} 
	else if (document.selection && document.selection.createRange) 
	{
		range = document.selection.createRange();
		str = range.text;
	} 
	return str;
}

/*
function set_radio(str,V){
var rez;
rez = str.substring(1,V);
	return rez;
	}
*/

function show_img(width,height,s_url){
	var imgnwin=window.open(s_url,"imgswin","resizable=yes,scrollbars=yes,toolbar=yes,location=no,directoties=no,status=no,menubar=no,width="+width+",height="+height);
}

function show_win(width,height,s_url){
	var p_top=(window.screen.height-height)/2, p_left=(window.screen.width-width)/2;
	var win=window.open(s_url,"imgswin","resizable=yes,scrollbars=yes,toolbar=no,location=no,directoties=no,status=no,menubar=no,width="+width+",height="+height+",top="+p_top+",left="+p_left);
	win.focus();
}

function show_winName(width,height,s_url,winname){
	var p_top=(window.screen.height-height)/2, p_left=(window.screen.width-width)/2;
	var win=window.open(s_url,winname,"resizable=yes,scrollbars=yes,toolbar=no,location=no,directoties=no,status=no,menubar=no,width="+width+",height="+height+",top="+p_top+",left="+p_left);
	win.focus();
}

var win_imggoods=null;
function show_goods_img(goods_name){
	var height=520, width=520;
	if (win_imggoods!=null) win_imggoods.close();
	if (ImgGoodsBig!='') {
		var p_top=(window.screen.height-height)/2, p_left=(window.screen.width-width)/2;	
		win_imggoods=window.open(null,"win_imggoods","resizable=yes,scrollbars=yes,toolbar=no,location=no,directoties=no,status=no,menubar=no,width="+width+",height="+height+",top="+p_top+",left="+p_left);
		win_imggoods.focus();
		win_imggoods.document.open();
		win_imggoods.document.write('<html><head><title>Изображение '+goods_name+'</title></head><body style="padding:0px;margin:0px;text-align:center;vertical-align:center;"><img src="'+ImgGoodsBig+'" width=500/></body></html>');
	}
}

function goods_img_load(obj_img, type){
	if (obj_img!=null && obj_img.src!=null && obj_img.src=="") 
	{
		goods_img_set(obj_img, type);
	}
}

function goods_img_error(obj_img, type){
	if (obj_img!=null) 
	{
		goods_img_set(obj_img, type);
	}
}

function goods_img_set(obj_img, type){
	var img_rubric = document.getElementById("img_rub");
	
	if (img_rubric!=null && img_rubric.src!="" && img_rubric.src.indexOf("i/0.gif")==-1
		&& type!=1) 
		obj_img.src = "/linkpics/i/null.gif";//img_rubric.src;
	else 
		obj_img.src="/linkpics/i/null.gif";
}

var ImgGoodsBig = '';
function set_img(id_src,img_url_small,img_url_big){
	var obj = document.getElementById(id_src);
	if (obj!=null && obj.src!=null && img_url_small!='') {
		obj.src=img_url_small;
	}
	if (img_url_big!='') { ImgGoodsBig = img_url_big; }
	else ImgGoodsBig = img_url_small;
}

function show_print(s_url){
	var height=520, width=520;
	if (win_imggoods!=null) win_imggoods.close();
	var p_top=(window.screen.height-height)/2, p_left=(window.screen.width-width)/2;	
	win_imggoods=window.open(s_url,"win_imggoods","resizable=yes,scrollbars=yes,toolbar=yes,location=no,directoties=no,status=no,menubar=no,width="+width+",height="+height+",top="+p_top+",left="+p_left);
	win_imggoods.focus();
}


function active_win(surl){
	window.opener.document.location=surl;
}




function add_bask_img(idcat,idgoods,url){
	str_url="";
	if (url != null) str_url = url;
	var styleClass = "fr_bask3";
	document.write("<a href='#' onclick='return show_fr(400, 135, \"" + styleClass + "\", \"" + str_url + "/basket_add.aspx?idc=" + idcat + "&idg=" + idgoods + "&c=addbask&ctype=showbask&r=" + RND + "\");'><img src='/i/basket.gif' width=21 height=17 border=0 alt='в корзину' align='absmiddle' class='g_bask_img'></a>");
}
function add_bask_img_newPic(idcat, idgoods, url) {
    str_url = "";
    if (url != null) str_url = url;
    var styleClass = "fr_bask3";
    document.write("<a href='#' onclick='return show_fr(400, 135, \"" + styleClass + "\", \"" + str_url + "/basket_add.aspx?idc=" + idcat + "&idg=" + idgoods + "&c=addbask&ctype=showbask&r=" + RND + "\");'><img src='/i/basket.jpg' width='16' height='17' align='right' alt='в корзину' /></a>");
}
function add_bask_img_newPic2(idcat, idgoods, url) {
    str_url = "";
    if (url != null) str_url = url;
    var styleClass = "fr_bask3";
    document.write("<a href='#' onclick='return show_fr(400, 135, \"" + styleClass + "\", \"" + str_url + "/basket_add.aspx?idc=" + idcat + "&idg=" + idgoods + "&c=addbask&ctype=showbask&r=" + RND + "\");'><img src='/i/basket2.jpg' width='40' height='33' align='right' alt='в корзину' /></a>");
}

function add_bask_imgSpec(idcat,idgoods,url){
	str_url="";
	if (url!=null) str_url=url;
	var styleClass = "fr_bask3";
	document.write("<a href='#' onclick='return show_fr(400, 135, \"" + styleClass + "\", \"" + str_url + "/basket_add.aspx?idc=" + idcat + "&idg=" + idgoods + "&c=addbask&ctype=showbask&r=" + RND + "\");'><img src='/i/buy_spec.gif' width=146 height=48 border=0 alt='в корзину' align='absmiddle' class='g_bask_img'></a>");
}

function add_bask_imgSpec2(idcat, idgoods, url) {
    str_url = "";
    if (url != null) str_url = url;
    var styleClass = "fr_bask3";
    document.write("<a href='#' onclick='return show_fr(400, 135, \"" + styleClass + "\", \"" + str_url + "/basket_add2.aspx?idc=" + idcat + "&idg=" + idgoods + "&c=addbask&ctype=showbask&r=" + RND + "\");'><img src='/i/buy_spec.gif' width=146 height=48 border=0 alt='в корзину' align='absmiddle' class='g_bask_img'></a>");
}

function add_bask_img2(idcat,idgoods,url,status,price){
    var img_baskST = "", str_url = "";
	if (url!=null) str_url=url;
	var styleClass = "fr_bask3";

	var img_bask = "/i/buy0.gif";    // "/i/buy.gif";
	if (status != null && status > -20) {
	    img_bask = "/i/buy_analog.gif";
	}
	if (status != null && status >= -15) {
	    img_bask = "/i/buy_analog10.gif";
	}
	
	if (status != null && status == -10) {  // нет в наличии более 30 дней
	    document.write("<a href='javascript:show_call_send10();'><img src='" + img_bask + "' width=146 height=48 border=0 alt='заказать звонок' align='absmiddle' class='g_bask_img'></a>");
	}
	else if (status != null && status == -15) {  // нет в наличии в Москве
	    document.write("<a href='javascript:show_call_send10();'><img src='" + img_bask + "' width=146 height=48 border=0 alt='заказать звонок' align='absmiddle' class='g_bask_img'></a>");
	}
	else {  // рисуем нормальную корзину

	    img_baskST += "Быстрый заказ";

        document.write("<a href='#' class='ano_' onclick='return QuickOrder(" + idgoods + ", \"" + price + "\")'>");
            document.write("<div class=d1><div class=d2>" + img_baskST + "</div></div>");
            document.write("</a>");

            if (status != null && status <= -20) {
                if (ShopLogin == "knsnew")
                    document.write("<div class=text style='text-align:center; margin:5px 0px 10px 2px;'><a href='#' onclick='return show_fr(400, 135, \"" + styleClass + "\", \"" + str_url + "/basket_add.aspx?idc=" + idcat + "&idg=" + idgoods + "&c=addbask&ctype=showbask&r=" + RND + "\");' style='font-size:10px; display:block; white-space:nowrap; font-size:14px;'>Добавить в корзину</a><small style='display:block; font-size:9px; white-space:nowrap; margin-top:5px;'>кредит онлайн, оплата Visa/Mastercard,<br> доставка по России, Белоруссии и Казахстану</small></div>");
    	        else
    	            document.write("<div class=text style='text-align:center; margin:5px 0px 10px 2px;'><a href='#' onclick='return show_fr(400, 135, \"" + styleClass + "\", \"" + str_url + "/basket_add.aspx?idc=" + idcat + "&idg=" + idgoods + "&c=addbask&ctype=showbask&r=" + RND + "\");' style='font-size:10px; display:block; white-space:nowrap; font-size:14px;'>Добавить в корзину</a><small style='display:block; font-size:9px; white-space:nowrap; margin-top:5px;'>оплата Visa/Mastercard</small></div>");
    	    }
	} 
}

function add_bask_img_text(idcat,idgoods,url){
    var styleClass = "fr_bask3";
    document.write("<a href='#' onclick='return show_fr(400, 135, \"" + styleClass + "\", \"" + str_url + "/basket_add.aspx?idc=" + idcat + "&idg=" + idgoods + "&c=addbask&ctype=showbask&r=" + RND + "\");' class=bask_img_text><img src='/i/bask_goods.gif' width=21 height=17 border=0 alt='в корзину' align='absmiddle' class='g_bask_img'> в корзину</a>");
}

function add_bask_text(idcat,idgoods,url){
    var styleClass = "fr_bask3";
    document.write("<a href='#' onclick='return show_fr(400, 135, \"" + styleClass + "\", \"" + str_url + "/basket_add.aspx?idc=" + idcat + "&idg=" + idgoods + "&c=addbask&ctype=showbask&r=" + RND + "\");' class=bask_img_text>выбрать в заказ</a>");
}

function add_bask_text2(idcat,idgoods,url){
	var str_url="";
	if (url!=null) str_url=url;
	var styleClass = "fr_bask3";
	document.write("<a href='#' onclick='return show_fr(400, 135, \"" + styleClass + "\", \"" + str_url + "/basket_add.aspx?idc=" + idcat + "&idg=" + idgoods + "&c=addbask&ctype=showbask&r=" + RND + "\");' class=bask_img_text>");
}


function get_selected(p){
	if (p==null) return "";
	for (i=0; i < p.options.length; i++) {
		if (p.options[i].selected) { return p.options[i].value; }
	}
	return "";
}
function set_selected(p,v){
	if (p==null) return;
	for (i=0; i < p.options.length; i++) {
		if (p.options[i].value==v) { p.options[i].selected=true; break; }
	}
}

function set_radio(p,v){
	for (i=0; i < p.length; i++) {
		if (p[i].value==v) { p[i].checked=true; break; }
	}
}

function set_checked(p,v){
	if (p.value==v) p.checked=true; 
}

function show_parent_div(div_par){
    var IDParentElement="", NextParentElement="";
		var obj=null; 
		var obj1=null;
    if (document.getElementById(div_par)!=null)
    {
			obj1=document.getElementById(div_par);
			for(var i=0; i<10; i++) {
				obj=obj1;
				if (obj!=null) {
					if (obj.id!="" && obj.style.display!="block") {
						obj.style.display="block";
					}
				}
				else break;
				obj1=eval("obj.parentElement");
			}
		}
}

function ShowAsDeleted(div_par)
{
    MakeBgColor4TagName("TR", div_par, "#AAAAAA");
    var obj=document.getElementById(div_par);
    var col=null;
    if (obj!=null)
    {  
		if (IsIE) col=obj.children;
		else col = obj.childNodes;
		for(var i=0; i<col.length; i++)
		{
    		if (col[i].tagName=="A")
    		{
                changeText(col[i], "Отображать на сайте");
                break;
    		}
		}
    }
}

function MakeBgColor4TagName(TagName, div_par, bgcl)
{
    var i=0;
	var obj=null;
    var obj1=document.getElementById(div_par);
    while (obj1!=null && i<10)
    {
		obj=obj1;
		//alert("1="+obj.tagName);
		obj.style.backgroundColor=bgcl;
		if (obj.tagName==TagName)
		{
			break;
		}
	    i++;
		if (IsIE) obj1=eval("obj.parentElement");
		else obj1=eval("obj.parentNode");
	}
}


function show_divTR(id_cur){
	var div_set=null;
	div_set=document.getElementById(id_cur);
	if (div_set!=null) {
	    if (div_set.style.display == "")
		    div_set.style.display="none";
		else div_set.style.display="";
	}
}

function show_div(id_cur) {
    var div_set = null;
    div_set = document.getElementById(id_cur);
    if (div_set != null) {
        if (div_set.style.display == "block")
            div_set.style.display = "none";
        else div_set.style.display = "block";
    }
}

function show_divMODE(id_cur, mode){
	var div_set=null;
	div_set=document.getElementById(id_cur);
	if (div_set!=null)
		div_set.style.display=mode;
}


function show_cat(id_cur){
	var div_set = document.getElementById(id_cur);
	var obj_link = document.getElementById(id_cur+"_a");
	var obj_ico = document.getElementById(id_cur+"_ico");
	if (div_set!=null) {
		if (div_set.style.display=="block") {
			div_set.style.display="none";
			/*
			if ( obj_link!=null )
			{
				obj_link.setAttribute("className","cat0_off");
				obj_link.className = "cat0_off";
			}
			*/
			if (obj_ico!=null && obj_ico.src!=null)
			{
				obj_ico.src = "/i/ic_plus.gif"
			}
		}
		else {	
			div_set.style.display="block";
			/*
			if ( obj_link!=null )
			{
				obj_link.setAttribute("className","cat0_on");
				obj_link.className = "cat0_on";
			}
			*/
			if (obj_ico!=null && obj_ico.src!=null)
			{
				obj_ico.src = "/i/ic_minus.gif"
			}
		}
	}
	return false;
}


function show_parent_div(div_par){
    var IDParentElement="", NextParentElement="";
		var obj=null; 
		var obj1=document.getElementById(div_par);


		if (obj1 != null)
    {
			for(var i=0; i<10; i++) {
				obj=obj1;

				if (obj!=null) {
					if (obj.id!="" && obj.style.display!="block") {
						obj.style.display="block";
					}
					//if ( obj.id.indexOf('cat')!=-1 && cat_cur_bgcolor!="" ) obj.style.backgroundColor = cat_cur_bgcolor;
					if ( cat_cur_color!="" && document.getElementById(obj.id+'_a')!=null ) 
						document.getElementById(obj.id+'_a').style.color = cat_cur_color;
					obj_ico = null;
					if ( (obj_ico=document.getElementById(obj.id+'_ico'))!=null && obj_ico.src!=null ) 
						obj_ico.src = "/i/ic_minus.gif";

				}
				else break;
				if (IsIE) obj1=eval("obj.parentElement");
				else obj1=eval("obj.parentNode");
				//parentNode 
			}// end for
		}
		else {
			obj1=document.getElementById(div_par+'_a');
			if ( cat_cur_color!="" && obj1!=null ) obj1.style.color = cat_cur_color;
		}
}

CurCurse='1.0';


function normalize(price)
{	var pr, str;
	pr=parseInt(Math.round(price*100));
	str = new String(pr);
	pr="";
	if (str.length>2)
		pr += str.substring(0, str.length-2);
	else
		pr += "0";
	pr += ".";
	if (str.length>2)
		pr += str.substring(str.length-2, str.length);
	else
	{	if (str.length==1)
			pr += "0";
		pr += str;
	}
	return pr;
}

function price_alt(in_price,in_usd,in_rur){
	if (in_price=='' || (in_usd=='' && in_rur=='')) return;
	var normal_price=parseFloat("0"+in_price);
	if (in_usd!='') { document.write( normalize(normal_price*CurCurse)+" руб." ); return; } // если цена товара в USD, то пересчитаем в рублях и отобразим альтернативную цену
	if (in_rur!='') { document.write( normalize(normal_price/CurCurse)+" $" ); return; } // если цена товара в USD, то пересчитаем в рублях и отобразим альтернативную цену
}

function price_alt2(in_price){
CurValuteFlag='2'; // 0 - не установлен, 1-доллары, 2-рубли.
	var normal_price=parseFloat("0"+in_price);
	if (CurValuteFlag=='1') { document.write( normalize(normal_price*CurCurse)+" руб." ); return; } // если цена товара в USD, то пересчитаем в рублях и отобразим альтернативную цену
	if (CurValuteFlag=='2') { document.write( normalize(normal_price/CurCurse)+" $" ); return; } // если цена товара в USD, то пересчитаем в рублях и отобразим альтернативную цену
}

function ico_img(graph)
{
	if (graph == '/i/null.gif') document.write('<img src="/i/ico_noimg.gif" width=30 height=30 border=0 alt="Изображение отсутствует">');
	else if (graph == '/i/noimage.gif') document.write('<img src="/i/ico_noimg.gif" width=30 height=30 border=0 alt="Изображение отсутствует">');
	else document.write('<img src="/i/ico_img.gif" width=30 height=30 border=0 alt="Описание с изображением">')
}

function CreateCookie(name,value,ex_date){
	var today=new Date();
	today.setDate(today.getDate()+ex_date);
	document.cookie=name+"="+value+"; expires="+today.toGMTString()+"; path=/;";
}

function CreateTmpCookie(name,value){
	document.cookie=name+"="+value+"; path=/;";
}

function RemoveCookie(name){
	CreateCookie(name,"",-1);
}

function ViewCompare(idcat, idgoods){
	document.write("<a href='javascript:void(0);' onclick='retval=SetCompare("+idcat+","+idgoods+"); fr_bask.document.location=\"/compare_set.aspx?idc="+idcat+"&idg="+idgoods+"&r="+RND+"\"; if (retval) document.getElementById(\"fr_bask_id\").style.display=\"block\";'>К сравнению</a>");
}

function ViewCompare2(idcat, idgoods){
	document.write("<a href='javascript:void(0);' onclick='retval=SetCompare("+idcat+","+idgoods+"); fr_bask.document.location=\"/compare_set.aspx?idc="+idcat+"&idg="+idgoods+"&r="+RND+"\"; if (retval) document.getElementById(\"fr_bask_id\").style.display=\"block\";'>");
}

function ViewCompareCheck(idcat,idgoods, IsChecked){
	document.write("<input id='compare"+idgoods+"' name='compare"+idgoods+"' type='checkbox' "+IsChecked+" onclick='fr_bask.document.location=\"/compare_set.aspx?idc="+idcat+"&idg="+idgoods+"&r="+RND+"\"; if (this.checked) document.getElementById(\"fr_bask_id\").style.display=\"block\";'/>");
}




function SetCompare(idc, idg){
	obj_check = document.getElementById("compare"+idg);
	retVal = false;
	if (obj_check != null)
	{
		if (!obj_check.checked) obj_check.checked = true;
		else obj_check.checked = false;
		retVal = obj_check.checked;
	}
	return retVal;
}

function ClearCompare(idg){
	obj_check = document.getElementById("compare"+idg);
	if (obj_check != null) obj_check.checked = false;
}

function SpellCompare(obj){
	var str="";
	var start_IDG=0;
	var end_IDG=-1;
	var break_point=0;
	var flag;
	while (start_IDG!=-1){
		start_IDG=document.cookie.indexOf("idg",start_IDG);
		end_IDG=document.cookie.indexOf("=",start_IDG);
		if (start_IDG==-1 || end_IDG==-1) break;
		idg=unescape(document.cookie.substring(start_IDG+3,end_IDG));
		start_IDG=end_IDG;
		flag=false;
		//alert("idg="+idg+" , obj.idg.length="+obj.idg.length);
		if (isNaN(obj.idg.length)) { 
			if (obj.idg.value==idg) { obj.idg.checked=true; flag=true; }
		}
		else {
			for (i=0;i<obj.idg.length;i++) {
				if (obj.idg[i].value==idg) { obj.idg[i].checked=true; flag=true; break; }
			}
		}
		//alert("flag="+flag);
		if (!flag) { 
			//alert("!!! idg="+idg);
			str+="<input type=hidden name=idg value="+idg+">"
		}
		break_point++; if (break_point>10) break;
	}
	return str;
}

function SearchScroll(FileAction,pgsize,numpage,stype,str_url){
	var s1=new RegExp("pgsize=.&|pgsize=..&|pgsize=...&", "gi");
	var s2=new RegExp("page=.&|page=..&|page=...&", "gi");
	var s3=new RegExp("stype=.&|stype=..&|stype=...&", "gi");
	str_url=str_url.replace(s1,''); str_url=str_url.replace(s2,''); str_url=str_url.replace(s3,'');
	document.location = FileAction + '?c=search&pgsize='+pgsize + '&page='+numpage +'&stype='+stype + '&'+str_url;
}

function logoff(file_templ,idc,stype,page,idr,idt,idn){
	RemoveCookie("login");
	RemoveCookie("pass");
	RemoveCookie("userid");
	document.location='/'+ file_templ +'?idc='+idc +'&stype='+stype +'&page='+page +'&idr='+idr +'&idt='+idt +'&idn='+idn +'&r='+RND;
	//location.reload();
}

function set_url(str_url){
    if (str_url.indexOf("?")>0)
        parent.document.location=str_url+'&r='+RND;
	else
	    parent.document.location=str_url+'?r='+RND;
	return false;
}

function gotoB() {
    document.location = "http://knsblog.ru";
    return true;
}


function GetMianForm() {
	var theForm = document.forms['aspnetForm'];
	if (!theForm) {
			theForm = document.aspnetForm;
	}
	if (!theForm.onsubmit || (theForm.onsubmit() != false)) return theForm;
	else return null;
}

function SetPostBack(command, command_type) {
    var theForm = GetMianForm();
    if (theForm != null) {
        if (theForm.c != null) theForm.c.value = command;
        if (theForm.ctype != null) theForm.ctype.value = command_type;
    }
}

function PostBack(command, command_type) {
	var theForm = GetMianForm();
	if (theForm != null) {
			if (theForm.c!=null) theForm.c.value = command;
			if (theForm.ctype!=null) theForm.ctype.value = command_type;
			if (theForm.IsPostForm!=null) theForm.IsPostForm.value = 1;
			theForm.submit();
	}
	return false;
}

/// установить шаг для корзины
function SetBasketStep(step_val, doSubmit) {
    var theForm = GetMianForm();
    var step = document.getElementById("step");
    if (theForm != null && step != null) {
        step.value = step_val;
        if (theForm.IsPostForm != null) theForm.IsPostForm.value = 1;
        if (doSubmit) theForm.submit();
    }
    return false;
}
/// установить Paymode для корзины
function SetBasketPaymode(obj) {
    //alert("name='" + obj.name + "', id='" + obj.id + "'");
    var val = get_selected(document.getElementById(obj.id));
    document.getElementById("paymode_id").value = val;
    CreateTmpCookie("paymode_id", val);
    //alert("paymode_id = " + val);
    var theForm = GetMianForm();
    if (theForm != null) {
        theForm.submit();
    }
}
/// установить Shippmode для корзины
function SetBasketShippmode(obj) {
    //alert("name='" + obj.name + "', id='" + obj.id + "'");
    var val = get_selected(document.getElementById(obj.id));
    document.getElementById("shippmode_id").value = val;
    CreateTmpCookie("shippmode_id", val);
    //alert("shippmode_id = " + val);
    var theForm = GetMianForm();
    if (theForm != null) {
        theForm.submit();
    }
}

function SetDefaultButton(event, target, action) {
    if (event.keyCode == 13) {
        var src = event.srcElement || event.target;
        if (!src || (src.tagName.toLowerCase() != "textarea")) {
            var defaultButton;
            if (!IsIE) {
                defaultButton = document.getElementById(target);
            }
            else {
                defaultButton = document.all[target];
            }
            if (defaultButton && typeof (defaultButton.click) != "undefined") {

                //SetAction(action);
                //SetPostСommand(command);

                defaultButton.click();
                event.cancelBubble = true;
                if (event.stopPropagation) event.stopPropagation();
                return false;
            }
        }
    }
    return true;
}

function g_sort(s_name_sort){
	var theForm = GetMianForm();
	if (theForm != null) {
			if (theForm.GoodsSort!=null) theForm.GoodsSort.value = s_name_sort;
			if (theForm.IsPostForm!=null) theForm.IsPostForm.value = 1;
			theForm.submit();
	}
	return false;
}

function g_scroll(pgn,IsPostForm){
	var theForm = GetMianForm();
	if (theForm != null) {
			if (theForm.pgn!=null) theForm.pgn.value = pgn;
			theForm.submit();
	}
	return (IsPostForm=="1")?false:true;
}

function changeText(el,text) {
	//alert(el.firstChild.nodeValue);
  //if (IsIE && IE_Ver<7) el.innerText=text;
	//else {
		if (el.firstChild) el.firstChild.nodeValue=text;
		else el.appendChild(document.createTextNode(text));
	//}
}

function search_action(){
    var theForm = GetMianForm();
    var search_info = document.getElementById("search_info");

    if (theForm != null && ((theForm.s_Word != null && theForm.s_Word.value != '') || (theForm.s_GoodsID != null && theForm.s_GoodsID.value != ''))) {
        if (theForm.s_Word != null && theForm.s_GoodsID != null ) {
            if (theForm.s_Word.value != '' && theForm.s_GoodsID.value != '') {
                theForm.s_Word.value = '';
            }
        }
        if (theForm.c!=null) theForm.c.value = "search";
        if (theForm.IsPostForm!=null) theForm.IsPostForm.value = 1;
        if (theForm.__VIEWSTATE!=null) theForm.__VIEWSTATE.value = '';
        theForm.action='/search.aspx';
        if (search_info!=null) search_info.style.display="block";
        theForm.submit();
    }
    return false;
}

function vote_action(){
	var theForm = GetMianForm();
	if (theForm != null && theForm.c!=null) {
			if (theForm.c!=null) theForm.c.value = "addquest";
			if (theForm.IsPostForm!=null) theForm.IsPostForm.value = 1;
			if (theForm.__VIEWSTATE!=null) theForm.__VIEWSTATE.value = '';
			theForm.submit();
	}
	return false;
}

function search_keypress(event)
{
	if((event.keyCode == 0xA)||(event.keyCode == 0xD))
    {
		search_action();
    }
}


function set_message(id_div,text){
	var obj = document.getElementById(id_div);
	if (obj!=null) changeText(obj,text);
}

function CheckPayCondition(obj_Paymode, BasketSummUSD, BasketSumRUR){
	var PayConditionCreditPersonal = document.getElementById("PayConditionCreditPersonal");
	var PayConditionCreditOrg = document.getElementById("PayConditionCreditOrg");

	if (obj_Paymode!=null && PayConditionCreditPersonal!=null && PayConditionCreditOrg!=null) {
		PayConditionCreditOrg.style.display="none";
		PayConditionCreditPersonal.style.display="none";
		if (obj_Paymode.value==300 && BasketSummRUR<3000){
			PayConditionCreditPersonal.style.display="block";
		}
		else if (obj_Paymode.value==400 && BasketSummUSD<5000){
			PayConditionCreditOrg.style.display="block";
		}
	}
}

function mySelect(fileName, ObjectID2Paste, winName){
	var obj = document.getElementById(ObjectID2Paste);
	if (obj==null)
    {   
        alert("Не удается найти объект " + ObjectID2Paste);
        return false;
    }
    show_winName(800, 600, fileName + "?id=" + ObjectID2Paste, winName);
}

// функция для просмотра картинки в отдельном окне
function viewimageJS(myfile, mydirect, mypath)
{	var tmp, i;
	myfile = new String(myfile);
	if (myfile!="")
	{	if ((myfile.substring(0,7)!="http://") && (mydirect==0)) // относительная адресация
		{	tmp = new String(mypath);
			i = tmp.lastIndexOf("/");
			if (i>-1)
				tmp = tmp.substring(0, i-1);
			else
				tmp = "";
			if (tmp.substring(0, 1)=="/")
				myfile = "http://" + tmp.substring(0, tmp.lastIndexOf("/")-1) + myfile;
			else
				myfile = "http://" + tmp.substring(0, tmp.lastIndexOf("/")) + myfile;
		}
		alert(myfile);
		var iwin = window.open(myfile, "iwin", "resizable=yes,scrollbars=yes,toolbar=no,location=no,directoties=no,status=no,menubar=no,width=400,height=400");
		if (iwin!=null)
			iwin.focus();
	}
}

var row=1;
function s_tr(){if (row==1) { document.write("<tr bgcolor=#EDF1F6 valign=top>"); row=2; } else { document.write("<tr valign=top>"); row=1; }}

var cols=1;
function s_cols_1(num_cols){//start
	if (cols > num_cols) cols=1;
	if (cols==1) { document.write("<tr valign=top><td width="+(100/num_cols)+"%  style='padding-right:10;'>"); } 
	else { document.write("<td style='padding-left:20;'>"); }
}
function s_cols_2(num_cols){//end
	if ( cols==num_cols ) { document.write("</td></tr>"); } 
	else { document.write("</td>"); }
	cols++;
}
function s_cols_final(num_cols){//end
	if (cols<=num_cols) {
		for (i=cols; i<=num_cols; i++) {
			document.write("<td width="+(100/num_cols)+"%>&nbsp;</td>");
		}// end for
		document.write("</tr>");
	}// end if
}

function w_send(){
	document.write('<input type=hidden name=s_ch value=\"'+s_ch+'\">');
	document.write('<input type=hidden name=s_opin value=\"aqijeydecdx\">');
}

function spec_ico(ShopLogin, SpecID, RubricID, GoodsID) {
    if (SpecID != 0) {
        if (ShopLogin == "knsnew")
            document.write("<div style=\"position:relative; float:left;\"><a href=\"/vcd-" + RubricID + "-1-" + GoodsID + "/goodsinfo.html\"><img src=\"/i/spec_" + SpecID + ".png\" width=\"156\" height=\"122\" alt=\"Лучшая цена\" style=\"position:absolute; top:30px; left:0px;\" class=\"iePNG\" onerror=\"this.src='/i/0.gif'\" border=\"0\"/></a></div>");
        else
            document.write("<div style=\"position:relative; float:left;\"><a href=\"/vcd-" + RubricID + "-1-" + GoodsID + "/goodsinfo.html\"><img src=\"/i/spec_" + SpecID + ".png\" width=\"156\" height=\"122\" alt=\"Лучшая цена\" style=\"position:absolute; top:5px; left:0px;\" class=\"iePNG\" onerror=\"this.src='/i/0.gif'\" border=\"0\"/></a></div>");
    }
/*
    else {
        SpecID = 2;
        if (RubricID == 345424) {
            if (GoodsID == 0)
                document.write("<div style=\"position:relative; float:left;\"><a href=\"/vcd-" + RubricID + "/catalog.html\"><img src=\"/i/spec_" + SpecID + ".png\" width=\"156\" height=\"122\" alt=\"Лучшая цена\" style=\"position:absolute; top:5px; left:0px;\" class=\"iePNG\" onerror=\"this.src='/i/0.gif'\" border=\"0\"/></a></div>");
            else
                document.write("<div style=\"position:relative; float:left;\"><a href=\"/vcd-" + RubricID + "-1-" + GoodsID + "/goodsinfo.html\"><img src=\"/i/spec_" + SpecID + ".png\" width=\"156\" height=\"122\" alt=\"Лучшая цена\" style=\"position:absolute; top:5px; left:0px;\" class=\"iePNG\" onerror=\"this.src='/i/0.gif'\" border=\"0\"/></a></div>");
        }
    }
*/
}

function spec_ico_def(SpecID, RubricID, GoodsID) {
    if (SpecID != 0)
        document.write("<div style=\"position:relative; float:left;\"><a href=\"/vcd-" + RubricID + "-1-" + GoodsID + "/goodsinfo.html\"><img src=\"/i/spec_" + SpecID + "_s.png\" width=\"82\" height=\"65\" alt=\"Лучшая цена\" style=\"position:absolute; top:-10px; left:-10px;\" class=\"iePNG\" onerror=\"this.src='/i/0.gif'\" border=\"0\"/></a></div>");
}

function spec_ico_s(SpecID, RubricID, GoodsID) {
    if (SpecID != 0)
        document.write("<div style=\"position:relative; float:right;\"><a href=\"/vcd-" + RubricID + "-1-" + GoodsID + "/goodsinfo.html\"><img src=\"/i/spec_" + SpecID + "_s.png\" width=\"82\" height=\"65\" alt=\"Лучшая цена\" style=\"position:absolute; bottom:-10px; right:-20px;\" class=\"iePNG\" onerror=\"this.src='/i/0.gif'\" border=\"0\"/></a></div>");
/*
    else if (RubricID == 345424) {
        SpecID = 2;
        document.write("<div style=\"position:relative; float:left;\"><a href=\"/vcd-" + RubricID + "-1-" + GoodsID + "/goodsinfo.html\"><img src=\"/i/spec_" + SpecID + ".png\" width=\"156\" height=\"122\" alt=\"Лучшая цена\" style=\"position:absolute; top:-70px; left:-50px;\" class=\"iePNG\" onerror=\"this.src='/i/0.gif'\" border=\"0\"/></a></div>");
    }
*/
}

function spec_ico_rub(SpecID) {
    if (SpecID != 0)
        document.write("<div style=\"position:relative; float:right;\"><img src=\"/i/spec_" + SpecID + "_s.png\" width=\"82\" height=\"65\" alt=\"Лучшая цена\" style=\"position:absolute; bottom:-10px; right:-20px;\" class=\"iePNG\" onerror=\"this.src='/i/0.gif'\" border=\"0\"/></div>");
}


function spec_ico_g(SpecID, RubricID, GoodsID) {
    if (SpecID != 0)
        document.write("<div style=\"position:relative; float:left;\"><a href=\"/vcd-" + RubricID + "-1-" + GoodsID + "/goodsinfo.html\"><img src=\"/i/spec_" + SpecID + ".png\" width=\"156\" height=\"122\" alt=\"Лучшая цена\" style=\"position:absolute; top:70px; left:-60px;\" class=\"iePNG\" onerror=\"this.src='/i/0.gif'\" border=\"0\"/></a></div>");
}

function fixPNG(element) {
    //Если браузер 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 = "/i/0.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
        if (src) element.runtimeStyle.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + src + "',sizingMethod='scale')";
  }
}

num_td_sep=1;
function menu_sep1(){
    if (num_td_sep > 1) document.write("<td><div style='height:13px; width:10px; border-right:solid 1px #BFBFBF' /></td><td><div style='width:10px;' /></td>");
	num_td_sep++;
}
function menu_sep2(idt){
	if (idt==117)
		document.write("<td nowrap class=menu_up align=right><noindex><a href='http://knsblog.ru/' target=_blank rel=nofollow>Блог КНС</a></noindex></td>");
}


// *** VIC - информация для просчета стоимости доставки в корзине
var GoodsInfo4Delivery = new Array();   // массив с объектами-товарами для рассчета стоимости доставки
var GoodsInfo4DeliveryIdx = 0;          // текущий индекс активного товара (используется при рассчете)
var GoodsInfo4DeliveryWrongDataGoodsID = 0; // идентификатор товара с ущербными данными для доставки (0 - нет ИД => успех)
var cpcr_TotalCost=0;       // сумарная стоимость доставки

// класс для объекта - товара в корзине 
function GoodsItemInfo4Delivery(GoodsID, Quantity, Length, Width, Height, Weight){
	this.GoodsID=GoodsID;		// идентификатор товара
	this.Quantity=Quantity;     // заказанное количество 
	this.Length=Length;     // длинна (брутто, см)
	this.Width=Width;       // ширина (брутто, см)
	this.Height=Height;     // длинна (высота, см)
	this.Weight=Weight;     // Вес (брутто, кг)
}//end class

// добавление информации по доставке в массив
function addGoodsItemInfo4Delivery(Field_GoodsID, Field_Quantity, Field_Length, Field_Width, Field_Height, Field_Weight)
{
    Field_Quantity = parseFloat(Field_Quantity);
    Field_Length = parseFloat(Field_Length);
    Field_Width = parseFloat(Field_Width);
    Field_Height = parseFloat(Field_Height);
    Field_Weight = parseFloat(Field_Weight);
    if (isNaN(Field_Quantity) || isNaN(Field_Length) || isNaN(Field_Width) 
    || isNaN(Field_Height) || isNaN(Field_Weight))
    {
        GoodsInfo4DeliveryWrongDataGoodsID = Field_GoodsID;
        return;
    }
	GoodsInfo4Delivery[GoodsInfo4Delivery.length] = new GoodsItemInfo4Delivery(Field_GoodsID, Field_Quantity, Field_Length, Field_Width, Field_Height, Field_Weight);
}

function create_wait() {
    var obj = document.getElementById("div_wait");
    if (obj==null){
        var isIE_OLD = (window.navigator.appName.toLowerCase().indexOf('microsoft') != -1) ? true : false;// (/MSIE (5\.5|6).+Win/.test(navigator.userAgent));
        var css_modal = "div_wait";
        var css_msg = "div_wait_msg";
        var style_modal = ' style="height:' + window.screen.height + 'px;"';
        /*
        if (isIE_OLD) {
            css_modal = 'div_wait_OLD';
            css_msg = "div_wait_msg_old";
            style_modal = '';  //'style="width:' + window.screen.width + 'px;"';
        }*/
        document.write('<div id="div_wait" class="' + css_modal + style_modal + '"></div><div id="div_wait_msg" class="' + css_msg + '">Подождите...<br><br><img src="/i/loaderlight.gif"/></div>');
    }
}

function open_wait() {
    var obj = document.getElementById("div_wait");
    if (obj != null) obj.style.visibility = "visible";
    obj = document.getElementById("div_wait_msg");
    if (obj != null) obj.style.visibility = "visible";
}

function close_wait() {
    var obj = document.getElementById("div_wait");
    if (obj != null) obj.style.visibility = "hidden";
    obj = document.getElementById("div_wait_msg");
    if (obj != null) obj.style.visibility = "hidden";
}

function payonline(ido) {
    document.write
    document.write("<iframe style=\"padding:0px; margin:0px; width:150px; height:22px;\" src=\"/payonline.aspx?ido=" + ido + "\" frameborder=\"no\" scrolling=\"no\"></iframe>");
}

// обработка всех чекбоксов удаления в корзине
function ProcessPacksCheckboxes(objCheckbox) {
    var i, st, GoodsID, cmt, chk;
    st = objCheckbox.id;
    st = st.substr(7);
    cmt = document.getElementById("comment" + st);
    if (cmt == null)
        return false;
    if (cmt.value == "")
        return false;
    //alert("objCheckbox.id=" + st);
    
    var checked = objCheckbox.checked;
    var i, st, GoodsID, cmt, chk;
    var arr = document.getElementsByName("idg");
    st = "";
    for (i = 0; i < arr.length; i++) {
        GoodsID = arr[i].value;
        st = st + GoodsID + " ";
        cmt = document.getElementById("comment" + GoodsID);
        if (cmt == null)
            continue;
        if (cmt.value == "")
            continue;
        chk = document.getElementById("idg_del" + GoodsID);
        if (chk == null)
            continue;
        chk.checked = checked;
    }
    //alert(st);    
    
}

function addHandler(object, event, handler) {
    if (object.addEventListener) {
        object.addEventListener(event, handler, false);
    } else if (object.attachEvent) {
        object.attachEvent('on' + event, handler);
    } else alert("addHandler is not supported");
}

function removeHandler(object, event, handler) {
    if (object.removeEventListener) {
        object.removeEventListener(event, handler, false);
    } else if (object.detachEvent) {
        object.detachEvent('on' + event, handler);
    } else alert("removeHandler is not supported");
}

function showExtWWW(mode, RubricID, GoodsID) {
    document.writeln('<noindex><div class="rBlogs">');
    document.write('<a target="_blank" href="http://vkontakte.ru/knsds" title="Мы Вконтакте" rel="nofollow"><img src="/i/vk_1.jpg" border="0" width="18" height="18" alt="Мы Вконтакте" align="left" /></a>');
    document.write('<a target="_blank" href="http://www.facebook.com/pages/KNS-digital-solutions/167060036691043" title="Мы в Facebook" rel="nofollow"><img src="/i/face_1.jpg" border="0" width="18" height="18" alt="Мы в Facebook" align="left" /></a>');
    document.write('<a target="_blank" href="http://twitter.com/KNS_ru" title="Твиттер @KNS_ru" rel="nofollow"><img src="/i/twitt_1.jpg" border="0" width="18" height="18" alt="Твиттер @KNS_ru" align="left" /></a>');
    document.write('<a target="_blank" href="http://knsblog.ru" title="Блог KNS" rel="nofollow"><img src="/i/blog_1.jpg" border="0" width="18" height="18" alt="Блог KNS" align="left" /></a>');
    if (mode == 1) {
        document.write('<a target="_blank" href="/vcd-' + RubricID + '-1-' + GoodsID + '/goodsinfo_print.html" title="Версия для печати" rel="nofollow"><img src="/i/printer.png" border="0" width="18" height="18" alt="Версия для печати" align="left" /></a>');
    }
    document.writeln('</div></noindex>');
}
function GetNumString(num_str) {
    num_str = num_str.toString();
    var parts = num_str.split(".,");
    parts[0] = parts[0].substr(0, parts[0].length % 3) + parts[0].substr(parts[0].length % 3).replace(/(\d{3})/g, ' \$1');
    return parts.join(",");
}

/// удаляет все опции из SELECT
function RemoveAllInSelect(p) {
    p.length = 0;
}
/// добавляет опцию в SELECT
function AddInSelect(oSelect, MyValue, MyText) {
    oSelect.options[oSelect.length] = new Option(MyText, MyValue);
}

function ShowFirstImg(objID) {
    $("#" + objID).click();
    /*
    if (document.getElementById(objID)!=null)
    {
    document.getElementById(objID).click();
    }
    */
}

function urlEncode(str) {

    if (!str || typeof (str) == "undefined") return;
    // Создаем хеш для хранения символов, где ключ - сам символ, 
    // а значение - его шестнадцатеричеый эквивалент 
    var utf8Array = {};

    var i = j = j2 = 0;
    for (i = 0; i <= 255; i++) {
        j = parseInt(i / 16); var j2 = parseInt(i % 16);
        utf8Array[String.fromCharCode(i)] = ('%' + j.toString(16) + j2.toString(16)).toUpperCase();
    }
    // И отдельно проработаем кириллицу 
    var rusAdditional = {
        '_': '%5F', 'А': '%C0', 'Б': '%C1', 'В': '%C2', 'Г': '%C3', 'Д': '%C4', 'Е': '%C5',
        'Ж': '%C6', 'З': '%C7', 'И': '%C8', 'Й': '%C9', 'К': '%CA', 'Л': '%CB', 'М': '%CC',
        'Н': '%CD', 'О': '%CE', 'П': '%CF', 'Р': '%D0', 'С': '%D1', 'Т': '%D2', 'У': '%D3',
        'Ф': '%D4', 'Х': '%D5', 'Ц': '%D6', 'Ч': '%D7', 'Ш': '%D8', 'Щ': '%D9', 'Ъ': '%DA',
        'Ы': '%DB', 'Ь': '%DC', 'Э': '%DD', 'Ю': '%DE', 'Я': '%DF', 'а': '%E0', 'б': '%E1',
        'в': '%E2', 'г': '%E3', 'д': '%E4', 'е': '%E5', 'ж': '%E6', 'з': '%E7', 'и': '%E8',
        'й': '%E9', 'к': '%EA', 'л': '%EB', 'м': '%EC', 'н': '%ED', 'о': '%EE', 'п': '%EF',
        'р': '%F0', 'с': '%F1', 'т': '%F2', 'у': '%F3', 'ф': '%F4', 'х': '%F5', 'ц': '%F6',
        'ч': '%F7', 'ш': '%F8', 'щ': '%F9', 'ъ': '%FA', 'ы': '%FB', 'ь': '%FC', 'э': '%FD',
        'ю': '%FE', 'я': '%FF', 'ё': '%B8', 'Ё': '%A8'
    }
    for (i in rusAdditional) utf8Array[i] = rusAdditional[i];
    // Посимвольно заменяем символы на их шестнадцатиречные эквиваленты 
    var res = "";
    for (i = 0; i < str.length; i++) {
        var simbol = str.substr(i, 1);
        res += typeof utf8Array[simbol] != "undefined" ? utf8Array[simbol] : simbol;
    }
    // Пробелы заменяем на плюсы 
    res = res.replace(/\s/g, "+");
    return res;
}

