var product_direct; // direction of sorting products

var get_id;
var get_page;
var get_lng;
var get_w;
var get_q;

var last_id = 0;
var last_data = '';
var last_id_arr = new Array();

var skladovky = '';

function attachEvents () {
    // if element exists bind click event for adding to basket
    if ( $('.form_product_basket_add form').length > 0 ) {

        $('.form_product_basket_add form').submit ( function () {
            return add_to_basket ( $(this), true );
        });
    }

    // product settings
    attachEvents_views();
    attachEvents_paging();
    attachEvents_settings();
    
    // large images when moving mouse over an small image
    screenshotPreview();

    // show stock status
    showBubble();    
}

function load_page() {

    var link = window.location.href;
    var after = link.split('#')[1];
    var odkaz_stranka = 0;
    var a_page;

    if ( $('#products_dump .column .column_right .paging .box span.page_actual').length > 0 ) {
        var sA_page = $('#products_dump .column .column_right .paging .box span.page_actual:eq(0)').text();
        if ( sA_page != undefined && sA_page != '' && sA_page > 0 ) {
            a_page = parseInt ( sA_page );
        }
    }

    if ( after != undefined && after.length > 1 ) {
        after = after.substr(1); // odstranime p
        odkaz_stranka = parseInt ( after );
    } else {
        if ( a_page > 1 ) {
            odkaz_stranka = 1;
        }
    }

    if ( odkaz_stranka != 0 ) {
        showLoaders();

        get_get ();

        $.ajax ( {
            type: 'POST',
            dataType: 'html',
            cache: false,
            url: domain + '/web/pages/products/products_paging.php',
            data: { 'page_number': odkaz_stranka, 'get_id': get_id, 'get_page': get_page, 'get_lng': get_lng, 'w': get_w, 'q': get_q, 'sklc': skladovky },

            beforeSend: function() {
            },

            success: function ( data ) {
                $("#products_dump").html ( data );
                //$(document).scrollTop ( 0 );
                attachEvents();
                hideLoaders();
            }
        } );
    }
}

$(document).ready ( function () {
    // product parameters
    attachEvents_parameters();
    // search page
    //attachEvents_search ();
    // other events
    attachEvents ();

    $.history.init(function() {
        load_page();
    });

});

function add_to_basket ( this_object, form ) {
    
    var skl_cis;
    var lng;
    var unit;
    var quantity;
    var nazev;
    var imgsrc;

    if ( form ) {
        skl_cis = $(this_object).contents().find( 'input[name="skl_cis"]' ).val();
        lng = $(this_object).contents().find( 'input[name="lng"]' ).val();
        unit = $(this_object).contents().find( 'input[name="unit"]' ).val();
        quantity = $(this_object).contents().find( 'input[name="quantity"]' ).val();

        nazev = $(this_object).contents().find( 'input[name="nazev"]' ).val();
        imgsrc = $(this_object).contents().find( 'input[name="imgsrc"]' ).val();
    } else {
        skl_cis = $(this_object).parents('form').contents().find( 'input[name="skl_cis"]' ).val();
        lng = $(this_object).parents('form').contents().find( 'input[name="lng"]' ).val();
        unit = $(this_object).parents('form').contents().find( 'input[name="unit"]' ).val();
        quantity = $(this_object).parents('form').contents().find( 'input[name="quantity"]' ).val();

        nazev = $(this_object).parents('form').contents().find( 'input[name="nazev"]' ).val();
        imgsrc = $(this_object).parents('form').contents().find( 'input[name="imgsrc"]' ).val();
    }


    get_get ();

    var div = '<div id="basket_added_item"><div class="box">';
    div += '<h2>Vlo\u017eili jste do ko\u0161íku</h2>'; // misto ks dat jednotku... a misto skladovky ( nebo ke skladovce ) dat nazev polozky
    if ( imgsrc.length > 0 ) {
        div += '<div class="left"><img src="' + imgsrc.toString() + '" alt="' + nazev.toString() + '"></div>';
    }
    div += '<div class="right"><p><strong>' + quantity.toString() + ' ' + unit.toString() + '</strong> ' + nazev.toString() + ' (' + skl_cis.toString() + ').<p><a href="?act=basket">P\u0159ejít do ko\u0161íku</a></div>';
    div += '</div></div>';

    $.ajax({
    type: 'POST',
    dataType: 'html',
    cache: false,
    url: domain + '/web/pages/basket/basket_add.php',
    data: {'get_id': get_id, 'get_page': get_page, 'get_lng': get_lng,
            'skl_cis': skl_cis, 'lng': lng, 'quantity': quantity, 'ajax': true
    },

    beforeSend: function() {

    },

    success: function(data) {

        var tf = data.split('#')[0];

        if ( tf == 'False' ) {
            //window.alert ('Nic se nepřidalo. Není na skladě.');
            
        } else {
            data = data.substr ( tf.length + 1 );
        
            $("#head_basket").html(data);

            if ( $('#basket_added_item').length > 0 ) {
                $('#basket_added_item').animate({
                    'top': '-=110px'
                }, 400, function () {
                    $(this).remove();
                    $('#layout_centering').append(div);
                    $('#basket_added_item').css("left",( ($(window).width()/2) - ($("#basket_added_item").width()/2)) + "px");
                    $('#basket_added_item').animate({
                        'top': '+=110px'
                    }, 750).oneTime(5000, function() {
                        $(this).animate({
                            'top': '-=110px'
                        }, 500, function () {
                            $(this).remove();
                        });
                    });
                });
            } else {
                $('#layout_centering').append(div);
                $('#basket_added_item').css("left",( ($(window).width()/2) - ($("#basket_added_item").width()/2)) + "px");
                $('#basket_added_item').animate({
                    'top': '+=110px'
                }, 750).oneTime(5000, function() {
                    $(this).animate({
                        'top': '-=110px'
                    }, 500, function () {
                        $(this).remove();
                    });
                });
            }
        }
    }

    });

    return false;
}

