﻿///<reference path="jquery-1.3.2-vsdoc2.js">
///<reference path="pagelister.js">
///<reference path="productsFilter.js">

var AllProductsData = []; 
var selectedFilters = {};

var AllCachedData = null;
var NoStartDrawing = false;


var service_path = site_path + "Services/Products.asmx/";
//Sys.Application.add_init(function(){
//    Sys.Application.add_navigate(GetHistotyPoint)
//})
Sys.Application.add_load(applicationLoadHandler);

$(document).ready(function() {

    $(".sortType").click(SortByClick);

    if (CurrentDrawingType == "") {
        CurrentDrawingType = "Tile";
    }
    SetUncheckedIconsOfViewType();

    if (typeof (SearchIsNew) == "undefined") SearchIsNew = 0;
    if (typeof (SearchIsSale) == "undefined") SearchIsSale = 0;

    //Products.GetProductsByCategory(SearchClassID, SearchTypeID, SearchProducerID, decodeURI(SearchText), SearchIsNew == "1", SearchIsSale == "1", OnShowProducts);
    OnShowProducts(prodJSONdata);

})

function applicationLoadHandler() {
    var pars = getHashParameter();
    if (pars != null) {
        Gpn = pars["gpn"] ? pars["gpn"] : Gpn;
        CurrentDrawingType = pars["cdt"] ? pars["cdt"] : CurrentDrawingType;
        GSortDirection = pars["gsd"] ?pars["gsd"] : GSortDirection;
        GSortType = pars["gst"] ? pars["gst"] : GSortType;
        Gnum = pars["gnum"] ? pars["gnum"] : Gnum;
    }
}

function getHashParameter() {
    if (location.hash.length < 3) 
        return null;
    var parts = location.hash.split("&");
    var pars= {}; 
    for (var i= parts.length; i-->0;) { 
        var kv= parts[i].split('='); 
        var k= kv[0]; 
        var v= kv.slice(1).join('='); 
        pars[k]= v; 
    } 
    return pars; 
}

function SetHistotyPoint() {
    var state = { h: "1" };

    Gpn > 1 ? state.gpn = Gpn : state.gpn = null;

    //if (CurrentDrawingType && CurrentDrawingType != 'Tile')
    state.cdt = CurrentDrawingType;

    //if (GSortDirection == -1)
    state.gsd = GSortDirection;

    //if(GSortType && GSortType!='price')
    state.gst = GSortType;

    state.gnum = Gnum;

//    if (ProducerF!=null)
//        state.pid = ProducerF

//    if (ClassF!=null)
//        state.cid = ClassF

//    if (TypeF!=null)
//        state.tid = TypeF
        
   if(FilterIdF!=null)     
   state.filterId=FilterIdF;
         
    if(RemF!=null)    
   state.rem=RemF;
   
    if(GroupIdF!=null) 
   state.groupId=GroupIdF;
   
   if(CountF!=null)
    state.count=CountF;

    isSetingHistory = true;
    Sys.Application.addHistoryPoint(state);
    isSetingHistory = false;
}

function GetHistotyPoint(sender, e) {
    if (isSetingHistory) return;
    var state = e.get_state();
    Gpn = state.gpn ? state.gpn : 1;
    CurrentDrawingType = state.cdt ? state.cdt : "Tile";
    GSortDirection = state.gsd?state.gsd:1;
    GSortType = state.gst ? state.gst : "price";
    Gnum = state.gnum ? state.gnum : posPerPage[CurrentDrawingType][0];
    
    if ((window.AllProductsData == "undefined") || (AllCachedData == null)) {
        NoStartDrawing = true;
        Products.GetProductsByCategory(SearchClassID, SearchTypeID, SearchProducerID, decodeURI(SearchText), SearchIsNew == "1", SearchIsSale == "1",
            function(data) {

                NoStartDrawing = false;
                OnShowProducts(data);
                NoStartDrawing = true;

                AllCachedData = data;
                AllProductsData = AllCachedData.Products;

                SortBy();
                AffectAllFilters();
                //ifNeedSaveToHistory = true;
            });
    }
    
    else 
    {
       
         ifNeedSaveToHistory = false;
            if((FilterIdF==state.filterId && GroupIdF==state.groupId && RemF==state.rem)||(undefined==state.filterId && undefined==state.groupId && undefined==state.rem))
            {
                 AffectAllFilters();
                 
            }
            //if filter by filter in left column
            else
            {
                var back=true;
                if(state.count>CountF)
                    back=false;
                if(back==false && state.filterId!=null)
                    AddFilter(state.filterId,state.groupId,state.rem=="true"?true:null);
                if(back==true && FilterIdF!=null)
                    AddFilter(FilterIdF,GroupIdF,RemF=="false"?true:null);
                
                FilterIdF=state.filterId;
                GroupIdF=state.groupId;
                RemF=state.rem;
                CountF=parseInt(state.count);
            }
        ifNeedSaveToHistory = true;
        ifNeedSaveToHistory2=false;
        SortBy();
        ifNeedSaveToHistory2 = true;
        setPageSizeLabels();
    }
    
}

