﻿// Obrazki Produktów

function B2BImage(id, thin, medium, large, path) {
    this.id = id;
    this.thin = thin;
    this.medium = medium;
    this.large = large;
    this.path = path + '/';
}

B2BImage.prototype = {
    getID: function() { return this.id; },
    getThin: function() { return this.thin; },
    getMedium: function() { return this.medium; },
    getLarge: function() { return this.large; },
    getPath: function() { return this.path; }
};

function switchImage(ctrl) {
    var ii = ctrl.B2BImage;
    mainImage.src = imgPrefix + ii.getPath() + ii.getMedium();
    var tmp = currentImage;
    currentImage = ii;
    ctrl.B2BImage = tmp;
    ctrl.src = imgPrefix + tmp.getPath() + tmp.getThin();
};

function initImages() {
    //alert('aaa');
    var img_list = document.getElementById('img_list');
    for (var i = 1; i < img.length; ++i) {
        img_list.style.display = '';
        var ii = new Image();
        ii.src = imgPrefix + img[i].getPath() + img[i].getThin();
        ii.onclick = function() {
            mainImage.src = imgPrefix + this.B2BImage.getPath() + this.B2BImage.getMedium();
            var tmp = currentImage;
            currentImage = this.B2BImage;
            this.B2BImage = tmp;
            this.src = imgPrefix + this.B2BImage.getPath() + this.B2BImage.getThin();
        };
        ii.B2BImage = img[i];
        img_list.appendChild(ii);
    }
}

function removeChildrens(elem) {
    while (elem.childNodes.length > 0) {
        elem.removeChild(elem.childNodes[elem.childNodes.length - 1]);
    }
}

function findPos(obj) {
    var curleft = curtop = 0;
    if (obj.offsetParent) {
        curleft = obj.offsetLeft
        curtop = obj.offsetTop
        while (obj = obj.offsetParent) {
            curleft += obj.offsetLeft
            curtop += obj.offsetTop
        }
    }
    return [curleft, curtop];
}

function PopupMainImage() {
    window.open('/ViewImage.aspx?imageId=' + currentImage.getID(), '_blank', '');
}

var imgPrefix = '';
var img = new Array();

// Drzewko kategorii

var colapsed = null;

function colap(elem, head) {
    var a_colaps = elem.parent().parent().children('a.colap');

    a_colaps.parent().parent().children('ul').hide('fast');
    head.children('a').addClass('colap');
    a_colaps.removeClass('colap');
}

function Colap(elem) {
    var ul = elem.nextSibling.nextSibling;

    if (ul.display != 'none')
        J(ul).hide('fast');
    else
        J(ul).show('fast');
}

function pokaz(elem) {
    var tmp = J(elem).next();

    tmp.show('fast');

    colapsed = tmp;
    colap(tmp, J(elem));
}

function Pokaz(elem) {
    var tmp = J(elem).next();

    var e = elem.nextSibling;
    if (e.nodeName != 'UL')
        e = e.nextSibling;

    if (e.style.display == 'none') {
        tmp.show('fast');
        tmp.prev().children('a').addClass('colap');
    }
    else {
        tmp.hide('fast');
        tmp.prev().children('a').removeClass('colap');
    }

    colapsed = tmp;

    //Colap(elem);

    //colap(tmp, J(elem));
}

// FILTROWANIE

var filtry = new Array();

function notEmpty() { var v = document.getElementById('filter_box_-2'); return v == null ? false : v.checked; }  // false;

var alter = false;

//bug w ie
//if(!Array.indexOf){
Array.prototype.indexOf = function(obj) {
    for (var i = 0; i < this.length; i++) {
        if (this[i] == obj) {
            return i;
        }
    }
    return -1;
}
//}


function PrzelaczFiltry(elem) {
    var ch = elem.checked;

    if (ch == undefined)
        ch = J(elem).next().attr('checked') == true;

    if (ch) {
        var v = J(elem).parent().parent().parent();

        v.parent().children('.tree_item').hide();
        v.show();
    }
    else {
        var v = J(elem).parent().parent().parent().parent();

        v.children('.tree_item:not(.off)').show();
    }

    if (txt_parentFilters == '1')
        FiltrujFiltry(elem);
}

function FiltrujFiltry(elem) {
    var ch = elem.checked;

    if (ch == undefined)
        ch = J(elem).next().attr('checked') == true;

    var i = J(elem).attr('t');

    if (ch) {
        var v = J('.filtry').find('.par:not(.t' + i + ')');
        v.hide().addClass('off');
        v.each(function(e) { J(this).find('input:checked').click(); });
        J('.filtry').find('.par:not(.t' + i + ').par_' + J(elem).html()).show().removeClass('off');
    }
    else {
        J('.filtry').find('.par:not(.t' + i + ')').show().removeClass('off'); ;
    }
}
    function PobierzKoszyk() {
        J.post('MainHandler.ashx', { cmd: 'basket_get' }, PobierzKoszykCallback); 
    }
    function PobierzKoszykCallback(data) {
        J('#BasketLeft').html(data);
    }

function WyczyscFiltr(elem) {
    var v = J(elem).parent().parent().parent();

    v.find('.filter_box').attr('checked', false);
    v.find('.tree_item').show();

    filtry = new Array();

    Filtruj();
}

