var basketAddFunction = '';
var basketSearch = '0';

/**
* SSTL product information basket functions.
*/

function downloadPDFSheets()
{
    if ( !checkBasketSelectedProductCount() ) return false;

    if ( !checkBasketSelectedProductCountMax(50) )
    {
        alert(arrText['JS_Error_PDF_Sheets_Too_Many_Products']);
    }
    else
    {
        window.open(systemUrl + 'tuotetietokansio/?Action=printPDF&type=sheets&rows=selected', '_blank');
    }
}

function downloadPDFSheetsAll()
{
    if (!checkBasketProductCount()) return false;

    if ( !checkBasketProductCountMax(50) )
    {
        alert(arrText['JS_Error_PDF_Sheets_Too_Many_Products']);
    }
    else
    {
        window.open(systemUrl + 'tuotetietokansio/?Action=printPDF&type=sheets', '_blank');
    }
}

function downloadExcelAll()
{
    if (!checkBasketProductCount()) return false;

    if ( checkDownloadTermsAgreement() )
    {
        location.href= systemUrl +'tuotetietokansio/?Action=exportExcel&terms_agree=1';
    }
    return false;
}

function downloadExcelSelected()
{
    if (!checkBasketSelectedProductCount()) return false;

    if ( checkDownloadTermsAgreement() )
    {
        location.href= systemUrl +'tuotetietokansio/?Action=exportExcel&rows=selected&terms_agree=1';
    }
    else return false;
}

function downloadExcelAllwEmail()
{
    if (!checkBasketProductCount() ) return false;

    $('#fldExportRows').val('all');

    if ($('#fldExportEmail').val() == '' )
    {
        alert(arrText['JS_Error_Missing_Email']);
    }
    else
    {
        if ( checkDownloadTermsAgreement() )
        {
            document.forms.frmExportExcel.submit();
        }
    }
    return false;
}

function downloadExcelSelectedwEmail()
{
    if (!checkBasketSelectedProductCount() )
    {
        return false;
    }

    $('#fldExportRows').val('selected');
    if ($('#fldExportEmail').val() == '' )
    {
        alert(arrText['JS_Error_Missing_Email']);
    }
    else
    {
        if ( checkDownloadTermsAgreement() )
        {
            document.forms.frmExportExcel.submit();
        }
    }
    return false;
}

function checkDownloadTermsAgreement()
{
    if ( $('#download-terms-agree').is(':checked') )
    {
        return true;
    }
    else
    {
        alert(arrText['JS_Error_Term_Agreement_Required']);

        return false;
    }
}

function checkBasketProductCount()
{
    if ( $('#basketProducts').val() == '0' )
    {
        alert(arrText['Basket_Error_JS_Basket_Is_Empty']);
        return false;
    }

    return true;
}

function checkBasketProductCountMax(maxVal)
{
    if ((maxVal == null)||(maxVal=='')||(maxVal==0)) return true;

    if ( $('#basketProducts').val() > maxVal )
    {
        return false;
    }

    return true;
}


function checkBasketSelectedProductCount()
{
    if ($('#selectedProducts').val() == '0')
    {
        alert(arrText['Basket_Error_JS_No_Products_Selected']);
        return false;
    }
    return true;
}

function checkBasketSelectedProductCountMax(maxVal)
{
    if ((maxVal == null)||(maxVal=='')||(maxVal==0)) return true;

    if ($('#selectedProducts').val() > maxVal )
    {
        return false;
    }
    return true;
}


function setBasketInfo(info, productCount)
{
    setBasketLinkVisibility(productCount);
    $('#basket-item-count').text(info);
}

function setBasketLinkVisibility(productCount)
{
    if ( productCount == 0 )
    {
        hide('#basket-open-link');
    }
    else
    {
        show('#basket-open-link');
    }
}

function setBasketAddFunctionState(isReady, cmd, cmdLabel)
{
    if ( isReady == false )
    {
        basketAddFunction = '';
        $('#basket-add-all').text(arrText['JS_Loading_Product_List']);
    }
    else
    {
        basketAddFunction = cmd;
        $('#basket-add-all').text(cmdLabel);
    }
}