function attachEvents_settings () {
    product_direct = parseInt ( $('#product_direct').val() ); // default value

    $('#product_direct_1').click ( function () {
        product_direct = 1;
        get_settings();
        return false;
    });

    $('#product_direct_2').click ( function () {
        product_direct = 2;
        get_settings();
        return false;
    });

    $('#product_sorting').change ( function () {
        get_settings();
    });

    $('#product_price').change ( function () {
       get_settings();
    });

    $('#product_count').change ( function () {
       get_settings();
    });

}

function attachEvents_views () {
    $('#products_dump .column .column_left #bookmark_type_2_left ul li a').click ( function () {
        return change_view ( $(this) );
    });
}

function attachEvents_paging () {
    $('#products_dump .column .column_right .paging .box a').click ( function () {
        return change_page ( $(this) );
    } );
}

function get_get () {
    get_id = $('#get_id').val();
    get_page = $('#get_page').val();
    get_lng = $('#get_lng').val();


    if ( $('#search form fieldset input[name="w1"]').length > 0 ) {
        var w1 = $('#search form fieldset input[name="w1"]').attr('checked');
        var w2 = $('#search form fieldset input[name="w2"]').attr('checked');
        var w3 = $('#search form fieldset input[name="w3"]').attr('checked');
        var w4 = $('#search form fieldset input[name="w4"]').attr('checked');
        var w5 = $('#search form fieldset input[name="w5"]').attr('checked');

        w1 = w1 ? 1 : 0;
        w2 = w2 ? 1 : 0;
        w3 = w3 ? 1 : 0;
        w4 = w4 ? 1 : 0;
        w5 = w5 ? 1 : 0;

        get_w = w1.toString() + w2.toString() + w3.toString() + w4.toString() + w5.toString();
    } else {
        get_w = '00000';
    }

    if ( $('#search form fieldset span input[name="q"]').length > 0 ) {
        get_q = $('#search form fieldset span input[name="q"]').val();
        //window.location.href = domain + '/' + get_lng + '/search/#w=' + get_w + '&q=' + get_q;
    } else {
        get_q = '';
    }
        
}

function get_settings () {

    showLoaders();
    get_get ();

    var product_sorting = $('select#product_sorting option:selected').attr('value');
    var product_price = $('select#product_price option:selected').attr('value');
    var product_count = $('select#product_count option:selected').attr('value');

    $.ajax({
        type: 'POST',
        dataType: 'html',
        cache: false,
        url: domain + '/web/pages/products/products_settings.php',
        data: {'get_id': get_id, 'get_page': get_page, 'get_lng': get_lng, 'w': get_w, 'q': get_q,
                'product_sorting': product_sorting, 'product_direct': product_direct, 'product_price': product_price, 'product_count': product_count, 'sklc': skladovky},

        beforeSend: function(){

        },

        success: function ( data ) {
            $("#products_dump").html ( data );
            attachEvents();
            hideLoaders();
        }
    });
}

