$(document).ready(function () {

    // makes radio and checkbox inputs pretty
    /*	if ($("form#user-login").is('*'))
    {
    $("form#user-login").wrapInner("<fieldset></fieldset>");
    }
    */
    if (!($("div#storelocator").is('*'))) { //if the page does not have a storelocator selector on a div, run this code for input styling

        $('input[type=checkbox],input[type=radio]').prettyCheckboxes();
        $('p.note').addClass("prettyNote");
        $('div.form-checkboxes, div.form-checkboxes-error, div.form-checkboxes-required, div.form-radio, div.form-radio-error, div.form-radio-required').addClass("prettyWrap");
    }
    // makes textarea elements expandable
    $('textarea').prettyComments();

    // adds facebox event handling to all a tags with a rel of modal
    $('a[rel*=modal]').facebox();

    // convert tabbed div content to tabs
    $('.ui-tabbed').each(function (j, val) {
        var k = 0;
        var numSections = $(this).children(".section").length;
        var lastText = "";

        $(this).children(".section").each(function (p, val) {
            if (!$(this).hasClass("initial")) {
                var titles = $(this).children(".tab_title");
                var thisTitle = $(titles[0]).text();
                $(titles[0]).css("display", "none");

                $(this).addClass("tab" + (k + 1));

                var tabLink = "#";
                if ($(this).parent().parent().parent().hasClass("no-toggle")) {
                    tabLink = $(this).find(".tab_title a").attr("href");
                }

                if (k == 0) {
                    $(this).parent().prepend('<ul class="tab_navi"></ul>');
                }

                if (k == numSections - 1) {
                    lastText = "last";
                }
                else {
                    lastText = "";
                }

                if ($(this).hasClass("default")) {
                    $(this).siblings(".tab_navi").append('<li class="' + lastText + '"><a href="' + tabLink + '" rel="tab' + (k + 1) + '">' + thisTitle + '</a><span></span></li>');
                }
                else {
                    $(this).css("display", "none");
                    if (lastText != "") {
                        lastText = " last";
                    }
                    $(this).siblings(".tab_navi").append('<li class="disabled' + lastText + '"><a href="' + tabLink + '" rel="tab' + (k + 1) + '">' + thisTitle + '</a><span></span></li>');
                }
                k++;
            }
        });

        if (!$(this).parent().parent().hasClass("no-sections") && !$(this).parent().parent().hasClass("no-toggle")) {
            $(this).find(".tab_navi a").click(function (e) {
                $(this).parent().siblings("li").addClass("disabled");
                $(this).parent().removeClass("disabled");

                $(this).parent().parent().siblings(".section").each(function (m, val) {
                    $(this).css("display", "none");
                });

                $(this).parent().parent().siblings("." + $(this).attr("rel")).css("display", "block");
                return false;
            });
        }
    });

    // convert accordion div content to an accordion
    $('.ui-accordion').each(function (j, val) {

        $(this).children(".section").each(function (p, val) {
            var titles = $(this).children(".tab_title");
            var thisTitle = $(titles[0]).text();
            $(titles[0]).css("display", "none");

            var spanClass = "minus";

            if (!$(this).parent().hasClass("all-open")) {
                $(this).hide();
                spanClass = "plus";
            }

            if (p == 0) {
                $(this).before('<a href="#" class="tab first"><span class="' + spanClass + '"></span>' + thisTitle + '</a>');
            }
            else {
                $(this).before('<a href="#" class="tab"><span class="' + spanClass + '"></span>' + thisTitle + '</a>');
            }

            $(this).wrapInner('<div class="section_inner"></div>');

            $(this).css("width", $(this).parent().width());
            $(this).css("padding", "0");

        });

        $(this).children("a.tab").click(function () {

            if (!$(this).parent().hasClass("open-multi")) {
                $(this).siblings(".section").slideUp(300, function () {
                    $(this).prev().children("span").removeClass("minus").addClass("plus");
                });
            }

            $(this).next().filter(":visible").slideUp(300, function () {
                $(this).prev().children("span").removeClass("minus").addClass("plus");
            });

            $(this).next().filter(":hidden").slideDown(300, function () {
                $(this).prev().children("span").removeClass("plus").addClass("minus");
            });

            return false;
        });

    });

    // Control Subnav of dropdown list from tertiary menu
    $('.tert-menu-flyout').each(function (i) {


        $(this).hover(
            function () {
                $(this).children("ul").css("display", "block");
            },

            function () {
                $(this).children("ul").css("display", "none");
            }
        );

    })

    // convert main tier2 nav, depending on the content
    $('#menu > li').each(function (j, val) {

        $(this).children("ul").css("display", "block");
        $(this).children("ul").css("visibility", "hidden");

        var liTotalWidth = 0;
        $(this).find("li").each(function (k, val) {
            liTotalWidth += $(this).width();
        });

        $(this).children("ul").css("display", "");
        $(this).children("ul").css("visibility", "");

        var mainNavWidthInitial = $(this).parent().width();
        $(this).parent().css("width", "auto");
        var mainNavWidthAuto = $(this).parent().width();

        var mainNavDiff = mainNavWidthInitial - mainNavWidthAuto;
        var ulWidthInitial = $(this).children("ul").width();

        $(this).children("ul").css("width", liTotalWidth + "px");
        $(this).children("ul").css("padding-right", "0");

        var thisWidth = $(this).width();
        var thisPosition = $(this).position().left + thisWidth + mainNavDiff;
        var centerPoint = thisPosition - thisWidth / 2;

        $(this).parent().css("width", mainNavWidthInitial + "px");

        var thisUlWidth = $(this).children("ul").width();
        var UlPosition = (ulWidthInitial) - Math.round(centerPoint + thisUlWidth / 2) + (mainNavWidthInitial - ulWidthInitial + 7);

        if (UlPosition < 4) {
            UlPosition = 4;
            $(this).children("ul").css("width", ulWidthInitial - UlPosition + "px");

            $(this).children("ul").prepend('<li class="left-spacer"></li>');
            $(this).find(".left-spacer").css("width", ulWidthInitial - thisUlWidth - UlPosition + "px");
            $(this).find(".left-spacer").css("float", "left");

            $(this).children("ul").css("width", (liTotalWidth + (ulWidthInitial - thisUlWidth - UlPosition)) + "px");
        }
        else if (UlPosition + thisUlWidth > ulWidthInitial) {
            UlPosition = ulWidthInitial - thisUlWidth;
        }
        else {
            $(this).children("ul").prepend('<li class="left-spacer"></li>');
            $(this).find(".left-spacer").css("width", ulWidthInitial - thisUlWidth - UlPosition + "px");
            $(this).find(".left-spacer").css("float", "left");

            $(this).children("ul").css("width", (liTotalWidth + (ulWidthInitial - thisUlWidth - UlPosition)) + "px");
        }

        $(this).children("ul").css("padding-right", UlPosition + "px");
    });



    /*prepend numbers to subnav
    if (document.getElementById("sub_nav")) {
    var subNavLinks = document.getElementById("sub_nav").getElementsByTagName("a");
    for (i=1; i<subNavLinks.length+1; i++) {
    if (subNavLinks[i-1].parentNode.className != "btn") {
    var thisText = subNavLinks[i-1].firstChild.nodeValue;
    var thisNumber;
    if (i < 10) {
    thisNumber = "0" + i;
    } else {
    thisNumber = i;
    }
    subNavLinks[i-1].innerHTML = "<span>" + thisNumber + "</span>" + thisText;
    }
    }
    }*/

    // handle testimonial quote images
    var blockquotes = document.getElementsByTagName("blockquote");
    for (j = 0; j < blockquotes.length; j++) {
        var thisBlockInfo = blockquotes[j].innerHTML;
        var firstQuote = "<span class=\"quote_lt\">\"</span>";
        //var midQuote = "<span class=\"quote_lastword\">";
        //var lastQuote = "<img class=\"quote_rt\" src=\"assets/images/ui_framework/bg_quoteright.gif\" width=\"15\" height=\"11\" /></span>";		
        var midQuote = "";
        var lastQuote = "";
        //var thisBlockBuilder = "<span class=\"quote_lt\">\"</span>" + thisBlockInfo[0].nodeValue.substring(1, thisBlockInfo[0].nodeValue.length);
        var quoteSplit = thisBlockInfo.split(" ");
        //alert(quoteSplit[0].substring(1, quoteSplit[0].length));
        quoteSplit[0] = firstQuote + quoteSplit[0].substring(1, quoteSplit[0].length);
        quoteSplit[quoteSplit.length - 1] = midQuote + quoteSplit[quoteSplit.length - 1].substring(0, quoteSplit[quoteSplit.length - 1].length - 1) + lastQuote;

        var thisQuoteJoined = quoteSplit.join(" ");
        blockquotes[j].innerHTML = thisQuoteJoined;
    }

    // handle first items in a select drop-down list
    $("select option:first-child").addClass("first");

    // handle form selection class change when an item is selected
    $("select").change(function () {
        if (this.selectedIndex == 0) {
            $(this).removeClass();
        }
        else {
            $(this).addClass("active");
        }
    });

    // handle select style on page load
    function initSelectCurrent() {
        var selectArray = $("select");
        for (var i = 0; i < selectArray.length; i++) {
            if (selectArray[i].selectedIndex != 0) {
                selectArray[i].className = "active";
            }
        }
    }

    // handle radio button click event
    $(":radio").click(function () {
        $(this).siblings("label").removeClass("current");
        $(this).siblings("label:last").addClass("last");

        var thisId = this.getAttribute('id');
        $(this).siblings("label[for='" + thisId + "']").addClass("current");
    });

    // handle radio button style on page load
    /*function initRadioCurrent () {
    var thisRadioChecked = $(":radio:checked");
    for (var i = 0; i < thisRadioChecked.length; i++)
    {
    var thisId = thisRadioChecked[i].getAttribute('id');
    $("label[for='"+thisId+"']").addClass("current");
    }
    }*/

    /*// handle radio button click event
    $(":checkbox").click(function() {
    var thisId = this.getAttribute('id');
    var thisClass = $(this).siblings("label[for='"+thisId+"']").attr("class");
		
    if (thisClass.indexOf("current") != -1)
    {
    $(this).siblings("label[for='"+thisId+"']").removeClass("current");
    }
    else
    {
    $(this).siblings("label[for='"+thisId+"']").addClass("current");
    }
    });*/

    // handle radio button style on page load
    /*function initCheckboxesCurrent () {
    var thisCheckboxesChecked = $(":checkbox:checked");
    for (var i = 0; i < thisCheckboxesChecked.length; i++)
    {
    var thisId = thisCheckboxesChecked[i].getAttribute('id');
    $("label[for='"+thisId+"']").addClass("current");
    }
    }*/

    // make sure current radio buttons, select ddls, and checkboxes get the current class
    initSelectCurrent();
    //initRadioCurrent();
    //initCheckboxesCurrent();

    // apply functionality to all "form1" forms
    function initForm1() {
        if (!document.getElementById) return;

        var labels, id, field;

        // Set focus and blur handlers to hide and show 
        // LABELs with 'overlabel' class names.
        textInputs = $("fieldset.form1 :text, fieldset.form1 :password, fieldset.form1 textarea");
        for (var i = 0; i < textInputs.length; i++) {
            textInputs[i].onfocus = function () {
                this.className = 'focused';
            }

            textInputs[i].onblur = function () {
                this.className = 'default';
            }
        }
    };

    initForm1();
    // end "form1" form functionality

    // apply functionality to all "form2" forms
    function initOverLabels() {
        if (!document.getElementById) return;

        var labels, id, field;

        // Set focus and blur handlers to hide and show 
        // LABELs with 'overlabel' class names.
        labels = $("fieldset.form2 label.overlabel");
        for (var i = 0; i < labels.length; i++) {
            // Skip labels that do not have a named association
            // with another field.
            id = labels[i].htmlFor || labels[i].getAttribute('for');
            if (!id || !(field = document.getElementById(id))) {
                continue;
            }

            if (labels[i].className.indexOf("error") == -1) {
                // Change the applied class to hover the label 
                // over the form field.
                labels[i].className = 'overlabel-apply';
            }
            else {
                // Change the applied class to hover the label 
                // over the form field, with error
                labels[i].className = 'overlabel-apply error';
            }

            // Hide any fields having an initial value.
            if (field.value !== '') {
                if (labels[i].className.indexOf("error") == -1) {
                    hideLabel(field.getAttribute('id'), true);
                }
                labels[i].style.textIndent = '-1000px';
            }

            // Set handlers to show and hide labels.
            field.onfocus = function () {
                hideLabel(this.getAttribute('id'), true);
                this.className = 'focused';
            };

            field.onblur = function () {
                if (this.value === '') {
                    hideLabel(this.getAttribute('id'), false);
                }
                this.className = 'default';
            };

            // Handle clicks to LABEL elements (for Safari).
            labels[i].onclick = function () {
                var id, field;
                id = this.getAttribute('for');
                if (id && (field = document.getElementById(id))) {
                    field.focus();
                }
            };
        }
    };

    function hideLabel(field_id, hide) {
        var field_for;
        var labels = $("fieldset.form2 label");
        for (var i = 0; i < labels.length; i++) {
            field_for = labels[i].htmlFor || labels[i].getAttribute('for');
            if (field_for == field_id) {
                labels[i].style.textIndent = (hide) ? '-1000px' : '0px';
                labels[i].className = 'overlabel-apply';
                return true;
            }
        }
    }

    initOverLabels();
    // end "form2" form functionality

    $("button").hover(
		function () {
		    if ($(this).hasClass("btn_small")) {
		        $(this).addClass("btn_bluehover_small");
		    }
		    else {
		        $(this).addClass("btn_bluehover");
		    }
		},
		function () {
		    if ($(this).hasClass("btn_small")) {
		        $(this).removeClass("btn_bluehover_small");
		    }
		    else {
		        $(this).removeClass("btn_bluehover");
		    }
		}
	);

    /*	if ($("form#user-login").is('*'))
    {
    $("form#user-login").wrapInner("<fieldset></fieldset>");
    }

    if ($("input#edit-submit").is('*'))
    {
    var valueText = $("input#edit-submit").attr("value");
    $("#edit-submit").after('<button type="submit"><span>' + valueText + '</span></button>');
    $("#edit-submit").css("display", "none");
    } */


    // Use the each() method to gain access to each elements attributes
    $('.plans-fcc .feature a[rel], .plans_opt_group a[rel], .legal_links a[rel], .microcart_freeshipping a[rel], .tooltip a[rel]').each(function () {
        $(this).qtip(
      {
          content: {
              // Set the text to an image HTML string with the correct src URL to the loading image you want to use
              title: {
                  background: '',
                  text: '<h6></h6>',
                  button: 'X'
              },
              text: '<p class="disclaimer">Loading...</p>',
              url: $(this).attr('rel') // Use the rel attribute of each element for the url to load
          },
          position: {
              corner: {
                  target: 'bottomLeft', // Position the tooltip above the link
                  tooltip: 'topLeft'
              },
              adjust: {
                  screen: true // Keep the tooltip on-screen at all times
              }
          },
          show: {
              when: 'click',
              solo: true // Only show one tooltip at a time
          },
          hide: 'unfocus',
          style: {
              tip: { // Now an object instead of a string
                  corner: 'topLeft', // We declare our corner within the object using the corner sub-option
                  color: '#4d4d4d',
                  size: {
                      x: 13, // Be careful that the x and y values refer to coordinates on screen, not height or width.
                      y: 10 // Depending on which corner your tooltip is at, x and y could mean either height or width!
                  }
              },
              border: {
                  width: 6,
                  radius: 0,
                  color: '#4d4d4d'
              },
              name: 'light', // Use the default light style
              width: 326 // Set the tooltip width
          }
      })
    });

    // Use the each() method to gain access to each elements attributes
    $('.pt-tooltip a[rel]').each(function () {
        $(this).qtip(
      {
          content: {
              // Set the text to an image HTML string with the correct src URL to the loading image you want to use
              title: {
                  background: '',
                  text: '<h6></h6>',
                  button: 'X'
              },
              text: '<p class="disclaimer">Loading...</p>',
              url: $(this).attr('rel') // Use the rel attribute of each element for the url to load
          },
          position: {
              corner: {
                  target: 'bottomMiddle', // Position the tooltip above the link
                  tooltip: 'topLeft'
              },
              adjust: {
                  screen: true // Keep the tooltip on-screen at all times
              }
          },
          show: {
              when: 'click',
              solo: true // Only show one tooltip at a time
          },
          hide: 'unfocus',
          style: {
              tip: { // Now an object instead of a string
                  corner: 'topLeft', // We declare our corner within the object using the corner sub-option
                  color: '#4d4d4d',
                  size: {
                      x: 13, // Be careful that the x and y values refer to coordinates on screen, not height or width.
                      y: 10 // Depending on which corner your tooltip is at, x and y could mean either height or width!
                  }
              },
              border: {
                  width: 6,
                  radius: 0,
                  color: '#4d4d4d'
              },
              name: 'light', // Use the default light style
              width: 200 // Set the tooltip width
          }
      })
    });

    var browser = navigator.appName;
    var b_version = navigator.appVersion;

    if ((browser == "Microsoft Internet Explorer") && (b_version.indexOf("MSIE 6.0") != -1)) {
        DD_belatedPNG.fix('.png_fix, .header, .navigation-zipcode, .content, .graytabs, .whitetabs, .graytabs .ui-tabbed ul.tab_navi li, .graytabs .ui-tabbed ul.tab_navi li a, .whitetabs .ui-tabbed ul.tab_navi li, .whitetabs .ui-tabbed ul.tab_navi li a .sub-bottom');
    }

});
