offer.ProductsView = function(){
    this.expandedTR = null;
    this.product;
    this.productInfoDiv = null
    this.savedQuantity = ""
    this.createProductsSet = function(result){
        if (result.isGroupSet) {
            this.groupsTable(result)
        }
        else {
            this.productsTable(result)
        }
    }
    /**
     * Tabela produktów
     * @param {Object} result
     */
    this.productsTable = function(result){
        offerInstance.tabView.selectById("productsView", true)
        if (result.rows.length < 1) {
            offerInstance.tabView.getCurrent().innerHTML = ''
            //return
        }
        this.expandedTR = null
        var table = document.createElement("table")
        var t = document.createElement("tbody")
        table.appendChild(t)
        this.decorateWithGroups(result,t,offerInstance.showPrices() ? 6 : 3)
        for (var i = 0; i < result.rows.length; i++) {
            var product = result.rows[i]
            var r = document.createElement("tr");
            t.appendChild(r);
            var td1 = document.createElement("td");
            r.appendChild(td1);
            td1.className = "tableImageTD"
            var im = offer.ViewHelper.createImageView(product.images[0], product.name_string, true)
            im.className = "productImageMini"
            td1.appendChild(im);
            var td2 = document.createElement("td");
            r.appendChild(td2);
            td2.className = "tableTextField"
            var productName = document.createElement("div")
            productName.className = "productName pointerEl"
            productName.innerHTML = product.name_string
            td2.appendChild(productName)
            var td3 = document.createElement("td");
            r.appendChild(td3);
            td3.className = "tableSwitchTD"
            var imSwitch = document.createElement("img");
            td3.appendChild(imSwitch);
            this.decorateImSwitch(r, product, imSwitch, productName)
        }


        if (result.rows.length > 0 && !offerInstance.showPrices()) {
            r = document.createElement("tr");
            t.appendChild(r);
            td1 = document.createElement("td");
            td1.className = 'warningInOffer'
            r.appendChild(td1);
            td1.colSpan = "3"
            td1.innerHTML = jslt.rb.DRB.getString('offer', 'pricesPastLogin')
        }
        var pager = offer.ViewHelper.getPager(result.productsCount, offerInstance.productFilter.limitOnPage, offerInstance.productFilter.currentPage)
        offerInstance.tabView.clearCurrent();
        offerInstance.tabView.getCurrent().appendChild(pager)
        offerInstance.tabView.getCurrent().appendChild(table)
        //offerInstance.tabView.getCurrent().appendChild(pager) TODO
        if (this.productRequiredId != undefined) {
            if (this.productRequiredPage != 0) {
                offerInstance.groupsView.evProductPageChange(this.productRequiredPage)
                this.productRequiredPage = 0
            }
            else {
                var r = $('*[id_product="' + this.productRequiredId + '"]')[0]
                r.onclick();
                this.productRequiredId = undefined
            }
        }
    }
	this.decorateWithGroups=function(result,t,span){
		if (result.groupDescription != '' && result.groupDescription != undefined) {
            var r = document.createElement("tr");
            t.appendChild(r);
            var td1 = document.createElement("td");
            r.appendChild(td1);
			td1.className='descriptionBlock'
            td1.colSpan = span
			if (result.rows.length == 0 && result.groupImage != '' && result.groupImage != undefined) {
                td1.innerHTML += '<img src="' + result.groupImage.filePath + '" class="imageInGroupDescription"/>'
            }
            td1.innerHTML += result.groupDescription
        }
        if (result.groupDocuments != undefined && result.groupDocuments.length > 0) {
            var r = document.createElement("tr");
            t.appendChild(r);
            var td1 = document.createElement("td");
            r.appendChild(td1);
            td1.colSpan = span
			td1.className='descriptionBlock'
            //td1.innerHTML = jslt.rb.DRB.getString('offer', 'productCart') + ' :'
            //td1.appendChild(document.createElement("br"))
            for (var i = 0; i < result.groupDocuments.length; i++) {
                var aDoc = document.createElement("a")
                aDoc.href = result.groupDocuments[i].filePath
                aDoc.target = "_blank"
                aDoc.className = "productDocLink"
                aDoc.innerHTML =  result.groupDocuments[i].description
                td1.appendChild(aDoc)
                td1.appendChild(document.createElement("br"))
            }
        }
	}
    this.groupsTable = function(result){
        offerInstance.tabView.selectById("productsView", true)
        offerInstance.tabView.clearCurrent();
        var table = document.createElement("table")
        table.className = "groupsTable"
        offerInstance.tabView.getCurrent().appendChild(table)
        var t = document.createElement("tbody")
        table.appendChild(t)
		this.decorateWithGroups(result,t,2)
        var r = document.createElement("tr");
        t.appendChild(r);
        var tableCells = []
        for (var j = 0; j < 2; j++) {
            var td1 = document.createElement("td");
            r.appendChild(td1);
            tableCells.push(td1);
        }
        for (var i = 0; i < result.rows.length; i++) {
            var group = result.rows[i]
            var elGroup = document.createElement('div')
            elGroup.className = "groupBox pointerEl"
            elGroup.id_offer_group = group.id_offer_group
            elGroup.onclick = function(){
                offerInstance.groupsView.clickTreeElement({
                    id_offer_group: this.id_offer_group
                })
            }
            if (group.image) {
                var im = offer.ViewHelper.createImageView(group.image, group.name_string)
                elGroup.appendChild(im);
            }
            elGroup.appendChild(document.createElement("br"));
            elGroup.appendChild(document.createTextNode(group.name_string));
            tableCells[((i + 1) <= (result.rows.length / 2))|| i==0  ? 0 : 1].appendChild(elGroup)
        }


    }
    this.decorateImSwitch = function(r, product, imSwitch, textTD){
        imSwitch.className = "imSwitch"
        imSwitch.src = "/modules/layout/ico_right.png"
        $(imSwitch).attr('id_product', product.id_product)
        imSwitch.onclick = function(){
            offerInstance.productsView.evShowDetailsClick(r, product.id_product)
        }
        textTD.onclick = function(){
            offerInstance.productsView.evShowDetailsClick(r, product.id_product)
        }
    }
    /**
     * Po kliknieciu
     * @param {Object} rowRef
     * @param {Object} id
     */
    this.evShowDetailsClick = function(rowRef, id){
        if (this.expandedTR != null) {
            this.expandedTR.childNodes[2].firstChild.src = "/modules/layout/ico_right.png"
            this.expandedTR.childNodes[1].removeChild(this.productInfoDiv)
        }
        if (this.expandedTR == rowRef) {
            this.expandedTR = null
            return
        }
        this.savedQuantity = ""
        this.expandedTR = rowRef
        this.expandedTR.childNodes[2].firstChild.src = "/modules/layout/ico_down.png"
        this.productInfoDiv = document.createElement("div");
        this.productInfoDiv.className = "productInfoDiv"
        this.productInfoDiv.innerHTML = jslt.rb.DRB.getString('common', 'wait')
        this.expandedTR.childNodes[1].appendChild(this.productInfoDiv)
        var p = new cms2.offer.vo.ProductVO()
        this.selectedId = p.id_product = id
        offerInstance.evProductViewRequired(p)
        $.HistoryManager.save(this)
    }
    /**
     * pokazanie produktu po odczycie szczegółów z servera
     * @param {Object} product
     */
    this.showProduct = function(product){
        if (product != null) {
            this.product = product
        }
        $(document).trigger('EVENT_NAVIGATION_PATH_CHANGE', [[{
            label: this.product.name_string,
            toBody: false
        }]])
        //console.log(product);
        this.productInfoDiv.innerHTML = ""
        var form = document.createElement("form")
        this.productInfoDiv.appendChild(form)
        form.id = "addToCartForm"
        var descEl = document.createElement("div")
        descEl.className = "productDescDiv kropeczki"
        descEl.innerHTML = this.product.description_string
        form.appendChild(descEl)
        var codeEl = document.createElement("div")
        codeEl.innerHTML = ''
        var pIdx
        var warningEl
        if (this.product.warehouseItem && this.product.warehouseItem.producer_code!='') {
            codeEl.className = "productDescDiv kropeczki"
            codeEl.innerHTML = jslt.rb.DRB.getString('offer', 'productCode') + ": " + this.product.warehouseItem.producer_code
        }
        else
            if (this.product.listProperties.length > 0) {
                warningEl = document.createElement("div")
                warningEl.className = "productWarning productDescDiv kropeczki"
				var oneNoSelected = false
                for (pIdx = 0; pIdx < this.product.listProperties.length; pIdx++) {
                    if (this.product.listProperties[pIdx].id_selected_value == 0) {
                        oneNoSelected = true
                    }
                }
                if (oneNoSelected) {
                    warningEl.innerHTML = jslt.rb.DRB.getString('offer', 'selectProductOptions')
                }
                else if(!this.product.warehouseItem){
                    warningEl.innerHTML = jslt.rb.DRB.getString('offer', 'productInOptionsUnavailable')
                }
            }
        if (codeEl.innerHTML != '') {
            form.appendChild(codeEl)
        }
        var createLinks = false
        if (this.product.documents.length > 0) {
            createLinks = true
            var aDoc = document.createElement("a")
            aDoc.href = this.product.documents[0].filePath
            aDoc.target = "_blank"
            aDoc.className = "productDocLink"
            aDoc.innerHTML = this.product.documents[0].description!=''?this.product.documents[0].description:jslt.rb.DRB.getString('offer', 'productCart')
        }
        if (this.product.knowledgeItems.length > 0) {
            createLinks = true
            var aKnow = document.createElement("a")
            aKnow.href = this.product.knowledgeItems[0].id_knowledge
            aKnow.classname = "internalLink"
            aKnow.innerHTML = "&gt; " + jslt.rb.DRB.getString('offer', 'kbLinkLabel')
        }
        if (createLinks) {
            var productLinksDiv = document.createElement("div")
            productLinksDiv.className = "productLinksDiv kropeczki"
            if (aDoc != undefined) {
                productLinksDiv.appendChild(aDoc)
            }
            if (aKnow != undefined) {
                productLinksDiv.appendChild(document.createElement("br"))
                productLinksDiv.appendChild(aKnow)
            }
            form.appendChild(productLinksDiv)
        }
        if (warningEl != null && warningEl.innerHTML!='') {
            form.appendChild(warningEl)
        }
        var productProperties = document.createElement("div")
        productProperties.className = "productProperties kropeczki"
        form.appendChild(productProperties)
        var table = document.createElement("table")
        productProperties.appendChild(table);
        var t = document.createElement("tbody")
        table.appendChild(t)
        for (pIdx = 0; pIdx < this.product.listProperties.length; pIdx++) {
            var listP = this.product.listProperties[pIdx]
            var tr = document.createElement("tr")
            t.appendChild(tr)
            var td = document.createElement("td");
            tr.appendChild(td);
            td.className = "productListLabel"
            td.innerHTML = listP.name + ":"
            td = document.createElement("td");
            td.className = "productListOptions"
            tr.appendChild(td)
            var options = document.createElement("select");
            options.className = "selectStyle"
            td.appendChild(options);
            options.onchange = function(){
                offerInstance.productsView.evProductPropertyChange(this)
            }
            options.id = "id_list_property" + listP.id_list_property
            var selUtil = new jslt.element.Select()
            selUtil.createOption(options, "0", "...", true)
            for (var optVIdx = 0; optVIdx < listP.values.length; optVIdx++) {
                selUtil.createOption(options, listP.values[optVIdx].id_product_list_property_value, listP.values[optVIdx].property_value, listP.id_selected_value == listP.values[optVIdx].id_product_list_property_value)
            }
        }
        if (this.product.warehouseItem && offerInstance.showPrices()) {
            tr = document.createElement("tr")
            t.appendChild(tr)
            td = document.createElement("td");
            tr.appendChild(td);
            td.colSpan = "2"
            var priceText = document.createTextNode(jslt.rb.DRB.getString('cart', 'price') + ": ")
            td.appendChild(priceText);
            var priceValueText = document.createElement("span")
            td.appendChild(priceValueText);
            if (this.product.calculatedPrices) {
                priceValueText.className = 'calculatedPricesText'
                var priceValueTextContent = document.createTextNode(jslt.rb.DRB.getString('offer', 'calculatedPrices'))
            }
            else {
                var priceValueTextContent = document.createTextNode(offerInstance.config.authorization_available == 'past_acceptance' ? this.product.warehouseItem.price.netto : this.product.warehouseItem.price.brutto)
            }
            priceValueText.appendChild(priceValueTextContent);
        }
        tr = document.createElement("tr")
        t.appendChild(tr)
        td = document.createElement("td");
        tr.appendChild(td);
        td.colSpan = "2"
        var addToCartRow = document.createElement("div")
        td.appendChild(addToCartRow);
        var qntText = document.createTextNode(jslt.rb.DRB.getString('cart', 'quantity') + ": ")
        addToCartRow.appendChild(qntText);
        var qntInput = document.createElement("input")
        qntInput.name = qntInput.id = "qntInput"
        qntInput.type = "text";
        qntInput.value = this.savedQuantity
        qntInput.className = "inputStyle"
        addToCartRow.appendChild(qntInput);
        var gaugeText = document.createTextNode(" [" + this.product.gauge_name_string + "] ")
        addToCartRow.appendChild(gaugeText);
        addToCartRow.className = "addToCartRow"
        var addToCartBtn = document.createElement("button")
        addToCartBtn.className = "addToCartBtn pointerEl"
        addToCartRow.appendChild(addToCartBtn);
        var wiInCart = false
        var inCartQnt
        var inCartGauge
        if (this.product.warehouseItem) {
            for (var cartItemIdx = 0; cartItemIdx < offerInstance.cartView.cartVO.items.length; cartItemIdx++) {
                if (offerInstance.cartView.cartVO.items[cartItemIdx].warehouseItem.id_warehouse_item == this.product.warehouseItem.id_warehouse_item) {
                    wiInCart = true
                    var ci = offerInstance.cartView.cartVO.items[cartItemIdx]
                    inCartQnt = ci.quantity
                    inCartGauge = ci.product.gauge_name_string
                    break;
                }
            }
        }
        if (wiInCart) {
            qntInput.disabled = "disabled"
            qntInput.value = 'xxx'
            addToCartBtn.title = $.format(jslt.rb.DRB.getString('cart', 'inBasketFormated'), inCartQnt, inCartGauge)
            $(addToCartBtn).tooltip()
        }
        addToCartBtn.innerHTML = jslt.rb.DRB.getString('cart', wiInCart ? 'goToBasket' : 'addToBasket');

        if (!wiInCart) {
            addToCartBtn.qntInput = qntInput
            addToCartBtn.onclick = function(){
                offerInstance.productsView.evAddToCartClick(this)
                return false;
            }
        }
        else {
            addToCartBtn.onclick = function(){
                offerInstance.cartView.showCartView()
                return false;
            }
        }

        if (!this.product.warehouseItem) {
            addToCartBtn.disabled = "disabled"
        }
        if (this.product.packagings.length > 0) {
            tr = document.createElement("tr")
            t.appendChild(tr)
            td = document.createElement("td");
			td.colSpan = "2"
            tr.appendChild(td);
            td.innerHTML = jslt.rb.DRB.getString('offer', 'packaging') + ": " + this.product.packagings[0].name_string + " " + this.product.packagings[0].quantity + " " + this.product.gauge_name_string
        }
        $("#addToCartForm").validate({
            errorPlacement: function(error, element){
                error.appendTo(element.parent());
            },
            rules: {
                qntInput: {
                    required: true,
                    number: true
                }
            },
            messages: {
                qntInput: jslt.rb.DRB.getString('validator', 'numberWrite')
            },
            submitHandler: function(){
            }
        });
    }
    this.evAddToCartClick = function(ref){
        $("#qntInput").val($("#qntInput").val().replace(/,/, "."))
        if ($("#addToCartForm").valid()) {
            ref.innerHTML = jslt.rb.DRB.getString('cart', 'goToBasket')
            ref.qntInput.disabled = "disabled"
            ref.title = jslt.rb.DRB.getString('cart', 'gotToBasketModifi')
            $(ref).tooltip()
            ref.onclick = function(){
                offerInstance.cartView.showCartView()
                return false;
            }
            offerInstance.cartView.cartVO.warehouseItem = this.product.warehouseItem;//new cms2.offer.vo.WarehouseItemVO()
            offerInstance.cartView.cartVO.warehouseItem.quantity = document.getElementById("qntInput").value
            offerInstance.addShoppingCartItem(offerInstance.cartView.cartVO)
            ref.qntInput.value = 'xxx'
        }
    }
    this.evProductPropertyChange = function(listRef){
        offerInstance.serviceDelegate.a;
        for (var pIdx = 0; pIdx < this.product.listProperties.length; pIdx++) {
            if (("id_list_property" + this.product.listProperties[pIdx].id_list_property) == listRef.id) {
                this.product.listProperties[pIdx].id_selected_value = listRef.options[listRef.selectedIndex].value;
                offerInstance.evProductViewRequired(this.product)
                break;
            }
        }
    }
    this.saveState = function(){
        var p = {
            id_product: this.selectedId
        }
        return {
            hmgrp: 'ProductsView',
            params: p
        }
    }
    this.loadState = function(params){
        if (params.hmgrp == 'ProductsView') {
            offerInstance.productsView.productRequiredId = params.id_product
            offerInstance.serviceDelegate.findProductPath(params.id_product)
        }
    }
    /**
     * Listen for requirement
     */
    this.evProductRequired = function(e, params){
        offerInstance.productsView.productRequiredId = params.id_product
        offerInstance.serviceDelegate.findProductPath(params.id_product)
    }
    this.evFindProductPathResult = function(e, arr){
        offerInstance.productsView.productRequiredPage = Math.floor(arr[2] / offerInstance.productFilter.limitOnPage)
    }
    $.HistoryManager.register(this)
    $(document).bind('evProductRequired', this.evProductRequired)
    $(document).bind('evFindProductPathResult', this.evFindProductPathResult)
}

