jQuery(document).ready(function($){
  var initialSortList = $.tablesorter.defaults.sortList;
  if ($.cookie("sortParams")) {
    initialSortList = JSON.parse($.cookie("sortParams"));
  }
  
  $("#results_table").tablesorter({
    widgets: ['zebra'],
    widthFixed: true,
    headers: {
      9: {sorter: false}
    },
    /*debug: true,*/
    filters: {
      short_only: jQuery('[name="short_only"]'),
      ship_only_to: jQuery('[name="ship_only_to"]'),
      type_only: jQuery('[name="type_only"]'),
      size_only: jQuery('[name="size_only"]'),
      wall_only: jQuery('[name="wall_only"]')
    },
    sortList: initialSortList
  }).tablesorterPager({container: $(".pager")});
  
  $.cookie("sortParams", null);

  bind_items();
  
  jQuery(".contact_button").click(function() {
    jQuery.get("/contact.jsp", {}, function(data) {
      jQuery(data).modal({
        onOpen: function(dialog) {
          dialog.overlay.fadeIn('200', function() {
            dialog.container.slideDown('200', function() {
              dialog.data.fadeIn('200');
            });
          });
        },
        onShow: function(dialog) {
          jQuery("#req_fname").val(jQuery.cookie('req_fname'));
          jQuery("#req_lname").val(jQuery.cookie('req_lname'));
          jQuery("#req_company").val(jQuery.cookie('req_company'));
          jQuery("#req_address1").val(jQuery.cookie('req_address1'));
          jQuery("#req_address2").val(jQuery.cookie('req_address2'));
          jQuery("#req_city").val(jQuery.cookie('req_city'));
          jQuery("#req_state").val(jQuery.cookie('req_state'));
          jQuery("#req_zip").val(jQuery.cookie('req_zip'));
          jQuery("#req_phone").val(jQuery.cookie('req_phone'));
          jQuery("#req_mobile").val(jQuery.cookie('req_mobile'));
          jQuery("#req_email").val(jQuery.cookie('req_email'));
          jQuery("#req_comments").val(jQuery.cookie('req_comments'));
          
          jQuery("#request_contact_button").click(function() {
            if (jQuery("#req_fname").val() == null || jQuery("#req_fname").val() == '') {
              alert('You must fill in your first name.');
            } else if (jQuery("#req_lname").val() == null || jQuery("#req_lname").val() == '') {
              alert('You must fill in your last name.');
            } else if (jQuery("#req_company").val() == null || jQuery("#req_company").val() == '') {
              alert('You must fill in your company.');
            } else if (jQuery("#req_phone").val() == null || jQuery("#req_phone").val() == '') {
              alert('You must fill in your phone number.');
            } else if (jQuery("#req_email").val() == null || jQuery("#req_email").val() == '') {
              alert('You must fill in your email address.');
            } else {
              var params = {
                req_fname: jQuery("#req_fname").val(),
                req_lname: jQuery("#req_lname").val(),
                req_company: jQuery("#req_company").val(),
                req_address1: jQuery("#req_address1").val(),
                req_address2: jQuery("#req_address2").val(),
                req_city: jQuery("#req_city").val(),
                req_state: jQuery("#req_state").val(),
                req_zip: jQuery("#req_zip").val(),
                req_phone: jQuery("#req_phone").val(),
                req_mobile: jQuery("#req_mobile").val(),
                req_email: jQuery("#req_email").val(),
                req_comments: jQuery("#req_comments").val()
              };
              
              jQuery.cookie('req_fname', params.req_fname);
              jQuery.cookie('req_lname', params.req_lname);
              jQuery.cookie('req_company', params.req_company);
              jQuery.cookie('req_address1', params.req_address1);
              jQuery.cookie('req_address2', params.req_address2);
              jQuery.cookie('req_city', params.req_city);
              jQuery.cookie('req_state', params.req_state);
              jQuery.cookie('req_zip', params.req_zip);
              jQuery.cookie('req_phone', params.req_phone);
              jQuery.cookie('req_mobile', params.req_mobile);
              jQuery.cookie('req_email', params.req_email);
              jQuery.cookie('req_comments', params.req_comments);
              
              jQuery.post("/request_contact.jsp", params, function() {
                jQuery.modal.close();
              });
            }
            return false;
          });
        },
        onClose: function(dialog) {
          dialog.data.fadeOut('200', function () {
            dialog.container.slideUp('200', function () {
              dialog.overlay.fadeOut('200', function () {
                $.modal.close();
              });
            });
          });
        }
      });
    });
    return false;
  });

  /*
  jQuery(".help_button").click(function() {
    jQuery.get("/help.jsp", {}, function(data) {
      jQuery(data).modal({
        onOpen: function(dialog) {
          dialog.overlay.fadeIn('200', function() {
            dialog.container.slideDown('200', function() {
              dialog.data.fadeIn('200');
            });
          });
        },
        onClose: function(dialog) {
          dialog.data.fadeOut('200', function () {
            dialog.container.slideUp('200', function () {
              dialog.overlay.fadeOut('200', function () {
                $.modal.close();
              });
            });
          });
        }
      });
    });
    return false;
  });
  */
  
  jQuery(".help_button").click(function() {
    jQuery.get("/instructions.jsp", {}, function(data) {
      jQuery(data).modal({
        onOpen: function(dialog) {
          dialog.overlay.fadeIn('200', function() {
            dialog.container.css('height', 200);
            dialog.container.slideDown('200', function() {
              dialog.data.fadeIn('200');
            });
          });
        },
        onClose: function(dialog) {
          dialog.data.fadeOut('200', function () {
            dialog.container.slideUp('200', function () {
              dialog.overlay.fadeOut('200', function () {
                $.modal.close();
              });
            });
          });
        }
      });
    });
    return false;
  });
  
  jQuery(".photo_button").click(function() {
    jQuery.get("/photos.jsp", {}, function(data) {
      jQuery(data).modal({
        onOpen: function(dialog) {
          var viewHeight = jQuery("#modalOverlay").height();
          if (typeof document.documentElement != 'undefined' && typeof document.documentElement.clientHeight != 'undefined' && document.documentElement.clientHeight != 0) {
            viewHeight = document.documentElement.clientHeight;
          }
          jQuery("#modalContainer").width(0.6 * jQuery("#modalOverlay").width()).height(0.8 * viewHeight).css('margin-left', 0 - (0.5 * jQuery("#modalContainer").width()));
          jQuery("#photo_container").width(jQuery("#modalContainer").width() - 30).height(jQuery("#modalContainer").height() - 50);
          dialog.overlay.fadeIn('200', function() {
            dialog.container.slideDown('200', function() {
              dialog.data.fadeIn('200');
            });
          });
        },
        onClose: function(dialog) {
          dialog.data.fadeOut('200', function () {
            dialog.container.slideUp('200', function () {
              dialog.overlay.fadeOut('200', function () {
                $.modal.close();
              });
            });
          });
        }
      });
    });
    return false;
  });

  jQuery(".about_button").click(function() {
    jQuery.get("/about.jsp", {}, function(data) {
      jQuery(data).modal({
        onOpen: function(dialog) {
          var viewHeight = jQuery("#modalOverlay").height();
          if (typeof document.documentElement != 'undefined' && typeof document.documentElement.clientHeight != 'undefined' && document.documentElement.clientHeight != 0) {
            viewHeight = document.documentElement.clientHeight;
          }
          jQuery("#modalContainer").width(0.8 * jQuery("#modalOverlay").width()).height(0.8 * viewHeight).css('margin-left', 0 - (0.5 * jQuery("#modalContainer").width()));
          jQuery("#about_container").width(jQuery("#modalContainer").width() - 30).height(jQuery("#modalContainer").height() - 50);
          dialog.overlay.fadeIn('200', function() {
            dialog.container.slideDown('200', function() {
              dialog.data.fadeIn('200');
            });
          });
        },
        onClose: function(dialog) {
          dialog.data.fadeOut('200', function () {
            dialog.container.slideUp('200', function () {
              dialog.overlay.fadeOut('200', function () {
                $.modal.close();
              });
            });
          });
        }
      });
    });
    return false;
  });
  
  jQuery("#pagesize1").click(function() {
    jQuery("#pagesize2").val(jQuery(this).val());
  });
  
  jQuery("#pagesize2").click(function() {
    jQuery("#pagesize1").val(jQuery(this).val());
  });
  
  jQuery(".lightbox").lightbox();
});