function addToBasket(productId, productSheetView)
{
    $.ajax({
           type: "POST",
           data: "Module=Product&File=basket&Action=addToBasket&id=" + productId,
           url: ajaxUrl,
           async: true,
           success: function(response)
           {
                var basketInfo = '';
                var productCount = 0;
                if ( response != '' )
                {
                    if ( response == '-2' )
                    {
                        alert(arrText['Product_Basket_Full']+'\n'+arrText['Product_Basket_Full_Ln2']);
                        return;
                    }
                    else
                    {
                        var pos = response.indexOf(';');
                        if ( pos > -1 )
                        {
                            basketInfo = response.substr(pos+1);
                            response = response.substr(0, pos);

                            pos = basketInfo.indexOf(';');
                            if ( pos > -1 )
                            {
                                productCount = basketInfo.substr(0, pos);
                                basketInfo = basketInfo.substr(pos+1);
                            }
                        }
                    }
                }
                if ( response == '1' )
                {
                    if ( productSheetView == 1 )
                    {
                        setFunction_BasketRemove_ProductSheet(productId);
                    }
                    else
                    {
                        setFunction_BasketRemove(productId);
                    }
                    setBasketInfo(basketInfo, productCount);
                    setBasketDisplay(productCount);
                }
                else
                {
                    if ( productSheetView == 1 )
                    {
                        setFunction_BasketAdd_ProductSheet(productId);
                    }
                    else
                    {
                        setFunction_BasketAdd(productId);
                    }
                }
           },
           error: function(request,error)
           {
           }
    });
}

function removeFromBasket(productId, productSheetView)
{
    $.ajax({
            type: "POST",
            data: "Module=Product&File=basket&Action=removeFromBasket&id=" + productId,
            url: ajaxUrl,
            async: true,
            success: function(response)
            {
                var basketInfo = '';
                var productCount = 0;
                if ( response != '' )
                {
                    var pos = response.indexOf(';');
                    if ( pos > -1 )
                    {
                        basketInfo = response.substr(pos+1);
                        response = response.substr(0, pos);

                        pos = basketInfo.indexOf(';');
                        if ( pos > -1 )
                        {
                            productCount = basketInfo.substr(0, pos);
                            basketInfo = basketInfo.substr(pos+1);
                        }
                    }
                }
                if ( response == '1' )
                {
                    if ( productSheetView == 1 )
                    {
                        if ( productId == -1 )
                        {
                            $('.basket-func').each(function()
                            {
                                arrId = this.id.split(/_/);
                                setFunction_BasketAdd_ProductSheet(arrId[1]);
                            });
                        }
                        else
                        {
                            setFunction_BasketAdd_ProductSheet(productId);
                        }
                    }
                    else
                    {
                        if ( productId == -1 )
                        {
                            $('.basket-func').each(function()
                            {
                                arrId = this.id.split(/_/);
                                setFunction_BasketAdd(arrId[1]);
                            });
                        }
                        else
                        {
                            setFunction_BasketAdd(productId);
                        }
                    }
                    setBasketInfo(basketInfo, productCount);
                    setBasketDisplay(productCount);
                }
                else
                {
                    if ( productSheetView == 1 )
                    {
                        setFunction_BasketRemove_ProductSheet(productId);
                    }
                    else
                    {
                        setFunction_BasketRemove(productId);
                    }
                }
           }
    });
}

function addToBasket_All()
{
    if (( basketAddFunction == null ) || ( basketAddFunction == '' ))
    {
        return false;
    }

    var visibleProducts = '&check=' + getSelectionProductIDs();
    var searchMode = '&search=' + basketSearch;

    show('#basket-add-loader');

    $.ajax({
            type: "POST",
            data: "Module=Product&File=basket&Action=addToBasketBatch" + basketAddFunction + visibleProducts + searchMode,
            url: ajaxUrl,
            async: true,
            success: function(response)
            {
                var showMsgFull = false;
                var productCount = 0;
                var basketInfo = '';
                var checkData = '';
                var checked = new Array();
                if ( response != '' )
                {
                    if ( response == '-2' )
                    {
                        showMsgFull = true;
                    }
                    else
                    {
                        var pos = response.indexOf(';');
                        if ( pos > -1 )
                        {
                            var respParts = response.split(';');
                            if ( respParts.length > 0 ) response = respParts[0];
                            if ( respParts.length > 1 ) productCount = respParts[1];
                            if ( respParts.length > 2 ) basketInfo = respParts[2];
                            if ( respParts.length > 3 ) checkData = respParts[3];
                        }

                        if ( response !== '0' )
                        {
                            if ( checkData != '' )
                            {
                                checked = checkData.split(',');
                                for (var tx=0; tx < checked.length; tx++)
                                {
                                    setFunction_BasketRemove(checked[tx]);
                                }
                            }
                            setBasketInfo(basketInfo, productCount);
                            setBasketDisplay(productCount);
                            if ( response == '-2' )
                            {
                                showMsgFull = true;
                            }
                        }
                    }
                }
                hide('#basket-add-loader');
                if ( showMsgFull )
                {
                    alert(arrText['Product_Basket_Full']+'\n'+arrText['Product_Basket_Full_Ln2']);
                }
            }
    });
}

