var domain = 'http://'+location.host+'/'; 
var imagePrefix='insImage';
var imagePrefixSmall='smallInsImage';
var filePrefix = 'insFile';

function printPage()
{
window.print();
}

function pop_win(url, win, height, width) {
  	var scroll = 'no';
	var top=0, left=0;
	if(width > screen.width-10 || height > screen.height-28)
		scroll = 'yes';
	if(height < screen.height-28)
		top = Math.floor((screen.height - height)/2-14);
	if(width < screen.width-10)
		left = Math.floor((screen.width - width)/2);
	width = Math.min(width, screen.width-10);	
	height = Math.min(height, screen.height-28);
	width+=20;
	height+=10;
  popwin = window.open(url,win,"width="+width+",height="+height+",toolbar=no,resizable=no,scrollbars=yes");
  popwin.focus();
}

function pop_win2(url, win, height, width) {
  	var scroll = 'no';
	var top=0, left=0;
	if(width > screen.width-10 || height > screen.height-28)
		scroll = 'yes';
	if(height < screen.height-28)
		top = Math.floor((screen.height - height)/2-14);
	if(width < screen.width-10)
		left = Math.floor((screen.width - width)/2);
	width = Math.min(width, screen.width-10);	
	height = Math.min(height, screen.height-28);
	width+=20;
	height+=10;
  popwin = window.open(url,win,"width="+width+",height="+height+",toolbar=yes,resizable=no,scrollbars=yes");
  popwin.focus();
}

function pop_win3(url) {
  popwin = window.open(url);
  popwin.focus();
}


function clickButton(e, buttonid){ 
      var bt = document.getElementById(buttonid); 
      if (typeof bt == 'object'){ 
            if(navigator.appName.indexOf("Netscape")>(-1)){ 
                  if (e.keyCode == 13){ 
                        bt.click(); 
                        return false; 
                  } 
            } 
            if (navigator.appName.indexOf("Microsoft Internet Explorer")>(-1)){ 
                  if (event.keyCode == 13){ 
                        bt.click(); 
                        return false; 
                  } 
            } 
      } 
} 

function  GetAboutText()
{
text="";
text=text+"&nbsp;&nbsp;&nbsp;&nbsp;СофтМагазин.Ru - крупнейший интернет-магазин лицензионного программного обеспечения в Рунете!<br>";
text=text+"&nbsp;&nbsp;&nbsp;&nbsp;Всегда в наличии <b>продукты Microsoft</b>: средства разработки, Microsoft Windows XP,";
text=text+"Microsoft Office, а ткаже широкий ассортимент другого лицензионного программного обеспечения, как для крупных предприятий, так и для домашнего пользования: <br>";
text=text+"&nbsp;&nbsp;<b>антивирусы</b>: DrWeb, антивирус Касперского, Norton antivirus, panda, nod32 и др.;<br> ";
text=text+"&nbsp;&nbsp;средства защиты информации, операционные системы, продукты 1C, corel, программы для офиса, лицензионные finereader, autocad, delphi, lingvo, usergate, radmin, adobe photoshop и другие популярные средства разработки, графические пакеты и т.п.  продукты.<br>";
text=text+"&nbsp;&nbsp;&nbsp;&nbsp;У нас работает бесплатная доставка товаров по Москве и России.  Если Вы не нашли интересующий Вас товар на страницах SOFTMAGAZIN.RU -";
text=text+"оставьте заявку. Менеджер отдела продаж обработает Ваш заказ и свяжется с Вами.";
return text;
}

function CloseOrderWindow()
{				
  window.close();	
	//var prevForm=window.opener;
	//if (prevForm)	
	//prevForm.location=prevForm.location;	    	     
	
}

function Anthem_Error(result) {
alert('Anthem_Error was invoked with the following error message: ' + result.error);
}