function SortByClick() {
    var link = $(this);
    var sortby = link.attr("sortby");
    
    if (GSortType != sortby) {
        GSortDirection = 1
    } else {
        GSortDirection = -1 * GSortDirection;
    }
    GSortType = sortby;
    SortBy();
    
    //DrawPageLister();
}

var ifNeedSaveToHistory = true;
var isSetingHistory = false;
var ifNeedSaveToHistory2 = true;
// Глобальный номер страницы
var Gpn = 1;

// Глобальное кол-во страниц
var Gnum = 0;
// Глобальный тип отображения прайсов
var CurrentDrawingType = "Tile";

var GData;
// Глобальное кол-во позиций на странице
var posPerPage = { Tile: [40, 80], List: [40, 80], Table: [50, 100] };

//var FilterArg ={ProducerID:0,ClassID:0, TypeID:0};



// назначаем кнопкам события отрисовки
function OnShowProducts(data) {

    ifNeedSaveToHistory = false;

    if (NoStartDrawing)
        return false;

    $(".sort").css("visibility", "visible");

    AllProductsData = data.Products;

    if ((data.Products.length == 0) && (typeof (window.IsSearch) != "undefined")) {
        if (IsSearch == true) {
            DrawNothingFound("<p align='center'>По Вашему запросу ничего не найдено.</p>");
            $(".sort").hide();

            $("#filtersButton, #pricefltrButton").attr("onclick", "") // disable filter menu
                                                 .removeClass("pointer")
                                                 .unbind();
            $("#pricefltrButton").attr("src", image_path + "price_act01.gif");
            $("#filtersButton").attr("src", image_path + "filters_none_act01.gif");

            return false;
        }
    }

    // сортировка по цене в начале
    SortBy();

    AllCachedData = data;

    $("#totalCount").html("Всего позиций " + AllProductsData.length);

    $("#tileImg").click(function() {
        Gpn = 1;
        CurrentDrawingType = "Tile";
        Gnum = posPerPage[CurrentDrawingType][0];
        setPageSizeLabels();
        DrawPageLister();
        setCookie("UserViewType", "Tile");
    });

    $("#listImg").click(function() {
        Gpn = 1;
        CurrentDrawingType = "List";
        Gnum = posPerPage[CurrentDrawingType][0];
        setPageSizeLabels();
        DrawPageLister();
        setCookie("UserViewType", "List");
    });

    $("#tableImg").click(function() {
        Gpn = 1;
        CurrentDrawingType = "Table";
        Gnum = posPerPage[CurrentDrawingType][0];
        setPageSizeLabels();
        DrawPageLister();
        setCookie("UserViewType", "Table");
    });

    CurrentDrawingType = getCookie("UserViewType");
    if (CurrentDrawingType == "") {
        CurrentDrawingType = "Tile";
    }

    if (!Gnum)
        Gnum = posPerPage[CurrentDrawingType][0];
    setPageSizeLabels();

    DrawPageLister(function() {
        readFiltersFromCookie();
        CountFuture(WrapFilters); // recalculate filters on start
    });

    ifNeedSaveToHistory = true;

    Sys.Application.add_navigate(GetHistotyPoint)

}

function WrapFilters() {
    //////////////// - прокрутка фильтров и прайсов
    $("#ExtraMenuContainer").toggle("slide", { direction: "left" }, 300, function() {
        $("#freeFilters").toggle("slide", { direction: "right" }, 300
        );
    });
    ////////////////
}