function getSelectionProductIDs()
{
    var tmp = new Array();
    var tmpIdx = 0;

    $('.basket-func').each(function(i, e) {
        var selId = $(this).attr('id');
        var pos = selId.indexOf('_');

        if ( pos > -1 )
        {
            var productId = selId.substr(pos+1);
            tmp[tmpIdx] = productId;
            tmpIdx++;
        }
    });
    return tmp;
}

function setFunction_BasketAdd(productId)
{
    $('#basket_' + productId).html("<a href=\"javascript: addToBasket(" + productId + ");\"><img src=\"/images_system/icon_box_add_item_to_box.gif\" border=\"0\" alt=\""
        + arrText['Product_Basket_Add'] + "\" title=\"" + arrText['Product_Basket_Add'] + "\"></a>");
}

function setFunction_BasketAdd_ProductSheet(productId)
{
    $('#basket_' + productId).removeClass('basket-link-remove').addClass('basket-link-add');
    $('#basket_' + productId).html("<a href=\"javascript: addToBasket(" + productId + ", 1);\">" + arrText['Product_Basket_Add'] + "</a>");
}

function setFunction_BasketRemove(productId)
{
    $('#basket_' + productId).html("<a href=\"javascript: removeFromBasket(" + productId + ");\"><img src=\"/images_system/icon_box_item_on_box.gif\" border=\"0\" alt=\""
        + arrText['Product_Basket_Remove'] + "\" title=\"" + arrText['Product_Basket_Remove'] + "\"></a>");
}

function setFunction_BasketRemove_ProductSheet(productId)
{
    $('#basket_' + productId).removeClass('basket-link-add').addClass('basket-link-remove');
    $('#basket_' + productId).html("<a href=\"javascript: removeFromBasket(" + productId + ", 1);\">" + arrText['Product_Basket_Remove'] + "</a>");
}

function applyOpacity()
{
    $('.basket-item').prop('disabled', true);
}

function removeOpacity()
{
    $('.basket-item').prop('disabled', false);
}

function basketSelectAsync(productId)
{
    var val = '';
    var changeVal = 0;
    if ($('#item_' + productId).prop('checked') == true)
    {
        val = 1;
        changeVal = 1;
    }
    else
    {
        val = 0;
        changeVal = -1;
    }

    $.ajax({
           type: "POST",
           data: "Module=Product&File=basket&Action=selection&id=" + productId + "&value="+val,
           url: ajaxUrl,
           async: true,
           success: function(response)
           {
                if (response == '1')
                {
                    var selcount = $('#selectedProducts').val();
                    $('#selectedProducts').val(parseInt(selcount) + changeVal);
                }
                else if (response == '0')
                {
                    if ( changeVal == -1 )
                    {
                        $('#item_' + productId).prop('checked', true);
                    }
                    else
                    {
                        $('#item_' + productId).prop('checked', false);
                    }
                    alert(arrText['Basket_Error_JS_Selection_Failed']);
                }
           }
    });
}