function SetDefaultLinks()
{		
        var mLinks=document.links;
        for (i = 0; i < mLinks.length; ++i) {
            var urlOld = new String(trim(mLinks[i].href)); //url from link
            var urlOldPart = urlOld.match(/\/m\/\w+$/);
            var urlOldPart2 = urlOld.match(/\/m\/\w+#w+$/);
            if (urlOldPart != null) {
                var urlNew = domain + urlOldPart[0].substring(1); //new url for link
                mLinks[i].href = urlNew;
            } else
                if (urlOldPart2 != null) {
                var urlNew = domain + urlOldPart2[0].substring(1); //new url for link
                mLinks[i].href = urlNew;
            } else {
                var str = new String(trim(mLinks[i].name));
                var nameParts = str.split('_', 2);
                if (nameParts != null && nameParts[0] == filePrefix) {
                    var urlSrc = new String(trim(mLinks[i].href)); //url from file          
                    var fileId = urlSrc.match(/id=\d+/);
                    var urlNew = domain + 'file.ashx?' + fileId; //new url for file
                    mLinks[i].href = urlNew;
                }
            }
        }
}

function SetDefaultImage()
{	
	var mImg=document.images;	
	for (i=0;i<mImg.length;++i)
	{					
		var str=new String(trim(mImg[i].name));
		var nameParts=str.split('_',2);	
		if (nameParts[0]==imagePrefix || nameParts[0]==imagePrefixSmall)
		{		
			var urlSrc= new String(trim(mImg[i].src)); //url from image
			var url=domain+'image.aspx?'; //new url for full image
			var urlSmall=domain+'imagesmall.aspx?';	//new url for miniature								
			var imageId=0; // default imageId
			var width=200; // default width 
			var height=250; // default height
			var linkId=urlSrc.match(/id=\d+/);
			var linkWidth=urlSrc.match(/width=\d+/);		
			var linkHeight=urlSrc.match(/height=\d+/);			
			if (linkId!=null && linkId.length==1)
			{
				var tId=linkId[0].split('=',2);
				if (tId!=null && tId.length==2)
					imageId=tId[1];	
			}
			if (linkWidth!=null && linkWidth.length==1)
			{
				var tWidth=linkWidth[0].split('=',2);
				if (tWidth!=null && tWidth.length==2)
					width=tWidth[1];	
			}	
			if (linkHeight!=null && linkHeight.length==1)
			{
				var tHeight=linkHeight[0].split('=',2);
				if (tHeight!=null && tHeight.length==2)			
					height=tHeight[1];	
			}
			url+='id='+imageId;
			urlSmall+='id='+imageId;
			urlSmall+='&width='+width;		
			urlSmall+='&height='+height;		
			if (nameParts[0]==imagePrefix && urlSrc!=url)
			{						
				mImg[i].src=url;
			}else
			if (nameParts[0]==imagePrefixSmall && urlSrc!=urlSmall)
			{						
				mImg[i].src=urlSmall;	
			}	
		}		
	}
}



function ShowImage(sImgPath, width, height)
{
	var scroll = 'no';
	var top=0, left=0;
	if(width > screen.width-10 || height > screen.height-28)
		scroll = 'yes';
	if(height < screen.height-28)
		top = Math.floor((screen.height - height)/2-14);
	if(width < screen.width-10)
		left = Math.floor((screen.width - width)/2);
	width = Math.min(width, screen.width-10);	
	height = Math.min(height, screen.height-28);
	width+=20;
	height+=25;	
	window.open(domain+'image.aspx?id='+sImgPath,'','scrollbars='+scroll+',resizable=no,width='+width+',height='+height+',left='+left+',top='+top);
} 

function trim(stringToTrim) {
	return stringToTrim.replace(/^\s+|\s+$/g,"");
}

function bookmark(){
    var title="СофтМагазин.РУ"
    var url=domain;

    if (window.sidebar) window.sidebar.addPanel(title, url,"");

    else if( window.opera && window.print )
    {
    	alert('Нажмите Ctrl-D чтобы добавить сайт в избранное');
    }
    else if( window.external ) window.external.AddFavorite( url, title);

}

function linkTo1C()
{
    window.location="http://www.adelite.ru/";
}
function linkToIntegrate()
{
    window.location="http://www.it-insurance.ru/";
}
function linkToSoft()
{
    window.location="http://www.softmagazin.ru/";
}

function linkToSoftCatalog()
{
    window.location=domain+"/soft";
}
function linkToLite()
{
    window.location="http://www.it-lite.ru/";
}



var d = new Date();
var lsTime = d.getTime();
function getLiveSearchData(value,keyEvent) {

    if ((keyEvent.keyCode == '38' || keyEvent.keyCode == '40' || keyEvent.keyCode == '13') && $("#LiveSearchResults").css("display") != "none") {

        //ищем выделенную ссылку
        var selectElem = $("#LiveSearchResults .liveSeacrhSelected");
        //var selectCaption = selectElem.text();
        
        //снимаем выделение со всех ссылок
        $("#LiveSearchResults a").attr("class", "liveSeacrhNotSelected");

        if (keyEvent.keyCode == '13' && selectElem != null) {//обрабатываем нажатие enter
            /*
            if (selectCaption.length > 0)
            $("input[name='ctl00$TSearchForm1$TBword']").val(selectCaption);
            */
            hideLiveSearch();
        } else

            if (keyEvent.keyCode == '40') {//обрабатываем нажатие keyDown
                var nextElem = null;
                if (selectElem != null) {
                    // alert($(selectElem).next("a").text());
                    if (!$(selectElem).next().is("a")) {//если следующий элемент не ссылка
                        nextElem = $("#LiveSearchResults a").first();
                        $(nextElem).attr("class", "liveSeacrhSelected");
                    }
                    else {
                        nextElem = $(selectElem).next();
                        $(nextElem).attr("class", "liveSeacrhSelected");
                    }

                } else {
                    nextElem = $("#LiveSearchResults a").first();
                    $(nextElem).attr("class", "liveSeacrhSelected");
                }
                if (nextElem != null)
                    $("input[name='ctl00$TSearchForm1$TBword']").val($(nextElem).text());
            } else
                if (keyEvent.keyCode == '38') {//обрабатываем нажатие keyUp

                    var prevElem = null;
                    if (selectElem != null) {
                        if (!$(selectElem).prev().is("a")) {//если предыдущий элемент не ссылка
                            prevElem = $("#LiveSearchResults a").last();
                            $(prevElem).attr("class", "liveSeacrhSelected");
                        }
                        else {
                            prevElem = $(selectElem).prev();
                            $(prevElem).attr("class", "liveSeacrhSelected");
                        }
                    } else {
                        prevElem = $("#LiveSearchResults a").last();
                        $(prevElem).attr("class", "liveSeacrhSelected");
                    }
                    if (prevElem != null)
                        $("input[name='ctl00$TSearchForm1$TBword']").val($(prevElem).text());
                } 

    } else {
    
        var d = new Date();
        var curTime = d.getTime();
        if ((curTime - lsTime) < 250) {
            return;
        }
        else
            lsTime = curTime;

        if (value != "") {
            $.get(domain + 'ajaxGetSearch.aspx', { search: value }, function(data) {

                if (data.length > 0) {
                    $('#LiveSearchResults').html(data); 
                    $("#LiveSearchResults a").hover(
                      function() {
                          $("#LiveSearchResults a").attr("class", "liveSeacrhNotSelected");
                          $(this).attr("class", "liveSeacrhSelected");
                      },
                      function() {
                          $("#LiveSearchResults a").attr("class", "liveSeacrhNotSelected");
                      }
                    );
                    $("#LiveSearchResults").show();

                    $("#LiveSearchResults a").click(function() {
                        $("input[name='ctl00$TSearchForm1$TBword']").val($(this).text());
                        hideLiveSearch();
                        $("#ctl00_TSearchForm1_Benter").click();
                        return false;
                    });

                }
            });
        } else { hideLiveSearch(); }
    }

}

function hideLiveSearch() { $("#LiveSearchResults").hide(); }

function AddProductRemind(productId) {
    var email = $("input[id='remindEmail']").val();
    if (email.length == 0) {
        alert("Необходимо указать E-Mail");
        return;
    }
    if (email.length > 100) {
        alert("Поле 'E-Mail' может содержать не более 100 символов");
        return;
    }
    var filter = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
    if (!filter.test(email)) {
        alert("Необходимо указать корректный E-Mail");
        return;
    }
    $.get(domain + 'ajaxAddProductRemind.aspx',
         { email: email,
             productId: productId
         }, function(data) {
             if (data.length > 0) {
                 if (data == "0") {
                     alert("Заявка успешно отправлена");
                 } else
                     if (data == "1") {
                     alert("Заявка уже принята");
                 } else {
                     alert("Произошла ошибка. Попробуйте отправить заявку позднее.");
                 }
                 $("input[id='remindEmail']").val("");
             }

             $("#mask").hide();
             $("#remindProductForm").hide();
         });

     }

     function ShowRemindProductForm(productId) {
         if (productId > 0)
         {
             $("input[id='remindButton']").unbind('click');
             $("input[id='remindButton']").click(function () {
                 AddProductRemind(productId);
             }
             );            
         }
         //Get the screen height and width
         var maskHeight = $(document).height();
         var maskWidth = $(window).width();

         //Set height and width to mask to fill up the whole screen
         $('#mask').css({ 'width': maskWidth, 'height': maskHeight, 'top': 0, 'left': 0 });

         //transition effect
         $('#mask').fadeTo("slow", 0.7);

         //Get the window height and width
         var winH = $(window).height();
         var winW = $(window).width();

         //Set the popup window to center
         $("#remindProductForm").css('top', winH / 2 - $("#remindProductForm").outerHeight() / 2 + $(window).scrollTop());
         $("#remindProductForm").css('left', winW / 2 - $("#remindProductForm").outerWidth() / 2);
         $("#remindProductForm").css('position', 'absolute');

         //transition effect
         $("#remindProductForm").fadeIn(1000);

         $("#mask").click(function() {
             $(this).hide();
             $("#remindProductForm").hide();
         });
     }

     function CloseRemindForm() {
         $("#mask").hide();
         $("#remindProductForm").hide();
     }

     function ShowHideHardChildCategoryList(categoryId) {
         $(document).ready(function () {
             var blockId = "#hardCatalogChildList_" + categoryId;
             if ($(blockId).css("display") == "none") {
                 $("ul[id^='hardCatalogChildList_']").hide();
                 $(blockId).slideDown('fast', null);
             }
             else
                 $(blockId).hide();
         });
     }

     function ShowHideSoftChildCategoryList(categoryId) {
         $(document).ready(function () {
             var blockId = "#softCatalogChildList_" + categoryId;
             if ($(blockId).css("display") == "none") {
                 $("ul[id^='softCatalogChildList_']").hide();
                 $(blockId).slideDown('fast', null);
             }
             else
                 $(blockId).hide();
         });
     }

     function ShowSoftCatalog() {
         $(document).ready(function () {
             $("#defaultCatalog").hide();
             $("#hardCatalog").hide();
             $("#vendorList").hide();
             $("#softCatalog").fadeIn("slow", null);
             $("#linkToSoftCatalog").text("Каталог программного обеспечения")
             $("#linkToHardCatalog").html("<a href=\""+domain+"hard\" onclick=\"ShowHardCatalog(this);return false;\">Каталог оборудования</a>");
             $("#linkToVendorList").html("<a href=\"" + domain + "Vendors.aspx\" onclick=\"ShowVendorList(this);return false;\">Каталог производителей</a>");
         });
     }

     function ShowHardCatalog() {
         $(document).ready(function () {
             $("#defaultCatalog").hide();
             $("#softCatalog").hide();
             $("#vendorList").hide();
             $("#hardCatalog").fadeIn("slow", null);          
             $("#linkToHardCatalog").text("Каталог оборудования")
             $("#linkToSoftCatalog").html("<a href=\"" + domain + "soft\" onclick=\"ShowSoftCatalog(this);return false;\">Каталог программного обеспечения</a>");
             $("#linkToVendorList").html("<a href=\"" + domain + "Vendors.aspx\" onclick=\"ShowVendorList(this);return false;\">Каталог производителей</a>");
         });
     }

     function ShowVendorList() {
         $(document).ready(function () {
             $("#defaultCatalog").hide();
             $("#hardCatalog").hide();
             $("#softCatalog").hide();
             $("#vendorList").fadeIn("slow", null);
             $("#linkToVendorList").text("Каталог производителей")
             $("#linkToSoftCatalog").html("<a href=\"" + domain + "soft\" onclick=\"ShowSoftCatalog(this);return false;\">Каталог программного обеспечения</a>");
             $("#linkToHardCatalog").html("<a href=\"" + domain + "hard\" onclick=\"ShowHardCatalog(this);return false;\">Каталог оборудования</a>");
         });
     }