function change_view ( this_object ) {

    showLoaders();
    get_get ();

    var typ_pohledu = parseInt ( $(this_object).attr('rel') );

    $.ajax({
        type: 'POST',
        dataType: 'html',
        cache: false,
        url: domain + '/web/pages/products/products_views.php',
        data: {'get_type': typ_pohledu, 'get_id': get_id, 'get_page': get_page, 'get_lng': get_lng, 'w': get_w, 'q': get_q, 'sklc': skladovky},

        beforeSend: function(){

        },

        success: function ( data ) {
            $("#products_dump").html(data);
            attachEvents();
            hideLoaders();
        }
    });

    return false;
}

function change_page ( this_object ) {

    showLoaders();
    var odkaz_stranka = parseInt ( $(this_object).attr('rel') );

    get_get ();

    $.ajax({
        type: 'POST',
        dataType: 'html',
        cache: false,
        url: domain + '/web/pages/products/products_paging.php',
        data: { 'page_number': odkaz_stranka, 'get_id': get_id, 'get_page': get_page, 'get_lng': get_lng, 'w': get_w, 'q': get_q, 'sklc': skladovky },

        beforeSend: function() {
        },

        success: function ( data ) {
            $("#products_dump").html ( data );
            $(document).scrollTop ( 0 );
            attachEvents();
            hideLoaders();
        }
    });

    // return false;
}

function attachEvents_search () {

    if ( $('#search form fieldset input.button').length > 0 ) {

        get_get ();

        $('#search form').submit ( function () {
            search_init ();
            return false;
        });

        $('#search form fieldset input[name="q"]').focus ( function () {
            if ( $(this).val() == 'Hledaný text\u2026' ) {
                $(this).val( '' );
            }
        });

        $('#search form fieldset input[name="q"]').blur ( function () {
            if ( $(this).val() == '' ) {
                $(this).val( 'Hledaný text\u2026' );
            }
        });
    }
}

function search_init () {
    
    showLoaders();

    var lng = $('#search form fieldset input[name="lng"]').val();
    var q = $('#search form fieldset input[name="q"]').val();

    var w1 = $('#search form fieldset input[name="w1"]').attr('checked');
    var w2 = $('#search form fieldset input[name="w2"]').attr('checked');
    var w3 = $('#search form fieldset input[name="w3"]').attr('checked');
    var w4 = $('#search form fieldset input[name="w4"]').attr('checked');
    var w5 = $('#search form fieldset input[name="w5"]').attr('checked');

    w1 = w1 ? 1 : 0;
    w2 = w2 ? 1 : 0;
    w3 = w3 ? 1 : 0;
    w4 = w4 ? 1 : 0;
    w5 = w5 ? 1 : 0;

    var w = w1.toString() + w2.toString() + w3.toString() + w4.toString() + w5.toString();

    //window.alert ('attachEvents_search: pred ajaxem.');

    $.ajax ({
        type: 'POST',
        dataType: 'html',
        url: domain + '/web/pages/products/search_ajax.php',
        data: { 'get_lng': lng, 'w': w, 'q': q, 'ajax': true }, //'w1': w1, 'w2': w2, 'w3': w3, 'w4': w4

    beforeSend: function(){

    },
    success: function ( data ) {

        $('#products_dump').html( data.toString() );

        //window.alert ('attachEvents_search: ajax success.');

        attachEvents();

        // TODO window.location.href = domain + '/' + lng + '/search/#w=' + w + '&q=' + q;

        // schovat "loader"
        hideLoaders ();
    }
    });
}