function UstawFiltr(stan, id) {
    if (id == -2) {//alert('a');
        //notEmpty = !notEmpty();
        return;
    }

    var sid = id.toString();

    if (stan == true) {
        if (filtry.indexOf(sid) > -1) {
            return;
        }

        filtry.push(sid);
    }
    else {
        filtry.splice(filtry.indexOf(sid), 1);
    }

}

function HideEmptyRows(t) {
    if (t.childNodes.length == 0) {
        J(t).parent().hide();
        return;
    }

    var attrs = '';

    try {
        attrs = t.childNodes.item(0);
    }
    catch (ex) { attrs = ''; }

    if (attrs == null || attrs == '') {
        J(t).parent().hide();
        return;
    }
    var atrs = attrs.nodeValue.split(';');

    var show = 0;

    for (var i = 0; i < atrs.length; ++i) {
        if (atrs[i] != '') {

            if (filtry.indexOf(atrs[i]) > -1) {
                //J(t).parent().show();
                ++show; // = true;
            }
            else {
                J(t).parent().hide();
                //show = false;
            }
        }
    }

    if (show == filtry.length) {
        J(t).parent().show();
        J(t).parent().next('.opis_r').show();

    }
    else {
        J(t).parent().hide();
        J(t).parent().next('.opis_r').hide();

    }

}

function HideEmptyTables(t) {
    var rows = J(t).children().children(".HproductRow:visible, .lis:visible");

    if (rows.length < 1) {
        J(t).hide().prev().hide().prev().hide();
    }
    else {
        J(t).show().prev().show().prev().show();
    }
}

function PokazWszystkie() {
    J('.HtableTitle').show();
    J('.HtableButton').show();
    J('.Htable').show();
    J('.HtableHeader:not(.group_basket)').show();

    J(".HproductRow:not(:visible)")/*.children(".Hhidden")*/.each(function(i) {
        J(this).show().next('.opis_r').show();
        //J(this)./*parent().*/show().parent().parent().show().prev().show().prev().show();
    });
}

function AlterBackground(elem) {
    //        var tmp = J(elem).prevAll(':visible:first');

    if (J(elem).is('.HtableHeader')) {
        alter = false;
        return;
    }

    if (alter == true) {
        //J(elem).next('.opis_r').removeClass('Halter').addClass('Halter2');
        J(elem).removeClass('Halter').addClass('Halter2');
    }
    else {
        //J(elem).next('.opis_r').removeClass('Halter2').addClass('Halter');
        J(elem).removeClass('Halter2').addClass('Halter');
    }

    alter = !alter;
}

function Filtruj() {
    //PokazWszystkie();

    if (filtry.length == 0 && !notEmpty()) {
        //alert('1');
        PokazWszystkie();
        //alert('2');
        J('.group:not(.set)').show(); //alert('3');
    }
    else if (filtry.length == 0 && notEmpty()) {
        //alert('4');
        PokazWszystkie();
        //alert('5');
        J(".HproductRow:visible").children(".Hquantity").children(".Hbrak").each(function(i) { var v = J(this).parent().parent(); v.hide(); v.next('.opis_r').hide(); });
        //alert('6');
        J(".Htable").each(function(i) { HideEmptyTables(this) }); //alert('7');
    }
    else {
        J(".HproductRow").children(".Hhidden").each(function(i) { HideEmptyRows(this); });

        if (notEmpty()) {
            var o = J(".HproductRow:visible").children(".Hquantity");
            o.children(".Hbrak").each(function(i) { var v = J(this).parent().parent(); v.hide(); v.next('.opis_r').hide(); });
            o.children(".Hduzo").each(function(i) { var v = J(this).parent().parent(); v.show(); v.next('.opis_r').show(); });
            o.children(".Hsrednio").each(function(i) { var v = J(this).parent().parent(); v.show(); v.next('.opis_r').show(); });
        }

        J(".Htable").each(function(i) { HideEmptyTables(this) });
    }

    alter = false;
    //alert('8');
    J('.group').each(function(i) {
        var id = J(this).attr('group_id');
        //            if (J('.group_header_' + id).css('display') != 'none')
        if (J(this).next().css('display') != 'none') {
            HideGroup(id);
        }
        //FilterGroup2(id, J('.group_header_' + id).find('.active').attr('attr_id'), null);
    });
    alter = false;

    J(".lis:visible, .HtableHeader:visible").each(function(i) { AlterBackground(this); });

}

function Filtruj2() {
    document.getElementById('filter_box_-2').checked = true;

    J(".lis:visible, .HtableHeader:visible").each(function(i) { AlterBackground(this); });

}


// Lista Produktów



//top.window.onunload = CheckQuantities;
//document.getElementById('Hbody').setAttribute('onbeforeunload', 'CheckQuantities()');

function CheckQuantities() {
    var s = 0;
    J(".HproductRow, .lis").children(".Hile").each(function(i) { if (parseInt(this.value)) { ++s; return; } });

    if (s > 0)
        if (confirm(txt_1))
        DodajDoKoszyka();
}



function ClearQuantities() {
    J(".HproductRow, .lis").find(".Hile").each(function(i) { this.value = ''; });
}

