// code to execute when document is loaded
$(function() {

    $('form input[type=text], form textarea, .form_item input').blur(function() {
        $(this).removeClass('field_over');
    });
    $('form input[type=text], form textarea, .form_item input').focus(function() {
        $(this).addClass('field_over');
    });
    $('ul.links').each(function() {
        $(this).find('li').not(':first').prepend(' | ');
    });

    // check/uncheck the subcategories
    $('.row_left_register .label_row').
    find('input[type=checkbox][name="categories[]"]:first').click(check_subcategories);
    //    $('.row_left_register .label_row .category_box input[type=checkbox][name="categories[]"]')
    //    .click(uncheck_parent);
    $('.row_left .label_row').
    find('input[type=checkbox][name="categories[]"]:first').click(check_subcategories);
    //    $('.row_left .label_row .category_box input[type=checkbox][name="categories[]"]')
    //    .click(uncheck_parent);
    $('.row .label_row').
    find('input[type=checkbox][name="categories[]"]:first').click(check_subcategories);
    //$('.row .label_row .category_box input[type=checkbox][name="categories[]"]')
    //.click(uncheck_parent);


    $('#filter_retailers').click(filter_retailers);
    reset_all();

    // associate the datepicker
    if ($('#frm_add_retailer input.expires').length > 0)
        $('#frm_add_retailer input.expires').datepicker({
            dateFormat: 'yy-mm-dd'
        });
    if ($('#filter input[name=filter_start]').length > 0)
        $('#filter input[name=filter_start]').datepicker({
            dateFormat: 'yy-mm-dd'
        });
    if ($('#filter input[name=filter_end]').length > 0)
        $('#filter input[name=filter_end]').datepicker({
            dateFormat: 'yy-mm-dd'
        });

    if ($('#newsletter_date').length > 0)
        $('#newsletter_date').datepicker({
            dateFormat: 'yy-mm-dd'
        });

    //forms_validation();
    //search_autocomplete();

    if ($("#tabs").length > 0) {
        $("#tabs").tabs({
            remote: true,
            load: function(event, ui) {
                $('#tabs input[type=checkbox]').click(function() {
                    elem = $('#retailers').find('button:first');
                    if ($(this).is(':checked')) {
                        $.get(domain + 'home/select_retailers/' + $(this).val());
                        elem.removeAttr("disabled");
                    }
                    else {
                        $.get(domain + 'home/deselect_retailers/' + $(this).val());
                        if ($('#tabs input[type=checkbox]:checked').length == 0)
                            elem.attr("disabled", true);
                    }
                });
                elem = $('#retailers').find('button:first');
                if ($('#tabs input[type=checkbox]:checked').length > 0)
                    elem.removeAttr("disabled");
            }
        });
        $("#tabs").show();
        $("#steps_container").cycle({
            fx:      'fade',
            speedIn:  1500,
            speedOut: 300,
            //            easeIn:  'bounceout',
            //            easeOut: 'backin',
            delay:   -1500,
            next:   '.next_step',
            prev:   '.prev_step',
            timeout: 0
        });

        $('.step_container input[name=email]').keyup(check_email_field);
        $('button#register').click(function() {
            $('#frm_register').submit();
        });
    }

    // neable/disable the categories button
    $('#categories_step input[type=checkbox]').click(function() {
        elem = $('#categories_step').find('button:first');
        if ($('#categories_step input[type=checkbox]:checked').length > 0)
            elem.removeAttr("disabled");
        else
            elem.attr("disabled", true);
    });

    $.activeAjaxRequestCount = 0;
    $.activeAjaxTooltipsCount = 0;
    $('div.expand_box').click(function() {
        //if ($(this).hasClass('expand_box')) $('#search_term').attr('value', '');
        $(this).each(expand_collapse_box);
        elem = $(this).parent().parent().find('.price_range_box');
        if (elem.length > 0 && elem.find('input[name=price_from]').val() == '' 
            && elem.find('input[name=price_to]').val() == '') return;
        browse_offers();
    });
    $('div.collapse_box').click(function() {
        $(this).each(expand_collapse_box);
        elem = $(this).parent().parent().find('.price_range_box');
        if (elem.length > 0 && elem.find('input[name=price_from]').val() == ''
            && elem.find('input[name=price_to]').val() == '') return;
        browse_offers();
    });

    // open the right tab
    base = $('#base_url').val();
    //    if (document.location.href.indexOf(base+'s_') == 0 || document.location.href.indexOf(base+'stores') == 0)
    //        $('.leftbox').eq(1).find('.expand_box').each(expand_collapse_box);
    //    else if (document.location.href.indexOf(base+'b_') == 0 || document.location.href.indexOf(base+'brands') == 0)
    //        $('.leftbox').eq(2).find('.expand_box').each(expand_collapse_box);
    //    else if (document.location.href.indexOf(base+'c_') == 0 || document.location.href.indexOf(base+'categs') == 0)
    //        $('.leftbox').eq(3).find('.expand_box').each(expand_collapse_box);
    //    else
    //        $('.leftbox').eq(1).find('.expand_box').each(expand_collapse_box);

    //    $('#browsing_items').tooltip({
    //        effect: 'slidedown'
    //    });

    // check
    if ($('#hidden_load_offers').length > 0) {
        if ($('input[type=hidden][name=opened_tabs]').length > 0) 
            checktabs($('input[type=hidden][name=opened_tabs]').val());
        browse_offers();
    }
    $('.box_footer .box_footer_all').click(function() {
        $(this).parent().parent().find('input[type=checkbox]').attr('checked', true);
        browse_offers();
    });
    $('.box_footer .box_footer_none').click(function() {
        $(this).parent().parent().find('input[type=checkbox]').attr('checked', false);
        browse_offers();
    });
    $('.price_range_box input').change(browse_offers);
    $('.leftbox input[type=checkbox]').change(browse_offers);
    $('#brands').change(function() {
        $('input[type=checkbox][name="brands[]"]').attr('checked', $(this).is(':checked'));
    });
    $('#stores').change(function() {
        $('input[type=checkbox][name="stores[]"]').attr('checked', $(this).is(':checked'));
    });
});