function attachEvents_parameters() {

    last_data = $('#product_filter_parameters_data').val();

    // if all is checked, unchecked
    /*
    $('#product_filter_parameters ul li span.filter_parameters_head span.filter_parameters_head_box input').change (
        function () {
            var id = $(this).attr('id');
            var checked = $(this).attr('checked'); // true, false

            var nid = 'f' + id;
            if ( checked ) {
                $('#product_filter_parameters ul li span.filter_parameters_body ul#' + nid.toString() + ' li input').attr( 'checked', !checked );
            }

            onFilter();
        }
    );
    */

    // if reset is clicked

    $('#product_filter_parameters ul li .product_filter_parameters_box .filter_parameters_head .filter_parameters_head_box a').click ( function () {
        var pid = $(this).attr('rel'); // parametr id

        if ( pid == undefined ) {
            return false;
        }

        $('#product_filter_parameters ul li span.filter_parameters_body ul#fall' + pid.toString() + ' li input').each ( function () {
            $(this).attr('checked', false);
            $(this).attr('disabled', false);
        } );

        onFilter();

        return false;
    } );

    // if any of other checkboxes is checked, unchecked
    $('#product_filter_parameters ul li span.filter_parameters_body ul li input').click (
        function () {

            var ul_id = $(this).parents('ul').attr('id');
            last_id = ul_id.substr(4);

            if ( $(this).attr('checked') ) {
                last_id_arr.push ( $(this).attr('id').substr(1) ); // param-hod
            } else {
                var lia = new Array();
                for ( var i = 0; i < last_id_arr.length; i++ ) {
                    if ( last_id_arr[i] == $(this).attr('id').substr(1) ) {
                        continue;
                    }
                    lia.push ( last_id_arr[i] );
                }
                last_id_arr = lia;
            }

            //var all_id = ul_id.substr(1);

            // check if are all checked
            //checkForAll ( ul_id, all_id );

            onFilter();
        }
    );

}

// check if all checkboxes are checked, if true, check the ALL checkbox
/*
function checkForAll ( ul_id, all_id ) {
    var check = true;

    $('#product_filter_parameters ul li span.filter_parameters_body ul#' + ul_id.toString() + ' li input').each (
        function () {
            if ( $(this).attr( 'checked' ) ) {
                check = false;
            }
        }
    );

    $('#' + all_id.toString() ).attr ( 'checked', check );
}
*/
function showLoaders () {

    var w, h, t, l;

    if ( $('#product_filter_parameters').length > 0 ) {
        w = $('#product_filter_parameters').width();
        h = $('#product_filter_parameters').height();
        t = $('#product_filter_parameters').offset().top;
        l = $('#product_filter_parameters').offset().left;

        $('body').append('<div id="products_parameters_loader"></div>');
        $('#products_parameters_loader').css('position', 'absolute')
                                        .css('width', w.toString() + 'px')
                                        .css('height', h.toString() + 'px')
                                        .css('top', t.toString() + 'px')
                                        .css('left', l.toString() + 'px');
    }


    if ( $('#products_dump').length > 0 ) {
        w = $('#products_dump').width();
        h = $('#products_dump').height();
        t = $('#products_dump').offset().top;
        l = $('#products_dump').offset().left;

        $('body').append('<div id="products_loader"></div>');
        $('#products_loader')   .css('position', 'absolute')
                                .css('width', w.toString() + 'px')
                                .css('height', h.toString() + 'px')
                                .css('top', t.toString() + 'px')
                                .css('left', l.toString() + 'px');
    }

}

function hideLoaders () {
    if ( $('#products_loader').length > 0 ) {
        $('#products_loader').remove();
    }
    if ( $('#products_parameters_loader').length > 0 ) {
        $('#products_parameters_loader').remove();
    }
}