function PobierzPdf(id) {
    //var produkty = new Array();

    var hidden = document.getElementById(id);
    if (hidden == null)
        hidden = document.getElementById('ctl00_ContentPlaceHolder1_proMain_pdfIds');

    J(".HproductRow:visible").children(".Hid").each(function(i) { hidden.value += this.value + ';'; })


    __doPostBack('ctl00$ContentPlaceHolder1$proMain$lbtGetPdf', '');
    //KolterCorp.Web.Hurt.Controls.Produkty.GetPDF(produkty);
}



function ColapseSet(id, elem) {
    var v = J(elem).parent().parent();

    if (v.children('.' + id + ':first').css('display') == 'none') {
        v.children('.group').hide();
        v.children('.group_item').hide();
        v.children('.group_pad, .group_pad2').hide();
        v.children('.group_basket').hide();

        //v.children('.group_pad.' + id).show();
        var c = v.children('.' + id);
        c.show();
        //c.children().attr('onclick', 'javascript:void(0);');
        c.children('.foto_box').css('border', '1px solid White').css('background-color', 'White').children('.foto_T1').hide();
    }
    else {
        v.children('.group').hide();
        v.children('.group_item').hide();
        v.children('.group_pad, .group_pad2').hide();
        v.children('.group_basket').hide();

        v.children('.' + id).hide();
    }

    v.find(".lis:visible, .HtableHeader:visible").each(function(i) { AlterBackground(this); });
}


function ColapseGroup(id, headerId, elem, hide) {

    var setId = '';

    if (elem != null)
        setId = J(elem).parent().attr('set_id');

    var ss = setId == '' || setId == null ? '' : '.s_' + setId;
    if (ss == undefined)
        ss = '';
    //alert(ss);
    var v = J(elem).parent().parent();
    //alert('aa');
    var h = v.children('.' + headerId + ss);
    //alert('bb');
    var b = v.children('.group_basket.group_' + id + ss);
    if (b.css('display') == 'none' && hide != true) {
        //            J('.table_hidden_header').show();
        //            J('.tabhid').css('display', 'none');

        v.children('.group_item').hide();
        v.children('.group_pad').hide();
        v.children('.group_basket').hide();

        h.show();

        //J('.group' + id).show();
        v.children('.group_pad.group_' + id + ss).show();

        var l = h.find('.group_box_img').length;

        if (l < 2)
            h.hide();

        if (notEmpty() || l < 2)
            FilterGroup2(id, null, null, v, ss);

        // J(".lis:visible, .HtableHeader:visible").each(function(i) {  AlterBackground(this); });
    }
    else {
        HideGroup(id, ss);
    }
}

function HideGroup(id, ss) {
    if (ss == undefined)
        ss = '';

    //alert('hide' + ss);
    J('.table_hidden_header').hide();
    J('.tabhid').show();

    J('.group_' + id + ss + ':not(.set)').hide();

    J(".lis:visible, .HtableHeader:visible").each(function(i) { AlterBackground(this); });

    var v = J('.group_' + id.toString() + ss);
    v.find('.foto_popup').show();
    v.find('.foto_T1').hide();
}

function FilterGroup(id) {
    //alert('s' + id);

    var sel = '';

    J('.group_select_' + id).each(function() { if (this.selectedIndex != 0) { sel += this[this.selectedIndex].value + ';'; } });

    var seld = sel.split(';');

    J('tr.group_' + id + ' td.Hhidden')/*.children(".Hhidden")*/.each(function(i) { CheckRow(this, id, seld); });

    J(".lis:visible, .HtableHeader:visible").each(function(i) { AlterBackground(this); });
}

function FilterGroup2(id, attr, elem, table, ss) {
    //J('.table_hidden_header').show();
    //J('.tabhid').css('display', 'none');

    //J()

    if (ss == undefined)
        ss = '';

    var setId = '';

    if (ss != null)
        setId = ss;

    if (elem != null)
        setId = J(elem).parent().parent().attr('set_id');

    var ss = setId == '' || setId == null ? '' : '.s_' + setId;    
    //alert(ss);
    var seld = attr == null ? null : attr.split(';');

    if (elem != null) {
        J(elem).parent().children('.group_box_img').removeClass('active');
        J(elem).removeClass('active').addClass('active');
    }

    var va = null;
    if (table != null)
        va = table;
    else
        va = J(elem).parent().parent().parent();

    if (!J(elem).parent().parent().is('.set')) {
        va.children('.group_basket').hide();
        va.children('.group_item:not(.group_header)').hide();
    }

    va.children('.group_' + id.toString() + ss).children(".Hhidden").each(function(i) { CheckRow(this, id, seld); });

    //alert('f2 start');
    var tmp = '';
    va.children('.group_' + id.toString() + ss + ':not(.group_header):not(.group_basket):visible').each(function(i) {
        var v = J(this);
        var t = v.attr('img_group');

        if (tmp != t) {
            tmp = t;
            v.find('.foto_popup').hide();
            v.find('.foto_T1').show();
            v.addClass('table_bottom');
        }
    });

    var v = J(va.children('.group_' + id.toString() + ss + ':not(.group_header):not(.group_basket):visible:first'));
    v.find('.foto_popup').hide();
    v.find('.foto_T1').show();
    v.addClass('table_bottom');

    va.children('.group_basket.group_' + id.toString() + ss).show();

    //        else {
    //            J('tr.group_' + id + ' td.Hhidden')/*.children(".Hhidden")*/.each(function(i) { CheckRow(this, id, seld); });

    //            var v = J('.group_' + id.toString() + ':not(.group_header):visible:first');
    //            v.find('.foto_popup').hide();
    //            v.find('.foto_T1').show();
    //            v.addClass('table_bottom');
    //            J('.group_basket.group_' + id.toString()).show();
    //        }

    J(".lis:visible, .HtableHeader:visible").each(function(i) { AlterBackground(this); });
}