function check_subcategories() {
    subgroup = $(this).parent();
    if ($(this).parent().hasClass('ui-state-default'))
        subgroup = subgroup.parent().parent().parent();
    subgroup = subgroup.find('.category_box');
    if (subgroup.length > 0)
        subgroup.find('input[type=checkbox][name="categories[]"]').
        attr('checked', $(this).is(':checked'));
}

function uncheck_parent() {
    if ( ! $(this).is(':checked'))
        $(this).parent().parent().parent().find('input[type=checkbox][name="categories[]"]:first').
        attr('checked', false);
}

function searchterm() {
    closealltabs();
    browse_offers();
    return false;
}

function browse_offers(the_offset, ordering) {
    if (typeof(the_offset) == 'undefined' || typeof(the_offset) == 'object')
        the_offset = '';
    base = $('#base_url').val();
    $('#content_wrapper').html('<div class="loading_offers">'+
        '<div class="loading_offers_inside"><img src="'+base+'images/ajax-loader4.gif" /> '+
        'Loading offers. Please wait..</div></div>');

    // values to submit by post
    if ($('#search_term').length == 1) val_searc_term = $('#search_term').val();
    else val_searc_term = '';

    // apply the filters
    val_stores = '';
    if ($('.stores_box').is(':visible')) {
        $('.stores_box input[type=checkbox]:checked').each(function() {
            val_stores += ','+$(this).val();
        });
        if (val_stores != '') val_stores = val_stores.substr(1);
        else val_stores = '-1';
    }

    val_categories = '';
    if ($('.categories_box').is(':visible')) {
        $('.categories_box input[type=checkbox]:checked').each(function() {
            val_categories += ','+$(this).val();
        });
        if (val_categories != '') val_categories = val_categories.substr(1);
        else val_categories = '-1';
    }

    val_brands = '';
    if ($('.brands_box').is(':visible')) {
        $('.brands_box input[type=checkbox]:checked').each(function() {
            val_brands += ','+$(this).val();
        });
        if (val_brands != '') val_brands = val_brands.substr(1);
        else val_brands = '-1';
    }

    val_price_range = '';
    if ($('.price_range_box').is(':visible')) {
        val_price_range = $('.price_range_box input:first').val() + '_' +
        $('.price_range_box input:last').val();
    }

    if (typeof(the_offset) == 'undefined') the_offset = 0;
    $.activeAjaxRequestCount++;
    $.ajax({
        type: "POST",
        url: base + 'ajax_browse/' + the_offset,
        data: ({
            search_term: val_searc_term,
            stores: val_stores,
            categories: val_categories,
            brands: val_brands,
            price_range: val_price_range,
            ord: ordering
        }),
        dataType: "json",
        cache: false,
        success: function(data){
            $.activeAjaxRequestCount--;
            if ($.activeAjaxRequestCount > 0) return;
            if (data['error_message']) {
                $('#content_wrapper').html(data['error_message']);
                return;
            }
            if ($('.home_hack').length > 0) $('.home_hack').each(function() {
                $(this).removeClass('home_hack')
            });

            $('#content_wrapper').html(data['html']);
            $('#header_search_text').html(data['browse_message']);
            $('.pagination_wrapper').each(function() {
                $(this).html(data['paginate'])
            });
            $('.pagination_wrapper .paginate_links a').each(function() {
                arr_values = $(this).attr('href').split('/');
                val_offset = arr_values[arr_values.length - 1];
                $(this).attr('href', 'javascript: browse_offers('+val_offset+')');
            });

            //todo
            //closealltabs();
            //            checktabs('0');
            //            $('.price_range_box input:first').attr('value', data['price_from']);
            //            $('.price_range_box input:last').attr('value', data['price_to']);


            checktabs(data['opened_tabs']);
            $('#browsing_items .offer').tooltip({
                track: true,
                delay: 0,
                showURL: false,
                opacity: 1,
                fixPNG: true,
                showBody: " - ",
                //extraClass: "fancy",
                top: -2,
                left: 2,
                bodyHandler: function() {
                    base = $('#base_url').val();
                    theid = $(this).attr('id').substr(6);

                    if ($('#tooltip_'+theid).length > 0 && $('#tooltip_'+theid).html() != '')
                        return $('#tooltip_'+theid).html();
                    else if ($('#tooltip_'+theid).length == 0) {
                        $.activeAjaxTooltipsCount++;
                        $('#tooltip').after('<div style="display: none" id="tooltip_'+theid+'"></div>');
                        $.ajax({
                            type: "GET",
                            url: base+'browse/ajax_tooltip/'+theid,
                            dataType: "json",
                            success: function(data){
                                if (data['error']) mes = data['error_message'];
                                else mes = data['html'];
                                the_id = data['id'];
                                if ($('#tooltip_'+the_id).length > 0) $('#tooltip_'+the_id).html(mes);
                                $.activeAjaxTooltipsCount--;

                                if ($.activeAjaxTooltipsCount > 0) return;
                                $('#tooltip .body').html(mes);
                            },
                            cache: true,
                            error: function() {
                                $.activeAjaxTooltipsCount--;
                                $('#tooltip_'+theid).remove();
                            }
                        });
                    }
                    return '<img id="loader" src="'+base+'images/ajax-loader4.gif" />&nbsp;&nbsp;Loading info..';
                }
            })
        },
        error: function() {
            $.activeAjaxRequestCount--;
        }
    });
}