function spinner_and_links() {
  $("#spinner").html('<div style="position: absolute; height: 100%; width: 100%; background-color: #000000; z-index: 3000; filter: alpha(opacity=50); -moz-opacity:0.5; -khtml-opacity: 0.5; opacity: 0.5; color: #FFFFFF; font-size: 48px; text-align: center; padding-top: 300px; padding-bottom: 300px; top: 0px; left: 0px;">Searching...</div>');
}

function table_and_spinner() {
  bind_items();
  $(".export_pdf").attr("href", "save_results.jsp?" + $("#search_form").formSerialize());
}

function bind_items() {
  var options = {
    target: '#results',
    beforeSubmit: spinner_and_links, 
    success: table_and_spinner
  };

  jQuery("#search_form :input[name!='pagesize']").change(function () {
    jQuery('#search_form').ajaxSubmit(options);

    jQuery("#results_table").trigger("appendCache");
  });
  
  jQuery("#metric_check").click(function () {
    // Save the sort parameters that are selected into a cookie.
    var sortParams = [];
    jQuery("#results_table thead tr th").each(function (i) {
      if ($(this).is(".headerSortDown")) {
        sortParams.push([i, 0]);
      } else if ($(this).is(".headerSortUp")) {
        sortParams.push([i, 1]);
      }
    });
    $.cookie("sortParams", JSON.stringify(sortParams));
    
    if (jQuery("#metric_check").attr("checked")) {
      // Reload the page using the metric URL.
      window.location.href = window.location.href + "?metric=true";
    } else {
      // Reload the page using the US URL.
      window.location.href = window.location.href.replace(/\?metric=true/, "");
    }
  });

  jQuery("#reset_view").click(function() {
    jQuery('[name="short_only"]').val("all");
    jQuery('[name="ship_only_to"]').val("all");
    jQuery('[name="type_only"]').val("all");
    jQuery('[name="size_only"]').val("all");
    jQuery('[name="wall_only"]').val("all");
    jQuery('#search_form').ajaxSubmit(options);
    //$("#results_table").trigger("sorton", []);
    jQuery('.pagesize').val(20);
    jQuery('#pagesize1').trigger("change");
    jQuery("#results_table").trigger("appendCache");
    var sorting = new Array();
    //console.log(sorting);
    jQuery("#results_table").trigger("sorton", [sorting]);
    return false;
  });

  jQuery("#spinner").hide();
}