function CheckRow(t, id, sel) {
    var attrs = '';
    try {
        attrs = t.childNodes.item(0);
        attrs = attrs.nodeValue;
    }
    catch (ex) { attrs = ''; }

    if (attrs == null || attrs == undefined)
        attrs = '';
    var atrs = attrs.split(';');

    var show = 1;
    if (sel != null) {
        for (var i = 0; i < sel.length; ++i) {
            if (sel[i] != '') {
                if (atrs.indexOf(sel[i]) == -1) {
                    --show;
                    break;
                }
            }
        }
        if (show < 1) {
            J(t).parent().hide();
            return;
        }
    }

    if (filtry.length == 0 && !notEmpty()) {
    }
    else if (filtry.length == 0 && notEmpty()) {
        if (J(t).parent().children(".Hquantity").children(".Hbrak").length > 0) {
            --show;
        }
    }
    else {
        for (var i = 0; i < filtry.length; ++i) {
            if (filtry[i] != '') {

                if (atrs.indexOf(filtry[i]) > -1) {
                }
                else {
                    --show;
                }
            }
        }

        if (notEmpty()) {
            if (J(t).parent().children(".Hquantity").children(".Hbrak").length > 0)
                --show;
           J(".HproductRow:visible").children(".Hquantity").children(".Hsrednio").each(function(i) { J(this).parent().parent().show(); });
        }

        //J(".Htable").each(function(i) { HideEmptyTables(this) });
    }

    //alter = false;

    //J(".lis:visible, .HtableHeader:visible").each(function(i) { AlterBackground(this); });



    //        for (var i = 0; i < atrs.length; ++i) {
    //            if (atrs[i] != '') {

    //                if (filtry.indexOf(atrs[i]) > -1) {
    //                    //J(t).parent().show();
    //                    ++show; // = true;
    //                }
    //                else {
    //                    J(t).parent().hide();
    //                    //show = false;
    //                }
    //            }
    //        }

    if (show > 0)
        J(t).parent().show();
    else
        J(t).parent().hide();

}

function ToggleViewMode(elem, mode, id, id2) {
    Set_Cookie('b2b_view_mode', mode, '', '/', '', '');
    
    //alert(Get_Cookie('b2b_view_mode'));

//    J(id).css('font-weight', 'normal');
//    J(id2).css('font-weight', 'bold');

//    if (mode == 1) {
//        //J('.foto_popup').show();
//        J('.fot').addClass('pp').removeClass('fot');
//        J('.foto_T1').hide();
//        J('.opis_r').hide();
//        J('.opis_r').addClass('Hhidden');
//        J('.foto_box, .indent_box').attr('rowspan', '1');
//    }
//    else if (mode == 2) {
//        //J('.foto_popup').hide();
//        J('.pp').addClass('fot').removeClass('pp');
//        J('.foto_T1').show();
//        J('.opis_r').hide();
//        J('.opis_r').addClass('Hhidden');
//        J('.foto_box, .indent_box').attr('rowspan', '1');
//    }
//    else if (mode == 3) {
//    //J('.foto_popup').hide();
//        J('.pp').addClass('fot').removeClass('pp');
//        J('.foto_T1').show();
//        J('.opis_r').show();
//        J('.opis_r').removeClass('Hhidden');
//        J('.foto_box, .indent_box').attr('rowspan', '2');
//        J('.HtableHeader .foto_box').attr('rowspan', '1');
//    }

//    parent.resizeIframe('frmMain');
//    parent.resizeIframe('frmMain');
}

function GoToNextRow(elem, e) {
    var evt = e ? e : window.event;
    if (evt.keyCode == 13)
        J(J(elem).parent().parent().nextAll(":visible")[0]).find('#Quantity0').focus();
}

function GetFilters() {
    var filters = '';
    var first = true;
    var c = '';

    var v = J('#top_box select.flt').each(function() {
        if (this.value != 0) {
            filters += c + J(this).val();
            if (first) c = ';';
        }
    });
    
    return filters;
}