function checktabs(opened_tabs) {
    arr_opened_tabs = opened_tabs.split(',');
    if (opened_tabs != '')
        for (index in arr_opened_tabs) {
            if (isFinite(arr_opened_tabs[index]) && arr_opened_tabs[index] >= 0 && arr_opened_tabs[index] <= 3)
                $('.leftbox').eq(arr_opened_tabs[index]).find('.expand_box').each(expand_collapse_box);
        }
}

function closealltabs() {
    $('.leftbox').find('.collapse_box').each(expand_collapse_box);
}

function clear_filter() {
    $('#search_term').attr('value', '');
    $('#content_left .collapse_box').each(expand_collapse_box);
}

function expand_collapse_box() {
    if ($(this).hasClass('expand_box')) {
        $(this).parent().parent().find('.leftbox_expandable').show();
        $(this).removeClass('expand_box').addClass('collapse_box');
    }
    else {
        $(this).parent().parent().find('.leftbox_expandable').hide();
        $(this).removeClass('collapse_box').addClass('expand_box');
    }
}

function isValidEmailAddress(emailAddress) {
    var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
    return pattern.test(emailAddress);
}

function check_email_field() {
    elem = $('.next_step');
    email_val = $(this).val();

    if (email_val != '') {
        isValid = isValidEmailAddress(email_val);
        if (isValid) {
            elem.removeAttr("disabled");
        }
        else {
            elem.attr("disabled", true);
        }
    }
    else elem.attr("disabled", true);
}

function vote_up(offer_id) {
    base = $('#base_url').val();
    $.getJSON(base+'browse/ajax_vote/'+offer_id+'/up', {}, function(data) {
        if (data['error_message']) {
            $('.offer#offer_'+offer_id+' a.vote_up').remove();
        }
        else alert('There was a problem communicating with the server!');       
    });
}

function vote_down(offer_id) {
    base = $('#base_url').val();
    $.getJSON(base+'browse/ajax_vote/'+offer_id+'/down', {}, function(data) {
        if (data['error_message']) {
            $('.offer#offer_'+offer_id+' a.vote_down').remove();
        }
        else alert('There was a problem communicating with the server!');
    });
}