function onFilter () {

    // zobrazit loader
    showLoaders();

    get_get();

    var filter_idh = new Array();

    $('#product_filter_parameters ul li span.filter_parameters_body ul li input').each ( // [name="x' + i.toString() + '"]
        function () {
            var id_ = $(this).attr('name');
            var checked_ = $(this).attr('checked');

            if ( checked_ ) {
                if ( id_.length > 1 ) {

                    var uid = $(this).parents('ul').attr('id');

                    if ( $('#product_filter_parameters ul li span.filter_parameters_body ul#' + uid.toString() + ' li input').length > 1 ) {
                        filter_idh.push ( id_.substr(1) );
                    }
                }
            }
        }
    );

    var filter_idp = new Array ();

    $('#product_filter_parameters ul li span.filter_parameters_head input').each (
        function () {
            var id_ = $(this).attr('id');
            if ( id_.length > 3 ) {
                filter_idp.push ( id_.substr(3) );
            }
        }
    );

    var filter_idps = new Array ();

    $('#product_filter_parameters ul li span.filter_parameters_body ul li input').each (
        function () {
            var id_ = $(this).attr('id');
            var checked_ = $(this).attr('checked');

            if ( checked_ ) {
                id_ = $('#' + id_.toString() ).parents('ul').attr('id').substr(4);
                var do_add = true;

                for ( var i = 0; i < filter_idps.length; i ++ ) {
                    if ( id_ == filter_idps[i] ) {
                        do_add = false;
                        break;
                    }
                }

                if ( do_add ) {
                    filter_idps.push ( id_ );
                }
            }
        }
    );

    var filter_idpa = new Array ();

    $('#product_filter_parameters ul li span.filter_parameters_body ul li input').each (
        function () {
            var id_ = $(this).attr('id');
            var checked_ = $(this).attr('checked');
            //var dis_ = $(this).attr('disabled');

            if ( checked_ /*&& !dis_*/ ) {
                var idp = $('#' + id_.toString() ).parents('ul').attr('id').substr(4);
                var idh = $('#' + id_.toString() ).attr('name').substr(1);

                filter_idpa.push ( idp.toString() + '#' + idh.toString() );
            }
        }
    );

    var last_checked_id = 0; // prvni zaskrtnuty parametr
    if ( last_id_arr.length > 0 ) {
        last_checked_id = parseInt ( last_id_arr[ 0 /*last_id_arr.length - 1*/ ].toString().split('-')[0] );
    }

    var filter_idha = new Array (); // id hodnot aktivních ( nevyšedlých ), pro poslední parametr_id

    //window.alert ( last_id );

    $('#product_filter_parameters ul li span.filter_parameters_body ul#fall' + last_id.toString() + ' li input').each (
        function () {
            var dis_ = $(this).attr('disabled');

            if ( !dis_ ) {
                var id_ = $(this).attr('name').substr(1);
                var cnt = $(this).next('label').children('span').text().replace('(', '').replace(')', '').replace(' ', '');
                filter_idha.push ( id_.toString() + '#' + cnt.toString() );
            }

        }
    );

    //window.alert(filter_idha);

    $.ajax( {
        type: 'POST',
        contentType: 'application/x-www-form-urlencoded',
        dataType: 'html',
        cache: false,
        timeout: 100000, /* ms */
        url: domain + '/web/pages/products/products_parameters_filter.php',
        /*async: false,*/
        data: {'idh': filter_idh, 'idp': filter_idp, 'get_id': get_id,
                'idpa': filter_idps, 'idpha': filter_idpa, 'posledni_zaskrtnute_id_parametru': last_checked_id, 'last_data': last_data, 'idha': filter_idha,
                'w': get_w, 'q': get_q,
                'sklc': skladovky
                },

        beforeSend: function () {

        },

        success: function ( data , textStatus, xmlHttpRequest ) {

            //window.alert (data);

            var dtar = data.split('PARAM');
            skladovky = dtar[0];

            //$('#product_filter_parameters').append ('<div style="display: block; word-break: break-all;">' + data + '</div>');

            var radky = dtar[1].split(';');

            var len = radky.length - 1;

            last_data = dtar[1];

            var pole = new Array ();

            

            for ( var i = 0; i < len; i++ ) {

                var arr = radky[i].split(','); // idp, idh, cnt

                //$('#product_filter_parameters').append( radky[i].toString() + ' ' );

                pole[arr[0].toString() + '-' + arr[1].toString()] = arr[2];
            }

            

            $('#product_filter_parameters ul li span.filter_parameters_body ul li input').each (
                function () {
                    var idh = $(this).attr('name').substr(1);

                    var idp = $(this).parents('ul').attr('id').substr(4);

                    if ( pole[idp.toString() + '-' + idh.toString()] == undefined || pole[idp.toString() + '-' + idh.toString()] == 0 ) {
                        $(this).attr('disabled', true);
                        $(this).next('label').children('span').text ( '' );
                        $(this).next('label').addClass('disabled');
                    } else {
                        $(this).removeAttr('disabled');
                        // projit vsechny kde je neco zaskrtnuto, a tam to take enablovat...
/*
                        if ( idp.toString() + '-' + idh.toString() == '1872-1937' ) {
                            window.alert ( pole[idp.toString() + '-' + idh.toString()].toString() );
                        }
*/
                        $(this).next('label').children('span').text ( '(' + pole[idp.toString() + '-' + idh.toString()].toString() + ')' );
                        $(this).next('label').removeClass('disabled');
                    }
                }
            );

            $.ajax ({
                type: 'POST',
                dataType: 'html',
                /*cache: false,*/
                url: domain + '/web/pages/products/products_dump_ajax.php',
                data: { 'get_id': get_id.toString(), 'get_page': get_page.toString(), 'get_lng': get_lng.toString(), 'sklc': skladovky },

            beforeSend: function(){

            },
            success: function ( data ) {
                $('#products_dump').html( data.toString() );
                attachEvents();

                // schovat "loader"
                hideLoaders ();
            }
            });
        }
    });
}