var cur_page = 1;
function SubmitFilters() {
    //var el = target(window.event || arguments.callee.caller.arguments[0]);
    var nn = J('#top_box tr:first-child').css('display') == 'none';
    var v = J('#top_box');
    var chbAvailable = nn ? '' : v.find('#chbAvailableOnly').attr('checked') ? '1' : '0';
    var chbHidePrice = nn ? '' : v.find('#chbHidePrice').attr('checked') ? '1' : '0';
    var chbGroup = nn ? '' : v.find('#chbGroup').attr('checked') ? '1' : '0';
    var ps = ''; // v.find('#cmbPageSize').attr('value');
    var filters = GetFilters();
    var filterCategories = J('.flt_cat').attr('value');
    var q_tmp = J('#search .search_txt').attr('value');
    var query = q_tmp == null || q_tmp == '' || q_tmp == undefined ? getUrlEncodedKey('q') : q_tmp;

    if (query == undefined)
        query = ' ';

    Redirect( document.location.href, chbAvailable, chbGroup, query, filters, chbHidePrice, ps, cur_page, filterCategories);
}
function Search() {
    var el = target(window.event || arguments.callee.caller.arguments[0]);
    var nn = J('#top_box tr:first-child').css('display') == 'none';

    var url = 'Search.aspx';
    var v = J('#top_box');
    var chbAvailable = nn ? '' : v.find('#chbAvailableOnly').attr('checked') ? '1' : '0';
    var chbGroup = nn ? '' : v.find('#chbGroup').attr('checked') ? '1' : '0';
    var chbHidePrice = nn ? '' : v.find('#chbHidePrice').attr('checked') ? '1' : '0';
    var q_tmp = J('#search .search_txt').attr('value');
    var query = q_tmp == null || q_tmp == '' || q_tmp == undefined ? getUrlEncodedKey('q') : q_tmp;
    var ps = ''; // v.find('#cmbPageSize').attr('value');
    var filters = GetFilters();

    if (query.length < 2) return;

    setTitle(txt_foundItems);

    Redirect(document.location.href, chbAvailable, chbGroup, query, filters, chbHidePrice, ps, cur_page);
}

function ClearFilters() {
    var v = J('#top_box');
    v.find('#chbAvailableOnly').removeAttr('checked');
    v.find('#chbGroup').removeAttr('checked');
    
    J('#search, .search_txt').attr('value', '');

    SubmitFilters();
}

function Redirect(url, a, g, q, f, h, ps, pc, fc) {
    var qs = getQsFromUrl(url);
    var page = url.replace(qs, '');
   // alert(page);
    if(a != '') qs = setUrlEncodedKey('a', a, qs);
    if (g != '') qs = setUrlEncodedKey('g', g, qs);
    qs = setUrlEncodedKey('q', q == ' +' ? '  ' : q, qs);
    qs = setUrlEncodedKey('f', f, qs);
    if (h != '') qs = setUrlEncodedKey('h', h, qs);
    if (ps != '') qs = setUrlEncodedKey('ps', ps, qs);
    qs = setUrlEncodedKey('pc', pc, qs);
    if (fc != undefined && fc != null) qs = setUrlEncodedKey('fc', fc, qs);

    var el = window.parent.J('iframe:visible');

    el.attr('src', /* 'OfferMain.aspx'*/page + qs);     
}


// ######################### Nowy KOSZYK - Dodawanie ######################### 
var counter = 0;
var items = null;
var ids = '';
var qs = '';
var units = '';
var unitsparams = ''
var categories = '';

