$(function() {
    // Globals:
    var currentSearch;
    var currentSearchDetails;
    var OVERLAY_ARROW_INDENT = 26;

    // Initialization:

    // Clear all checkboxes (so 'Select All' doesn't remain checked after refresh in FF, etc)
    $('#productGuide input[type=checkbox]').attr('checked', false);

    $('#productGuide #postal_code').get(0).focus();

    $(window).resize(function() {
        posFeedback();
    });
    var sharePopup = $('#productGuide #sharePopup');
    sharePopup
    .find('.close, .complete, .error').click(function() {
        $(this).parents('#sharePopup').hide();
    })
    .end()
    .find('.send').click(function() {
        if (sharePopup.find('input[name=to]').val() == '') {
            alert('Please enter a To address.');
        }
        else if (sharePopup.find('input[name=from]').val() == '') {
            alert('Please enter a From address.');
        }
        else {
            $.ajax({
                type: 'POST',
                url: root + '_share.php',
                data: {
                    product_ids: sharePopup.find('[name=product_ids]').val(),
                    postalcode: sharePopup.find('[name=postalcode]').val(),
                    to: sharePopup.find('[name=to]').val(),
                    from: sharePopup.find('[name=from]').val(),
                    message: sharePopup.find('[name=message]').val()
                },
                error: function(xhr, textStatus, error) {
                    sharePopup.find('.spinner').hide();
                    sharePopup.find('.error').show();
                },
                success: function(data, status) {
                    sharePopup.find('.spinner').hide();
                    sharePopup.find('.complete').show();
                }
            });
        }

        return false;
    });
    function launchSharePopup(event, product_ids, postalcode) {
        var overlay = $('#sharePopup');
        overlay
      .find('.complete').hide().end()
      .find('.error').hide().end()
      .show()
      .css('left', event.pageX - OVERLAY_ARROW_INDENT)
      .css('top', event.pageY - overlay.innerHeight())
        // Reset all fields except 'from':
      .find('input[name=to]').each(function() { this.focus(); }).end()
      .find('input[name=product_ids]').val(product_ids).end()
      .find('input[name=postalcode]').val(postalcode).end()
      .find('input[type=text], textarea').filter(':not(input[name=from])').val('');
    }

    // General bar toggle functionality:
    $('#productGuide .bar .symbol, #productGuide .bar .text').click(function() {
        var bar = $(this).parents('.bar');
        var symbol = bar.find('.symbol');
        var target_id = bar.get(0).id.replace(/_bar$/i, '');
        var target = $('#' + target_id);

        if ($('#' + target_id + ':visible').length > 0) {
            symbol.html('+');
            target.hide();
        }
        else {
            symbol.html('−');
            target.show();
        }
    });


    // Step1 functionality:

    $('#productGuide #step1 .init form').submit(function() {

        $('#feedback_float').hide();

        // Validate input
        var postal_code = $('#productGuide #postal_code').val();
        if (postal_code == '') {
            $('#productGuide #step1 .error').empty().hide();
            $('#productGuide #postal_code').get(0).focus();
            return false;
        }
        
        if (postal_code.length == 6)
        {
            postal_code = postal_code.substr(0,3) + ' ' +postal_code.substr(3,3);
            
            $('#productGuide #postal_code').val(postal_code);
        }
        else if (postal_code.length == 7)
        {
            postal_code = postal_code.substr(0,3) + ' ' +postal_code.substr(4,3);
            $('#productGuide #postal_code').val(postal_code);
        }
        
        if (!String(postal_code).match(/(\d{5}(-\d{4})?|[ABCEGHJKLMNPRSTVXY]\d[A-Z] \d[A-Z]\d)/i)) {
            $('#step1 .error').html('The postal code you entered is invalid.  Note that only U.S. and Canadian postal codes are supported.').show();
            $('#productGuide #postal_code').get(0).focus();
            return false;
        }

        $('#productGuide #step1 .init .spinner').show();
        $.ajax({
            type: 'GET',
            url: root + '_search.php',
            data: { postal_code: postal_code },
            dataType: 'json',
            error: function(xhr, textStatus, error) {
                $('#productGuide #step1 .init .spinner').hide();
                if (xhr.status == 400) {
                    $('#step1 .error').html('The postal code you entered is invalid or cannot be located.').show();
                }
            },
            success: function(data, status) {
                $('#productGuide #step1 .init .spinner').hide();
                if (!data || data == '' || data.length == 0 || (data.by_product.length == 0 && data.by_credit.length == 0)) {
                    $('#step1 .error').html('Sorry, but there are no Lafarge facilities near this postal code.').show();
                }
                else {
                    $('#productGuide #step1 input[type=text]').each(function() { this.blur(); });
                    $('#productGuide #step1 .init').hide();
                    $('#productGuide #step1 .error').empty().hide();
                    $('#productGuide #current_postal_code').html(postal_code);
                    $('#productGuide #prodpostalcode').val(postal_code);
                    $('#productGuide #catpostalcode').val(postal_code);
                    $('#productGuide #step1 .complete').show();

                    currentSearch = data;
                    loadProducts();
                    loadCredits();
                    $('#productGuide #step2').show();
                }
            }
        });
        return false;
    });

    $('#productGuide #step1 .complete .edit').click(function(event) {
        $('#feedback_float').hide();
        var overlay = $(this).parents('.complete').find('.overlay');
        overlay.show()
      .css('left', event.pageX - OVERLAY_ARROW_INDENT)
      .css('top', event.pageY - overlay.innerHeight())
      .find('input[type=text]').each(function() {
          this.value = $('#productGuide #postal_code').val();
          this.focus();
          this.select();
      });
        return false;
    });
    $('#productGuide #step1 .complete .overlay form').submit(function() {
        $('#productGuide #postal_code').val($(this).find('input[type=text]').val());
        $(this).parents('.overlay').hide();
        $('#feedback_float').hide();
        $('#productGuide #step1 .complete, #step1 .revise, #step2, #step3').hide();
        // Those checkboxes that aren't recreated (i.e. 'select all') remain checked when revising; correct (sloppily) here:
        $('#productGuide input[type=checkbox]').attr('checked', false);
        $('#productGuide #step1 .init').show();
        $('#productGuide #step1 .init form').trigger('submit');
        return false;
    });
    $('#productGuide #step1 .complete .overlay').keyup(function(event) {
        if (event.keyCode == 27) $(this).hide();
    });
    $('#productGuide #step1 .complete .overlay .close').click(function() {
        $(this).parents('.overlay').hide();
    });


    // Step 2 functionality:

    $('#productGuide #step2 .bar_content form').submit(function() {
        var container = $(this).parents('.bar_content');
        var mode = container.get(0).id;
        var product_ids = [];
        if (mode == "by_product") {
            container.find('input[type=checkbox]:checked').each(function() {
                if (this.id.match(/^product_id_/)) {
                    product_ids.push(this.id.replace(/^product_id_/, ''));
                }
            });
        }
        else if (mode == "by_credit") {
            var credit_type_ids = []
            container.find('input[type=checkbox]:checked').each(function() {
                if (this.id.match(/^credit_type_id_/)) {
                    credit_type_ids.push(this.id.replace(/^credit_type_id_/, ''));
                }
            });
            $.each(credit_type_ids, function() {
                $.each(currentSearch.by_credit[this].credits, function() {
                    $.each(this.product_ids, function(idx, value) {
                        // NOTE: Pushing 'this' trips up uniquing later - I guess it must include a binding that breaks equality/comparison.
                        product_ids.push(value);
                    });
                });
            });
        }

        if (product_ids.length > 0) {
            var hash = {};
            for (var i = 0; i < product_ids.length; i++)
                hash[product_ids[i]] = true;

            currentSearch.selectedProductIds = [];
            currentSearch.selectedProducts = {};
            currentSearch.selectedProducts.all = [];

            $.each(currentSearch.by_product, function() {
                $.each(this.products, function(idx, p) {
                    if (hash[p.id]) {
                        if (!currentSearch.selectedProducts[p.product_type]) currentSearch.selectedProducts[p.product_type] = [];
                        currentSearch.selectedProducts[p.product_type].push(p);
                        currentSearch.selectedProducts.all.push(p);
                        currentSearch.selectedProductIds.push(p.id);
                    }
                });
            });
            $.each(currentSearch.selectedProducts, function(product_type, products) {
                products = products.sort(function(a, b) {
                    return (b.name < a.name) - (a.name < b.name);
                });
            });

            var count = currentSearch.selectedProductIds.length;
            $('#productGuide #step3 .options .product_count').html(count + (count > 1 ? ' products' : ' product') + ' selected');

            $('#productGuide #step2 .spinner').show();
            $('#productGuide #step3 .results').load(root + '_step2.php .results > *', { product_ids: currentSearch.selectedProductIds.join(','), postalcode: $('#productGuide #postal_code').val() }, function(data) {
                window.scroll(0, 0);
                $('#productGuide #step2, #productGuide #step2 .spinner').hide();
                $('#feedback_float').hide();
                $('#productGuide #step3, #productGuide #step1 .revise').show();
                posFeedback();
                $('#feedback_float').show();

                // Hook up the share all / print all links:
                $('#productGuide #step3 .bar2')
          .find('.share_all').click(function(event) {
              launchSharePopup(event, currentSearch.selectedProductIds.join(','), $('#productGuide #postal_code').val());
              return false;
          })
          .end()
          .find('.print_all').click(function() {
              window.open(root + '_step2.php?postalcode=' + $('#productGuide #postal_code').val() + '&product_ids=' + currentSearch.selectedProductIds.join(','));
          });

                // hookups for custom leed letter
                $('.leed_form_element').hide();
                $("a.custom_leed").click(function(event) {
                    $('.leed_form_element').show();
                    $('.custom_leed').hide();
                    $('.standard_leed').hide();
                    $('.leed_form_hide').hide();

                    alert("Please complete the custom form fields and submit to generate your custom LEED letter.");
                    $('#leed_customer_name').focus();
                    event.preventDefault();
                });


                // Results-specific hookups:
                $('#productGuide #step3 .results')
          .find('.name').click(function() {
              var $this = $(this);
              if ($this.html().match(/^\+/)) {
                  $this.html($this.html().replace(/^\+/, '−'));
                  $this.parents('li').find('.credit_description').show();
              }
              else {
                  $this.html($this.html().replace(/^\−/, '+'));
                  $this.parents('li').find('.credit_description').hide();
              }
          })
          .end()
          .find('.back').click(function() {
              window.scroll(0, 0);
          })
          .end()
          .find('.print_details').click(function() {
              var id = $(this).parents('.result').get(0).id.replace(/^result_/, '');
              window.open(root + '_step2.php?postalcode=' + $('#productGuide #postal_code').val() + '&product_ids=' + id);
          })
          .end()
          .find('.share_details').click(function(event) {
              var id = $(this).parents('.result').get(0).id.replace(/^result_/, '');
              launchSharePopup(event, id);
              return false;
          });

            }, 'html');
        }
        else {
            // TODO: Any behavior if no products / credit types are selected?  Ignore for now.
        }
        return false;
    });

    $('#productGuide #step1 .revise a').click(function() {
        $('#productGuide #step3, #productGuide #step1 .revise').hide();
        $('#feedback_float').hide();
        $('#productGuide #step2').show();
        return false;
    })


    $('#productGuide #step2 .all input[type=checkbox]').click(function() {
        $(this).parents('.bar_content').find('.categories input[type=checkbox]').attr('checked', this.checked);
    });

    $('#productGuide #step2 #details_overlay').click(function() {
        $(this).hide();
    });
    // TODO: I suppose all overlays should _either_ be hidden or removed, so I can close all of them based on events:
    $('#productGuide .bar .symbol, #productGuide .bar .text').click(function() {
        $('#productGuide #step2 #details_overlay').hide();
    });

    var loadProducts = function() {
        var byProduct = $('#productGuide #step2 #by_product .categories');
        byProduct.empty();

        $.each(currentSearch.by_product, function(category_id, category_data) {
            var category_name = category_data.name;
            var categoryDiv = $('<div class="category" id="category_product_type_' + category_id + '"></div>').appendTo(byProduct);
            categoryDiv.append('<div class="all_category"><input type="checkbox" id="all_product_type_' + category_id + '">All ' + category_name + ' Products</div>');
            var col1 = $('<div class="column"></div>').appendTo(categoryDiv);
            var col2 = $('<div class="column"></div>').appendTo(categoryDiv);
            // TODO: Replace with clear: after and clearfix.
            categoryDiv.append('<div style="clear: both;"></div>');

            var split = Math.ceil(category_data.products.length / 2);
            $.each(category_data.products, function(idx) {
                $('<div class="item"><input type="checkbox" id="product_id_' + this.id + '"><span class="overlay_link">' + this.name + '</span></div>').appendTo(idx < split ? col1 : col2);
            });
        });

        // With all checkboxes loaded, hook up 'all in category' checkbox:
        byProduct.find('.all_category input[type=checkbox]').click(function() {
            $(this).parents('.category').find('input[type=checkbox]').attr('checked', this.checked);
            $(this).parents('.bar_content').find('.all input[type=checkbox]').attr('checked', false);
        });
        byProduct.find('.column input[type=checkbox]').click(function() {
            $(this).parents('.category').find('.all_category input[type=checkbox]').attr('checked', false);
            $(this).parents('.bar_content').find('.all input[type=checkbox]').attr('checked', false);
        });

        // Connect all overlay links:
        byProduct.find('.overlay_link').click(function(event) {
            var product_id = $(this).parents('.item').find('input[type=checkbox]').get(0).id.replace(/^product_id_/, '');

            // TODO: I figure different data structure would work a lot better.
            var record = null;
            $.each(currentSearch.by_product, function() {
                $.each(this.products, function() {
                    if (this.id == product_id) {
                        record = this;
                        return false;
                    }
                });
                if (record != null) return false;
            });

            if (!record.description || record.description == '') {
                record.description = '[No description available at this time.]';
            }

            var overlay = $('#productGuide #step2 #details_overlay');

            overlay.removeClass('small medium large');
            if (record.description.length <= 185)
                overlay.addClass('small');
            else if (record.description.length <= 295)
                overlay.addClass('medium');
            else
                overlay.addClass('large');

            overlay.find('h2').text(record.name);
            overlay.find('p').text(record.description)

            if (!record.url || record.url == '')
                overlay.find('a').hide();
            else
                overlay.find('a').show().attr('href', record.url)

            overlay.show()
        .css('left', event.pageX - OVERLAY_ARROW_INDENT)
        .css('top', event.pageY - overlay.innerHeight());

            return false;
        });
    };

    var loadCredits = function() {
        var byCredit = $('#productGuide #step2 #by_credit .categories');
        byCredit.empty();
        var categoryDiv = $('<div class="category"></div>').appendTo(byCredit);

        $.each(currentSearch.by_credit, function(id, data) {
            if (this.name != "None") {
                categoryDiv.append('<div class="item"><input type="checkbox" id="credit_type_id_' + id + '">' + this.name + '</div>');
            }
        });

        // Selecting any credit disables the 'Select All' checkbox.
        byCredit.find('input[type=checkbox]').click(function() {
            $(this).parents('.bar_content').find('.all input[type=checkbox]').attr('checked', false);
        });
    };

});

function posFeedback() {
    var main_pos = $("#main_table").position();
    var main_width = $("#main_table").width();
    var window_width = $(window).width();

    var offset_left = 40;
    var right = 0;
    if ((window_width - main_width) > 0)
        right = (window_width - main_width)/2 + offset_left;
    else
        right = (window_width - main_width) + offset_left;

    var offset_top = 140;
    var top = 0;
    if (main_pos.top > 0)
        top = main_pos.top + offset_top;
    else
        top = $(window).outerHeight() - $('#main_table').height() + offset_top;
        
    $("#feedback_float").css({ "right": right + "px", "top": top + "px" });
    //$("#feedback_float").html('main_width: ' + main_width + '<br>main_pos.left: ' + main_pos.left + '<br> right: ' + right + ' <br> window height: ' + $(window).height() + ' <br>  window width: ' + $(window).width() + "");
}