function email_results() {
  jQuery('<div id="email_popup" style="margin: 15px;"><a class="modalCloseX modalClose" href="#" title="Close">x</a><div>Please provide your email address and the email address of the person you wish to share this listing with in the fields below:</div><div class="clearfix" style="width: 380px; margin: 5px 0px;"><div style="float: left;">* Your Email Address:</div><div style="float: right;"><input type="text" id="email_from"/></div></div><div class="clearfix" style="width: 380px; margin: 5px 0px;"><div style="float: left;">* Colleague\'s Email Address:</div><div style="float: right;"><input type="text" id="email_to"/></div></div><div>If you wish to add a message to the email, please enter it below::</div><div><textarea id="email_text" style="width: 550px; height: 200px;"></textarea></div><div><input type="image" src="/images/submit_button.png" style="margin-top: 5px;" id="send_email_button" value="Send"/></div></div>').modal({
    onOpen: function(dialog) {
      dialog.overlay.fadeIn('200', function() {
        dialog.container.slideDown('200', function() {
          dialog.data.fadeIn('200');
        });
      });
    },
    onShow: function(dialog) {
      jQuery("#email_to").val(jQuery.cookie('email_to'));
      jQuery("#email_from").val(jQuery.cookie('email_from'));
      jQuery("#email_text").val(jQuery.cookie('email_text'));
      
      jQuery("#send_email_button").click(function() {
        if (jQuery("#email_to").val() == null || jQuery("#email_to").val() == '') {
          alert('You must fill in the To: field.');
        } else if (jQuery("#email_from").val() == null || jQuery("#email_from").val() == '') {
          alert('You must fill in the From: field.');
        } else if (jQuery("#email_text").val() == null || jQuery("#email_text").val() == '') {
          alert('You must fill in the Message: field.');
        } else {
          var params = {
            email_to: jQuery("#email_to").val(),
            email_from: jQuery("#email_from").val(),
            email_text: jQuery("#email_text").val(),
            short_only: jQuery("[name='short_only']").val(),
            ship_only_to: jQuery("[name='ship_only_to']").val(),
            type_only: jQuery("[name='type_only']").val(),
            size_only: jQuery("[name='size_only']").val(),
            wall_only: jQuery("[name='wall_only']").val(),
            metric: jQuery("[name='metric']").val()
          };
          
          jQuery.cookie('email_to', params.email_to);
          jQuery.cookie('email_from', params.email_from);
          jQuery.cookie('email_text', params.email_text);
          
          jQuery.post("email_results.jsp", params, function() {
            jQuery.modal.close();
          });
        }
      });
    },
    onClose: function(dialog) {
      dialog.data.fadeOut('200', function () {
        dialog.container.slideUp('200', function () {
          dialog.overlay.fadeOut('200', function () {
            jQuery.modal.close();
          });
        });
      });
    }
  });
}