function ReDrawList() {
    
    SetUncheckedIconsOfViewType();

//    DrawAsTile(getPageByNum(Gpn, posPerPage[CurrentDrawingType][0]));

    switch (CurrentDrawingType) {
        case "Tile":
            DrawAsTile(getPageByNum(Gpn, Gnum));
            break;

        case "List":
            DrawAsList(getPageByNum(Gpn, Gnum));
            break;

        case "Table":
            DrawAsTable(getPageByNum(Gpn, Gnum));
            break;
    }

    $("#totalCount").html("Всего позиций " + AllProductsData.length);


    // установить значение кол-ва товаров в общий скрытый серверный инпут Count.
    $(".product_input01").blur(function() {
        $("#" + HiddenCountFieldName).val($(this).val());
    });
    
    //CheckDigitalInput - в main.js
    $(".product_input01").keyup(function(evt) {
        CheckDigitalInput(this, $(this).attr("qpb"), evt);

    });


    $(".product_input01").keydown(function(evt) {
        enterOnInput(evt, this);
    });


    // прорисовать уголочки
    redrawPriseCorners(); 
    
    // установить значение из кукисов
    $(".compare_checkbox").each(function(i){
        $(this).attr("checked",IsCompare($(this).attr("value")));
    });
    
    SetCompare_button();

    HighlightPageSizeLabels();
}


function SetUncheckedIconsOfViewType() {

    $("#tileImg").attr("src", image_path + "pict01.gif");

    $("#listImg").attr("src", image_path + "pict02.gif");
    
    $("#tableImg").attr("src", image_path + "pict03.gif"); 
    
    
        switch (CurrentDrawingType) {
        case "Tile": //01
            $("#tileImg").attr("src", image_path + "pict01_a.gif");
            break;

        case "List": //02
            $("#listImg").attr("src", image_path + "pict02_a.gif");
            break;

        case "Table": //03
            $("#tableImg").attr("src", image_path + "pict03_a.gif");
            break;
      }
}



// ф-ция получения страницы по ее номеру. pn - номер страницы, num - кол-во эл-тов на стр.
// pn должна быть глобалной и будет изменяться нажатием на PageLiser.
function getPageByNum(pn, num) {

    Gnum = num;

    var PageData = [];

    var startIndex = num * (pn - 1);

    var endIndex = startIndex + num;

    if (endIndex > AllProductsData.length)
        endIndex = AllProductsData.length;

    for (var i = startIndex; i < endIndex; i++) {
        PageData.push(AllProductsData[i]);
    }
   
    return PageData;
}


function DrawNothingFound(MessageTxt) {
        $("#priceDiv").html(MessageTxt);
 }