function AddProduct(ilosc, domyslna_ilosc) {
    var v = J(ilosc).parent();
    if(!domyslna_ilosc) domyslna_ilosc = '';

    var il = J(ilosc).attr('value');
    ids += v.parent().attr('i') + ';';
    qs += (il == '' ? domyslna_ilosc : il) + ';';
    categories += (v.parent().attr('c') == undefined ? '0' : v.parent().attr('c')) + ';';
    var u = v.find('option:selected').attr('order');
    if (u == undefined) {
         u = v.children('select.qu').attr('selectedIndex');
    }
    if (u != undefined) {
        units += u + ';';
        unitsparams += v.children('select.qu').attr('value') + ';';
    }
    
    ++counter;
}
var added_txt_, basketId_;
function AddBasket(basketId, added_txt) {        
    added_txt_ = added_txt;
    var el = target(window.event || arguments.callee.caller.arguments[0]);
    var do_koszyka_z_przechowalni = J(el).is('.bsk_add_to_basket');
   // alert(do_koszyka_z_przechowalni + ' ' + curProductId);
    // kopiowanie do koszyka z przechowalni
    if (do_koszyka_z_przechowalni) {
        J('#axc2 .chbS:checked').each(function () { AddProduct(J(this).parent().parent().find('.Hile'), 1); });
        basketId = basketId == 0 ? Get_Cookie('b2b_basket_1_' + txt_customerId) : basketId;
    }
    else
        J(".Htable#axc .Hile, .Htable.basket#axc2 .Hile").each(function (i) { if (parseFloat(this.value.replace(',', '.'))) AddProduct(this); });
   // alert();
    // dodanie do przechowalni
    if(curProductId != '' ) {
        J('#axc1 .chbS:checked').each(function () { AddProduct(J(this).parent().parent().find('.Hile')); })
        if (curProductId != '-1') {
            ids = curProductId + ';' + ids;
            qs = '1;' + qs;
            categories = curCategoryId + ';' + categories; 
            units = (units != '' ? '0;' + units : '');
            unitsparams = (unitsparams != '' ? '1;' + unitsparams : ''); 
            }
    }
    curProductId = '';

    // ostrzezenie o braku podanej ilosci
    if ((ids == '' || !ids) && added_txt == undefined) {
        alert(txt_noQauntity);
        return;
    }
    
    if (added_txt != undefined) {
        J.post('MainHandler.ashx', { cmd: 'basket_add', ids: ids, categories: categories, quantities: qs, units: units, unitsparams: unitsparams, customerId: txt_customerId, basketId: basketId, actionType: p_actionType, qs: location.search }
            , do_koszyka_z_przechowalni ? AddBasketCallback3 : AddBasketCallback2);
        basketId_ = basketId;
    }
    else
        J.post('MainHandler.ashx', { cmd: 'basket_add', ids: ids, categories: categories, quantities: qs, units: units, unitsparams: unitsparams, customerId: txt_customerId, basketId: Get_Cookie('b2b_basket_1_' + txt_customerId), actionType: p_actionType, qs: location.search }, AddBasketCallback);
    
    ids = ''; qs = ''; units = ''; unitsparams = ''; counter = 0;    
}
// dodawanie do koszyka
function AddBasketCallback(data, text) {
    ids = '';qs = '';units = '';unitsparams = '';counter = 0;
    
    J('.basket_notify').show();

    if (txt_clearQuantities != '0')
        ClearBasket();

//    if (txt_addedToBasket != '' && txt_addedToBasket != null && data == '1') {       
//        alert(added_txt_ == undefined || added_txt_ == null ? txt_addedToBasket : added_txt_);
//        added_txt_ = null;
//    }
    if (data != '')
        alert(data);
    Set_Cookie('b2b_basket_add', '1', '', '/', '', '');
}
// dodawanie do przechowalni z koszyka
function AddBasketCallback2(data, text) {
    ids = ''; qs = ''; units = ''; unitsparams = ''; counter = 0;

    J('.basket_notify').show();

    if (txt_clearQuantities != '0')
        ClearBasket();

    // odswizenie koszyka i przejscie do przechowalni
    try {
        if (basketId_ && txt_deleteSelectedProductsFromBasket) {
            Set_Cookie('b2b_basket_2_' + txt_customerId, basketId_, '', '/', '', '');
            J('#hidNewId2').attr('value', basketId_);
            var v = confirm(txt_deleteSelectedProductsFromBasket);
            if (v)
                J('#bsk_del1').click();
            else
                bsk_Zapisz(2);
        }
    } catch (ex) { }
}
// kopiowanie do koszyka z przechowalni
function AddBasketCallback3(data, text) {
    ids = ''; qs = ''; units = ''; unitsparams = ''; counter = 0;
    //changes = new Array();
    bsk_Zapisz(2);    
}
function AddBasketGetDefaultQuantity(el) {
//    if (el && ( curProductId == '' || curProductId == undefined)) {
//        var v = J(el).parent().parent().attr('i');
//        if (v) curProductId = v;
//    }  
}