function request_quote() {
  jQuery('<div id="quote_popup" style="margin: 15px;"><a class="modalCloseX modalClose" href="#" title="Close">x</a><div>Please complete all of the following fields, and a representative will contact you about the current selection of items.</div><div class="clearfix" style="width: 350px; margin: 5px 0px;"><div style="float: left;">* Name:</div><div style="float: right;"><input type="text" id="quote_name"/></div></div><div class="clearfix" style="width: 350px; margin: 5px 0px;"><div style="float: left;">* Phone Number:</div><div style="float: right;"><input type="text" id="quote_phone"/></div></div><div class="clearfix" style="width: 350px; margin: 5px 0px;"><div style="float: left;">* Email:</div><div style="float: right;"><input type="text" id="quote_email"/></div></div><div class="clearfix" style="width: 350px; margin: 5px 0px;"><div style="float: left;">* Company:</div><div style="float: right;"><input type="text" id="quote_company"/></div></div><div>If you wish to add a message to the email, please enter it below:</div><div><textarea id="quote_notes" style="width: 550px; height: 150px;"></textarea></div><div><input type="image" src="/images/submit_button.png" id="get_quote_button" value="Send" style="margin-top: 5px;"/></div></div>').modal({
    onOpen: function(dialog) {
      dialog.overlay.fadeIn('200', function() {
        dialog.container.slideDown('200', function() {
          dialog.data.fadeIn('200');
        });
      });
    },
    onShow: function(dialog) {
      jQuery("#quote_name").val(jQuery.cookie('quote_name'));
      jQuery("#quote_phone").val(jQuery.cookie('quote_phone'));
      jQuery("#quote_email").val(jQuery.cookie('quote_email'));
      jQuery("#quote_company").val(jQuery.cookie('quote_company'));
      jQuery("#quote_notes").val(jQuery.cookie('quote_notes'));
      
      jQuery("#get_quote_button").click(function() {
        if (jQuery("#quote_name").val() == null || jQuery("#quote_name").val() == '') {
          alert('You must fill in your name.');
        } else if (jQuery("#quote_phone").val() == null || jQuery("#quote_phone").val() == '') {
          alert('You must fill in your phone number.');
        } else if (jQuery("#quote_email").val() == null || jQuery("#quote_email").val() == '') {
          alert('You must fill in your email address.');
        } else if (jQuery("#quote_company").val() == null || jQuery("#quote_company").val() == '') {
          alert('You must fill in your company.');
        } else {
          var params = {
            quote_name: jQuery("#quote_name").val(),
            quote_phone: jQuery("#quote_phone").val(),
            quote_email: jQuery("#quote_email").val(),
            quote_company: jQuery("#quote_company").val(),
            quote_notes: ((jQuery("#quote_notes").val() == null || jQuery("#quote_notes").val() == '') ? "" : jQuery("#quote_notes").val()),
            short_only: jQuery("[name='short_only']").val(),
            ship_only_to: jQuery("[name='ship_only_to']").val(),
            type_only: jQuery("[name='type_only']").val(),
            size_only: jQuery("[name='size_only']").val(),
            wall_only: jQuery("[name='wall_only']").val(),
            metric: jQuery("[name='metric']").val()
          };
          
          jQuery.cookie('quote_name', params.quote_name);
          jQuery.cookie('quote_phone', params.quote_phone);
          jQuery.cookie('quote_email', params.quote_email);
          jQuery.cookie('quote_company', params.quote_company);
          jQuery.cookie('quote_notes', params.quote_notes);
          
          jQuery.post("request_quote.jsp", params, function() {
            jQuery.modal.close();
          });
        }
      });
    },
    onClose: function(dialog) {
      dialog.data.fadeOut('200', function () {
        dialog.container.slideUp('200', function () {
          dialog.overlay.fadeOut('200', function () {
            jQuery.modal.close();
          });
        });
      });
    }
  });
}