// три типа прорисовки отобранных данных
function DrawAsList(data) {

    var ProductInfoUrl_forSearch = globalSiteUrl + 'products/class/info.aspx?';  // g=1&c=101&t=23&id=86724
	
    // Кэшируем див для вывода хтмл
    PriceDiv = $("#priceDiv");

    var RezHtmlString = '';

    var p;

    RezHtmlString += '<table width="100%" border="0" cellpadding="0" cellspacing="0"><tr><td valign="top">';


    for (i = 0; i < data.length; i++) {

        // текущий продукт
        p = data[i];
		
		var infoUrl = ProductInfoUrl_forSearch + 'g=' + p.GroupID + '&c=' + p.ClassID + '&id=' + p.ID;

        RezHtmlString += '<div class="product_main02" id="listik'+ p.ID+'">';
        
        img = GetImage(p);
            RezHtmlString +='<div class="product_border02"><div class="';
            if(p.IsComparable==true)
                RezHtmlString +='product_with_compare';
            RezHtmlString +='"><div class="product_pict02">';
			RezHtmlString +=AddImgAction(p.ID,0);
			RezHtmlString += '<div class="product_img03"><a href="' + infoUrl + '">' + img + '</a>	</div></div>';
			
			if(p.IsComparable==true){
			    var qpb='-1';
			    if ((p.AvailabilityStatus > 3 && IsOrderMake && p.Price != null) || finBillmode)
			       var qpb= p.QuantityPerBox;
					       
			    RezHtmlString +=  '<div class="product_compare" style="display:block;"><div><input name="" type="checkbox" value="'+p.ID +'" class="compare_checkbox" onClick="SetCompare_box(this,'+p.ID +','+qpb+')"  />';
			    RezHtmlString +=  '&nbsp;<a class="pointer" onclick="SetCompare_box(this,'+p.ID +','+qpb+')">сравнение</a></div></div>';
            }
            
            RezHtmlString +='</div><div class="product_descr02' ;
            if(p.IsComparable==true)
			    RezHtmlString +=  ' descr_with_compare';
			RezHtmlString +='"><div class="product_name02"><a href="' + infoUrl + '">' + p.Name + '</a></div>' +
			'<div class="product_pn"><b>PN:</b>' + p.PartNumber + '</div></div>' +
			'<div class="product_info02">' +
			'<div class="product_cost">Цена: <span class="light_blue">' + p.PriceText + ' ' + p.PricePref + '</span></div>';

        // рисовать корзину и наличие?
        if (IsAuthenticated != "False") {

            RezHtmlString += '<div class="product_avail_new">' + AvailabilityStatusDrawer(p, false) + '</div>';

            if ((p.AvailabilityStatus > 3 && IsOrderMake && p.Price != null) || finBillmode) {
                RezHtmlString += '<div class="product_price_diler"><input gid="' + p.ID + '" type="text" qpb="' + p.QuantityPerBox + '" class="product_input01" value="'+ p.QuantityPerBox+'"/> <img id="buy' + p.ID + '" src="' + image_path + 'buy_product.gif" style="cursor:pointer" class="icon Abuybutton" alt="Добавить" title="Добавить" height="16" width="24" onclick="AddToBacket(' + p.ID + ',' + p.QuantityPerBox + ', event, this);"><span id="runningB' + p.ID + '"></span></div>';
            }
            else {
                RezHtmlString += '<div class="product_price_diler" onclick="return false;"><input type="text" disabled="disabled" class="product_input01 opacity"/> <img src="' + image_path + 'unbuy_product.gif" class="icon" height="16" width="24"></div>';
            }
        }

        var ProdInfoLink = globalSiteUrl + 'products/class.aspx?g=' + p.GroupID + '&c=' + p.ClassID + '&t=' + p.TypeID;

        RezHtmlString += '</div></div><div style="clear: both;"></div></div>';
        if(i+1!= data.length)
            RezHtmlString += '<div class="line01"><img src="' + image_path + '0.gif"></div>';
  }
    
    RezHtmlString += '</td></tr></table>'; 

    PriceDiv.html(RezHtmlString);

    PriceDiv.show();

    data = null;
}