function basketSelectSync(productId)
{
    var val = '';
    var changeVal = 0;
    if ($('#item_' + productId).prop('checked') == true)
    {
        val = 1;
        changeVal = 1;
    }
    else
    {
        val = 0;
        changeVal = -1;
    }

    var response = $.ajax({
                         type: "POST",
                         data: "Module=Product&File=basket&Action=selection&id=" + productId + "&value="+val,
                         url: ajaxUrl,
                         async: false
                         }).responseText;

    if (response == '1')
    {
        var selcount = $('#selectedProducts').val();
        $('#selectedProducts').val(parseInt(selcount) + changeVal);
    }
    else
    {
        if ( changeVal == -1 )
        {
            $('#item_' + productId).prop('checked', true);
        }
        else
        {
            $('#item_' + productId).prop('checked', false);
        }
        alert(arrText['Basket_Error_JS_Selection_Failed']);
    }
}

function basketSelect(productId)
{
    $('#export-excel-options').hide();
    basketSelectAsync(productId);
}

function handleBasketItemSelection()
{
    $('#export-excel-options').hide();

    var shownItems = getSelectionProductIDs();
    var visibleProducts = '&check=' + shownItems;
    var checkValue = 0;
    if ($('#basket-select-all').prop('checked') == true)
    {
        checkValue = 1;
    }
    $.ajax({
       type: "POST",
       data: "Module=Product&File=basket&Action=selectAll&value=" + checkValue + visibleProducts,
       url: ajaxUrl,
       async: true,
       success: function(response)
       {
            if ( response != '0' )
            {
                var tmp = new Array();

                var respParts = response.split(';');
                if ( respParts.length > 2 )
                {
                    $('#selectedProducts').val(parseInt(respParts[1]));

                    var checked = respParts[2].split(',');

                    for (var tx=0; tx < checked.length; tx++)
                    {
                        tmp[checked[tx]] = 1;
                    }

                }
                for (tx =0; tx < shownItems.length; tx++)
                {
                    var checkItem = shownItems[tx];

                    if (( tmp[checkItem] != null ) && (tmp[checkItem] == 1) )
                    {
                        $('#item_' + checkItem).prop('checked', true);
                    }
                    else
                    {
                        $('#item_' + checkItem).prop('checked', false);
                    }
                }

            }
       }
    });
}

function saveBasket(dialogTitle)
{
    var response = $.ajax({
                         type: "POST",
                         data: "Module=Product&File=basket&Action=save",
                         url: ajaxUrl,
                         async: false
                         }).responseText;

    if (response == '0')
    {
        alert(arrText['JS_Save_Failed']);
    }
    else if ( response == '1' )
    {
        alert(arrText['JS_Save_Empty_Basket']);
    }
    else
    {
        $('#basket-save-url').val(systemUrl + 'tuotetietokansio/?id=' + response);
        $('#basket-save-url').prop('disabled', false);
        //$('#basket-save-info').show();
        openBasketDialog('basket-save-info', dialogTitle);
    }
    return false;
}

function basketContentExport(dialogTitle)
{
    var response = $.ajax({
                         type: "POST",
                         data: "Module=Product&File=basket&Action=getExportControl",
                         url: ajaxUrl,
                         async: false
                         }).responseText;

    if ( response != '' )
    {
        var totControl = 0;
        var selControl = 0;

        var respParts = response.split(';');
        if ( respParts.length > 0 ) totControl = parseInt(respParts[0]);
        if ( respParts.length > 1 ) selControl = parseInt(respParts[1]);

        if ( totControl == 1 ) // < 100
        {
            $('#export-excel-all').show();
        }
        else // > 100
        {
            $('#export-excel-all').hide();
            $('#export-excel-batch').show();
            $('#export-excel-all-batch').show();
        }
        if ( selControl == 1 ) // < 100
        {
            $('#export-excel-selected').show();
        }
        else // > 100
        {
            $('#export-excel-selected').hide();
            $('#export-excel-batch').show();
            $('#export-excel-selected-batch').show();
        }

        //$('#export-excel-options').show();
        //alert('Response: ' + response + '\n\ntot: ' + totControl + ' sel: '+ selControl);
        
        openBasketDialog('export-excel-options', dialogTitle);
   }
}

// General function to show form as dialog
function openBasketDialog(containerId, containerTitle)
{
    
    $('div#' + containerId).dialog({
        title: containerTitle,
        width: '600px',
        modal: true
    });
}

$("h2.trigger").click(function()
{
    $(this).toggleClass("active").next().slideToggle("slow");
});