function ClearBasket() {
    J(".Htable#axc .Hile, .Htable.basket#axc2 .Hile").each(function(i) { this.value = ''; });
}
function pch_Dodaj(el, n, type, customerId, refresh) {
    if (n != undefined && n != null && n != '') {
        if(refresh == 1)
            J.post('MainHandler.ashx', { cmd: 'basket_new', name: n, type: type, customerId: customerId, txtReturn: '{0}' }, NewBasketCallback2);
        else
            J.post('MainHandler.ashx', { cmd: 'basket_new', name: n, type: type, customerId: customerId, txtReturn: '{0}' }, NewBasketCallback);
    }
}
function NewBasketCallback(data, text) {
    Set_Cookie('b2b_basket_2_' + txt_customerId, data, '', '/', '', '');
    AddBasket(data, '');
    J.post('MainHandler.ashx', { cmd: 'basket_popup_text', basketId: data, type: 2, customerId: txt_customerId }, BasketPopupTextCallback);
    nd(); return nd();
}
function NewBasketCallback2(data, text) {
    J('#hidNewId2').attr('value', data);
    Set_Cookie('b2b_basket_2_' + txt_customerId, data, '', '/', '', '');
    bsk_Zapisz(2);
}
function BasketPopupTextCallback(data, text) {
    txt_addToBasketHtml = data.toString().replace(/\\'/g, "'");
}

var curProductId = '';
var curCategoryId = '';
var p_actionType = 1;
function pch_PokazPopup(pos, actionType) {
    var el = target(window.event || arguments.callee.caller.arguments[0]);
    curCategoryId = J(el).parent().parent().attr('c');
    if (curCategoryId == undefined) curCategoryId = '0';
    curProductId = J(el).parent().parent().attr('i');
    if (curProductId == undefined) curProductId = '-1';
    pos = curProductId == '-1' && !(pos > -3000) ? 0 : (pos > -3000 ? pos : -500);
    p_actionType = actionType;

    if (txt_addToBasketHtml == '') {
        var n = prompt(txt_giveNewBasket2Name);
        pch_Dodaj(el, n, 2, txt_customerId);
    }
    else {
        overlib(txt_addToBasketHtml, STICKY, LEFT, OFFSETY, 0, OFFSETX, Math.abs(pos));
        return overlib(txt_addToBasketHtml, STICKY, LEFT, OFFSETY, 0, OFFSETX, Math.abs(pos));
    }
}

// // ######################### Nowy KOSZYK - Dodawanie na podstawie dokumentów ######################### 
function ZlozZamowienie(type,doctype,docId) {
//    J(".Htable .Hile").each(function (i) { if (parseFloat(this.value.replace(',', '.'))) AddProduct(this); });
//    //alert(ids + ' '+ qs +  ' ' + units);
    J.post('MainHandler.ashx', { cmd: 'doc_basket_add', cmdtype: type, doctype: doctype, DocId: docId, basketId: Get_Cookie('b2b_basket_1_' + txt_customerId) }, ZlozZamowienieCallback);
//    //alert('po');

//    ids = '';

//    qs = '';
//    units = '';
//    unitsparams = '';
    //    counter = 0;
 //   alert(docId);
}

function ZlozZamowienieCallback(data, text) {
    ids = '';
    qs = '';
    units = '';
    unitsparams = '';
    counter = 0;
    J('.basket_notify').show();


//    if (txt_clearQuantities != '0')
//        ClearBasket();

    if (txt_addedToBasket != '' && txt_addedToBasket != null && data == '1') {

        Set_Cookie('b2b_basket_add', '1', '', '/', '', '');
        alert(txt_addedToBasket);
    }
    if (data != '1')
        alert(txt_notAddedToBasket);
}
// ########################################################################


// // ######################### Oferta detaliczna ######################### 
function ofr_UstawParametry() {
    J('#hidPdf').val('');

    pars = unescape(J('#hidZmianyOferty').attr('value'));
    if (pars == '')
        return;
    var p = pars.split('||');
    for (var i = 0; i < p.length; ++i) {
        if (p[i] == '') continue;
        var pp = p[i].split('^');
        var v = J('#b_'+ pp[0] +'_'+ pp[1]);
        v.attr('value', pp[2]);
        if (pp[0] == '1') ofr_NarzutZmiana(null, v);
    }
    ofr_PrzeliczSume();
}

var ofr_block_narzut, ofr_block_detal;
function ofr_NarzutZmiana(e, el) {
    if (ofr_block_narzut)
        return;

    var licz_sume = el == undefined ? true : false;
    el = el == undefined ? target(window.event || arguments.callee.caller.arguments[0]) : el;

    ofr_block_narzut = true;
    J(el).val(J(el).val().replace('.', ','));
    J('#edRabat').val(J('#edRabat').val().replace('.', ','));
    ofr_block_narzut = false;

    var v = J(el);
    var narzut = parseFloat(v.val().replace(',', '.'));
    var cena = parseFloat(v.parent().parent().find('.p_td').html().replace(',', '.'));
    if (cena == NaN || cena == 'NaN' || !(cena > -1)) return;
    var vat = parseFloat(v.parent().parent().attr('v'));
    var il = v.parent().parent().find('.Hile');
    var ilosc = parseFloat(il.val().replace(',', '.')) * parseFloat(il.attr('prv').replace(',', '.'));

    // aktualizacja cen detalicznych
    ofr_block_narzut = true;  
    var v_dn = v.parent().parent().find('.dn_td input');
    var v_db = v.parent().parent().find('.db_td input');
    if (J(el).val() == '' || narzut <= 0) {
        // przywracamy domyslna cene detaliczna, gdy narzut zostaje wyczyszczony lub gdy jest mniejszy lub równy zero
        var dn = parseFloat(v_dn.attr('d').replace(',', '.'));
        dn = (dn * (1 + narzut / 100)).toFixed(2);
        var db = (dn * (1 + vat / 100)).toFixed(2);
        v_dn.val(dn.toString().replace('.', ','));
        v_db.val(db.toString().replace('.', ','));
    }
    else {
        var dn = (cena * (1 + narzut / 100)).toFixed(2);
        var db = (dn * (1 + vat / 100)).toFixed(2);
        v_dn.val(dn.toString().replace('.', ','));
        v_db.val(db.toString().replace('.', ','));
    }    
    ofr_block_narzut = false;

    // aktualizacja wartosci
    var wartosc_brutto = (ilosc * db).toFixed(2);
    v.parent().parent().find('.wb_td').html(wartosc_brutto.toString().replace('.', ','));
    if (licz_sume)
        ofr_PrzeliczSume();
}
function ofr_Zapisz(action) {
    el = target(window.event || arguments.callee.caller.arguments[0]);
    var v = J(el);
    var bsk_pars = '';

    if (action == 1) {
        // sortowanie
        if (v.attr('s') == undefined) v = v.parent();
        if (v.attr('s') == undefined) v = v.parent();

        J('#hidSort').val(escape(v.attr('s')));
        J('#hidSortDirection').val(escape(v.attr('d')));
    }
    else if (action == 5) {
        // pdf
        J('#hidPDF').val('oferta');
        J('.Hile').each(function () {
            var tr = J(this).parent().parent();
            var id = J(this).attr('p');
            bsk_pars = '-1^' + id + '^' + J(this).find('option:selected').text().replace(/\^/g, '') + '||' + bsk_pars;
            bsk_pars = '-2^' + id + '^' + tr.find('.dn_td input').val().replace(/\^/g, '') + '||' + bsk_pars;
            bsk_pars = '-3^' + id + '^' + tr.find('.db_td input').val().replace(/\^/g, '') + '||' + bsk_pars;
            bsk_pars = '-4^' + id + '^' + tr.find('.wb_td').html().replace(/\^/g, '') + '||' + bsk_pars;
        });
    }
    
    J('.ofr').each(function () {
        var v = J(this).attr('type') == 'checkbox' ? (J(this).attr('checked') == true ? '1' : '0') : J(this).attr('value');
        if (J(this).attr('pp') == '1')
            bsk_pars += J(this).attr('pp') + '^' + J(this).attr('p') + '^' + v.toString().replace(/\^/g, '') + '||';
        else 
            bsk_pars = J(this).attr('pp') + '^' + J(this).attr('p') + '^' + v.toString().replace(/\^/g, '') + '||' + bsk_pars;            
    });
    J('#hidZmianyOferty').val(escape(bsk_pars));

    document.forms["form1"].submit();
}
function ofr_DetalBruttoZmiana() { ofr_DetalNettoZmiana(false); }
function ofr_DetalNettoZmiana(netto) {
    if (ofr_block_detal)
        return;

    var el = target(window.event || arguments.callee.caller.arguments[0]);

    ofr_block_detal = true;
    J(el).val((parseFloat(J(el).val().replace(',', '.'))).toFixed(2).toString().replace('.', ','));
    ofr_block_detal = false;

    if (netto != false) netto = true;
    var v = J(el);
    var d = netto ? '.db_td input' : '.dn_td input';
    var detal_netto, detal_brutto;
    var il = v.parent().parent().find('.Hile');
    var ilosc = parseFloat(il.val().replace(',', '.')) * parseFloat(il.attr('prv').replace(',', '.'));
    var cena = parseFloat(v.parent().parent().find('.p_td').html().replace(',', '.'));
    var vat = parseFloat(v.parent().parent().attr('v'));

    // ustawienie cen detalicznych
    if (netto) {
        detal_netto = (parseFloat(v.val().replace(',', '.'))).toFixed(2);
        detal_brutto = (detal_netto * (1 + vat / 100)).toFixed(2);
    } else {
        detal_brutto = (parseFloat(v.val().replace(',', '.'))).toFixed(2);
        detal_netto = (detal_brutto / (1 + vat / 100)).toFixed(2);
    }

    // aktualizacja drugiej ceny detalicznej
    ofr_block_detal = true;
    v.parent().parent().find(d).val((netto ? detal_brutto : detal_netto).toString().replace('.', ','));
    ofr_block_detal = false;

    // aktualizacja narzutu
    if (!ofr_block_narzut) {
        ofr_block_narzut = true;
        var narzut = ((detal_netto / cena - 1) * 100).toFixed(2);
        v.parent().parent().find('.n_td input').val(narzut.toString().replace('.', ','));
        ofr_block_narzut = false;
    }

    // aktualizacja wartosci
    var wartosc_brutto = (ilosc * detal_brutto).toFixed(2);
    v.parent().parent().find('.wb_td').html(wartosc_brutto.toString().replace('.', ','));
    ofr_PrzeliczSume();
}
function ofr_PrzeliczSume() {
    var sum = 0;
    J('.wb_td').each(function () {
        sum += parseFloat(J(this).html().replace(',', '.'));
    })

    J('#ofr_sum').html(sum.toFixed(2).toString().replace('.', ','));
    J('#hidSummary').val(sum.toFixed(2));
}
function ofr_Edytuj(el, id, type) {
    J('.ofr_edit'+type).hide();
    J(el).parent().find(id).removeClass('h').show().focus();
}
function ofr_Narzut() {
    var n = parseFloat(J('#edNarzut').val().replace(',', '.')).toFixed(2);
    var r = parseFloat(J('#edRabat').val().replace(',', '.')).toFixed(2);
    n = (n == 'NaN' ? 0 : n) - (r == 'NaN' ? 0 : r);
    J('.n_td input:not(#edNarzut)').val(n.toFixed(2)).each(function () { ofr_NarzutZmiana(null, this); }); //.change();
    ofr_PrzeliczSume();
}
function ofr_Narzut2() {
    var el = target(window.event || arguments.callee.caller.arguments[0]);
    var v = J(el).parent().parent().find('.n_td input');
    v.each(function () { ofr_NarzutZmiana(null, this); });
    ofr_PrzeliczSume();
}
function ofr_Ukryj(el) {
    if (el.checked)
        J('.n_td, .p_td').hide();
    else
        J('.n_td, .p_td').show();
}
function ofr_Drukuj() {
    J('.ofr_s, .ofr_pars, .n_td, .p_td').hide();
    J('body').removeClass('print').addClass('print');
    J('#chbUCH').attr('checked', 'checked');
    J('.Hile').each(function () { J(this).parent().find('.qp_').html(J(this).find('option:selected').text()); });
    window.print();
    J('.ofr_s, .ofr_pars').show();
    J('body').removeClass('print');
    J('.Hile').each(function () { J(this).parent().find('.qp_').html(''); });
}
// ########################################################################