function DrawAsTile(data) {

    var ProductInfoUrl_forSearch = globalSiteUrl + 'products/class/info.aspx?';  // g=1&c=101&t=23&id=86724

    // Кэшируем див для вывода хтмл
    PriceDiv = $("#priceDiv");

    var RezHtmlString = '';

    var p;
    var w;
    var h;

    RezHtmlString += '<table width="100%" border="0" cellpadding="0" cellspacing="0"><tr><td valign="top">';

    var BuyHtml = '';


    for (var i = 0; i < data.length; i++) {

        // текущий продукт
        p = data[i];
		
		var infoUrl = ProductInfoUrl_forSearch + 'g=' + p.GroupID + '&c=' + p.ClassID + '&id=' + p.ID;

        // линия после каждого 4-го эл-та
        if ((i % 4 == 0) && (i > 0)) {
            RezHtmlString += '</br><div class="line" style="clear: both;"><img src="' + image_path + '0.gif"/></div>';
        }

        img = GetImage(p);

        RezHtmlString += '<div class="product_main"><div id="listik' + p.ID + '"><div class="product_border"><div class="product_pict">' + AddImgAction(p.ID, 0) + '<div class="product_img03"><a href="' + infoUrl + '">' + img + '</a></div></div>';
      
        if(p.IsComparable==true && IsAuthenticated.toLowerCase()=="true"){
            var qpb='-1';
			    if ((p.AvailabilityStatus > 3 && IsOrderMake && p.Price != null) || finBillmode)
			       var qpb= p.QuantityPerBox;
			       
			    RezHtmlString +='<div class="product_compare"><div><input name="" type="checkbox" value="'+p.ID +'" class="compare_checkbox" onClick="SetCompare_box(this,'+p.ID +','+qpb+')"  />';
			    RezHtmlString +='&nbsp;<a class="pointer" onclick="SetCompare_box(this,'+p.ID +','+qpb+')">сравнение</a></div></div>';
        }
            
        RezHtmlString +='<div class="product_name"><a href="' + infoUrl + '">' + p.Name + '</a></div>' +
    	'<div class="product_pn_new"><b>PN:</b> ' + p.PartNumber + '</div>';


        if (IsAuthenticated != "False") {

            RezHtmlString +=
            '<div class="product_avail_new">' + AvailabilityStatusDrawer(p, false) + '</div>' +
            '<div id="div'+p.ID+'" class="product_price_diler">' + p.PriceText + ' ' + p.PricePref + '&nbsp;&nbsp;' +
            '<input type="text" maxlength="4" class="product_input01" gid="'+p.ID+'" value="'+p.QuantityPerBox+'" qpb="' + p.QuantityPerBox + '"/>&nbsp;&nbsp;';

            if ((p.AvailabilityStatus > 3 && IsOrderMake && p.Price != null) || finBillmode) {
                RezHtmlString += '<img id="buy' + p.ID + '" src="' + image_path + 'buy_product.gif" onclick="AddToBacket(' + p.ID + ', ' + p.QuantityPerBox + ' ,event, this);" width="24" height="16" class="icon pointer" /><span id="runningB' + p.ID + '"></span>';
            }
            else {
                RezHtmlString += '<img src="' + image_path + 'unbuy_product.gif" width="24" height="16" class="icon pointer" />';
            }
            
            RezHtmlString += '</div>';

        }
        else {

            var optPriceDiv =
                '<div class="product_price_opt">' +
                    '<div class="light_bl">опт</div>' +
                    '<div>' + p.PriceText + ' ' + p.PricePref + '</div>' +
                '</div>';

            if ((p.ProducerID == 252 || p.ProducerID == 326) && window.location.href.indexOf('sale.aspx')==-1) {
                optPriceDiv = '';
            }                

            RezHtmlString +=
            '<div class="product_price">' +
                '<div>Цена:</div>' +
                  optPriceDiv + 
                '<div class="product_price_rozn">' +
                    '<div class="light_gr">розница</div>' +
                    '<div>' + p.RetailPriceText + ' ' + p.PricePref +
                    ' <img class="icon pointer" alt="Где купить?" title="Где купить?" onclick="getProductShops(' + p.GroupID + ', ' + p.ClassID + ', ' + p.ProducerID + ')" height="16" width="16" src="' + image_path + 'info.gif"/></div>' +
                '</div>' +
            '</div>';
        }

        var ProdInfoLink = globalSiteUrl + 'products/class.aspx?g=' + p.GroupID + '&c=' + p.ClassID + '&t=' + p.TypeID;

       // RezHtmlString += '<div class="product_link"><a href="' + ProdInfoLink + '">все товары этой группы <img src="' + image_path + 'all_goods.gif" width="6" height="7" class="icon" /></a></div>';

        RezHtmlString += '</div></div></div>';
    }

    RezHtmlString += '</td></tr></table>';

    PriceDiv.html(RezHtmlString);

    PriceDiv.show();

    data = null;
}

function DrawAsTable(data) {

    var ProductInfoUrl_forSearch = globalSiteUrl + 'products/class/info.aspx?';  // g=1&c=101&t=23&id=86724

 // Кэшируем див для вывода хтмл
    PriceDiv = $("#priceDiv");

    var RezHtmlString = '';

    var PriseType = '(грн.)';

    if (IsAuthenticated != "False") {
    
        PriseType = '(у.е.)';
    }

    var p;
   
    RezHtmlString+= 
		'<table class="list_of_products02" border="0" cellpadding="0" cellspacing="0" width="100%"><tbody>'+
		'<tr class="head_of_products">'+
			'<td class="products_none" valign="top"><img src="' + image_path + '0.gif" height="1" width="7"></td>' +
			//'<td valign="top">&nbsp;</td>' +
			'<td valign="top" colspan="2" align="center">P/N</td>' +
			'<td valign="top">Наименование</td>' +
			'<td align="center" valign="top">Наличие</td>' +
			'<td width="10%" align="right" valign="top">Цена '+ PriseType +'</td>'+
			'<td align="center" valign="top" width="75">' + '<img src="' + image_path + 'buy_sm.gif" height="12">' + '</td>' +
			//'<td width="11" align="center" valign="top">&nbsp;</td>' +
			'<td class="products_none" valign="top"><img src="' + image_path + '0.gif" height="1" width="7"></td>' +
		 '</tr>';

    for (var i = 0; i < data.length; i++) {

        // текущий продукт
        p = data[i];

        var infoUrl = ProductInfoUrl_forSearch + 'g=' + p.GroupID + '&c=' + p.ClassID + '&id=' + p.ID;
		
		var trclass = ((i + 1) % 2 != 0) ? "products02" : "products01";
		var tdclass = (i != 0) ? "products_none" : "products_none01";
		
        RezHtmlString +='<tr class="' + trclass + '">' + '<td class="' + tdclass +
			'" valign="top" width="7"><img src="' + image_path + '0.gif" height="1" width="1"></td><td class="products01" nowrap="nowrap" valign="top">';
			
	    if(p.IsComparable==true && IsAuthenticated.toLowerCase()=="true"){
            var qpb='-1';
			    if ((p.AvailabilityStatus > 3 && IsOrderMake && p.Price != null) || finBillmode)
			       var qpb= p.QuantityPerBox;
			       
			    RezHtmlString +='<input name="" type="checkbox" value="'+p.ID +'" class="compare_checkbox" onClick="SetCompare_box(this,'+p.ID +','+qpb+')"  />';
			   
        }
		else
		    RezHtmlString +='&nbsp;';
			RezHtmlString +='</td><td class="products01" nowrap="nowrap" valign="top">' + p.PartNumber + '</td>' +
			'<td valign="top">'+AddImgAction(p.ID,1)+'&nbsp;<a class="icon" href="' + infoUrl + '">' + p.Name + '</a></td>' +
			'<td align="center" valign="top">' + AvailabilityStatusDrawer(p, true) + '</td>' +
			'<td align="right" valign="top">' + p.PriceText + '</td>' +
			'<td nowrap align="center" valign="top">';

        // рисовать корзину и наличие
        if (IsAuthenticated != "False") 
        {
            if ((p.AvailabilityStatus > 3 && IsOrderMake && p.Price != null) || finBillmode) {
                RezHtmlString += '<input type="text" maxlength="4" class="product_input01" gid="'+p.ID+'" value="' + p.QuantityPerBox +'" qpb="' + p.QuantityPerBox + '"/>&nbsp;&nbsp;<img id="buy' + p.ID + '" src="' + image_path + 'buy_product.gif" alt="Добавить" title="Добавить" class="icon" style="cursor:pointer" onclick="AddToBacket(' + p.ID + ',' + p.QuantityPerBox + ', event, this);"><span id="runningB' + p.ID + '"></span>';
            } 
            else {
                RezHtmlString += '<input type="text" class="product_input01 opacity" disabled="disabled"/> <img src="' + image_path + 'unbuy_product.gif" class="icon" onclick="return false;">';
            }
        }
        RezHtmlString += ' <img class="smallbasketlist icon" id="listik' + p.ID + '" src="' + image_path + 'basket_list.gif" height="16" width="11" style="visibility:hidden"></td>' +
			'<td class="' + tdclass + '" valign="top" width="7"><img src="' + image_path + '0.gif" height="1" width="1"></td></tr>';
  }

  RezHtmlString += '</tbody></table>';

    PriceDiv.html(RezHtmlString);

    PriceDiv.show();

    data = null;
}


function GetImage(dataObject) {

    w = dataObject.mWidth;
    h = dataObject.mHeight;

    img = '';

    if (dataObject.ImageName != "") {
        img = '<img alt="'+dataObject.Name+'" src="' + CommonImagesPath + 'MediumImages/' + dataObject.ImageName + '"'; ;
        if (w / h > 1.4) {
            img += ' width="' + ((w > 85) ? 85 : w) + '"/>';
        } else {
            img += ' height="' + ((h > 60) ? 60 : h) + '"/>';
        }
    } else {
    img = '<img src="' + image_path + 'no_photo.gif" width="50" height="50"/>';
    }
    return img;
}


function AvailabilityStatusDrawer(prodObj, tab) {

    var quantStr = "100+";

    if(prodObj.QuantityItems<100) {
        quantStr = "50+";
        
        if(prodObj.QuantityItems<50) {
            quantStr = "10+";
            
            if (prodObj.QuantityItems < 10) {
                quantStr = prodObj.QuantityItems;
            }
        }
    }

    var d ="";
    if(prodObj.AvailabilityDate!=null)
    {
        //d = (new Date(prodObj.AvailabilityDate)).format('dd.MM.yy')
        var jsonDate = new Date(parseInt(prodObj.AvailabilityDate.replace("/Date(", "").replace(")/", ""), 10));
        d = (new Date(jsonDate)).format('dd.MM.yy');
    }

    //CurrentDrawingType = state.cdt ? state.cdt : "Tile";
	
    var availStr = '';

    switch (prodObj.Availability) {
        case 0:
            availStr = (tab) ? "Нет" : "Наличие: нет";
            break;

        case 1: availStr = (tab) ? "Нет" : "Наличие: нет";
            break;
			
		case 2:
        case 4:
            availStr = (tab) ? ("с " + d) : ("Ожидается с " + d);
            break;

        case 3:
        case 5:
        default:
            if (prodObj.Availability == 3)
                availStr = ((tab) ? "" : "Наличие: ") + "<span class='product_reserve' title='в резерве'>" + quantStr +"</span>";
            else
                availStr = ((tab) ? "" : "Наличие: ") + "<span title='есть в наличии'>" + quantStr + "</span>";
            break;
    }
    return availStr;
}

function AddImgAction(el,table)
{
//   if (IsAuthenticated != "False") {
        var arr=AllCachedData.Actions;
        if (arr!=null && arr.length>0) {         
            for (var i = 0; i < arr.length; i++) 
            {
                if (arr[i].ID == el)
                    if (table==0)
                        return  '<div class="actions"><a href="/actions.aspx?n='+arr[i].ActionID+'"><img src="'+image_path+'action.png" width="38" height="15" border="0" alt="Описание акции" title="Описание акции"/></a></div>';
                    else
                        return  '<a href="/actions.aspx?n='+arr[i].ActionID+'"><img class="icon" src="'+image_path+'action.png" width="38" height="15" border="0" alt="Описание акции" title="Описание акции"/></a>';
            }
        }               
//    }
    return '';
}

function changePageSize(id) {

    var num = 0;

    $("#APageSizeL, #BPageSizeL, #FullPageSizeL").removeClass("active_link");
    $("#" + id).addClass("active_link");
    
    switch(id)
    {
        case "APageSizeL":
            num=posPerPage[CurrentDrawingType][0];
            break;
            
        case "BPageSizeL":
            num=posPerPage[CurrentDrawingType][1];
            break;
            
        case "FullPageSizeL":
            num=AllProductsData.length;
            break;
    }
    Gpn = 1;
    Gnum = num;
    
    DrawPageLister();
}

function setPageSizeLabels() {
    $("#APageSizeL").text(posPerPage[CurrentDrawingType][0]);
    $("#BPageSizeL").text(posPerPage[CurrentDrawingType][1]);
    HighlightPageSizeLabels();
}

function HighlightPageSizeLabels() {
    $("#APageSizeL, #BPageSizeL, #FullPageSizeL").removeClass("active_link none_news");
    $("#APageSizeL, #BPageSizeL, #FullPageSizeL").addClass("pointer");
    if (Gnum == posPerPage[CurrentDrawingType][0])
        $("#APageSizeL").addClass("active_link");
    else if (Gnum == posPerPage[CurrentDrawingType][1])
        $("#BPageSizeL").addClass("active_link");
    else
        $("#FullPageSizeL").addClass("active_link");

    if (posPerPage[CurrentDrawingType][0] >= AllProductsData.length) {
        $("#APageSizeL").addClass("none_news").removeClass("pointer");
    }

    if (posPerPage[CurrentDrawingType][1] >= AllProductsData.length) {
        $("#BPageSizeL").addClass("none_news").removeClass("pointer");
    }
}