///<reference path="jquery-1.3.2.min-vsdoc.js" />
$(document).ready(function() {
    applyTooltips();
    applyBrandingHelperTooltips();
});

function hideSelectedSort() {
    var selected = $("#selectedSort").val();
    $(selected).addClass("disabled");
}

($(document).ready(function($) {

    var timeout = false;
    var selectClass = "ac_over";
    var input = $("#category");
    var results;
    populateCategoryPickers();

    function populateCategoryPickers() {
        var category = $("#category");
        var categorySuggest = $("#categorySuggest");
        var subCategory = $("#subCategory");
        var subCategorySuggest = $("#subCategorySuggest");

        category.focus(function() {
            GetCategorySuggest("", categorySuggest);
            categorySuggest.show();
            results = $("#categorySuggest ul");
            input = $("#category");
            subCategory.val("");
        });

        subCategory.focus(function() {
            if (category.val() == "") return;
            GetCategorySuggest(category.val(), subCategorySuggest);
            subCategorySuggest.show();
        });

        category.blur(function() {
            setTimeout(function() { categorySuggest.hide() }, 200);
        });

        subCategory.blur(function() {
            setTimeout(function() { subCategorySuggest.hide() }, 200);
        });

        trapKeys();
    }

    function trapKeys() {
        try {
            results.bgiframe();
        } catch (e) { }


        if ($.browser.mozilla)
            input.keypress(processKey);
        else
            input.keydown(processKey);
    }

    function processKey(e) {

        // handling up/down/escape requires results to be visible
        // handling enter/tab requires that AND a result to be selected
        if (/27$|38$|40$/.test(e.keyCode) ||
					(/^13$/.test(e.keyCode) && getCurrentResult())) {

            if (e.preventDefault)
                e.preventDefault();
            if (e.stopPropagation)
                e.stopPropagation();

            e.cancelBubble = true;
            e.returnValue = false;

            switch (e.keyCode) {

                case 38: // up
                    prevResult();
                    break;

                case 40: // down
                    nextResult();
                    break;

                //                case 9:  // tab    
                case 13: // return
                    selectCurrentResult();
                    break;

                case 27: //	escape
                    results.hide();
                    break;

            }

        } else /*if ($input.val().length+1 != prevLength)*/{

            prevLength = input.val().length;
        }
    }

    function getCurrentResult() {
        if ($("#category").val().length == 0) {
            results = $("#categorySuggest ul");
        }
        else if ($("#subCategorySuggest ul").length > 0) {
            results = $("#subCategorySuggest ul");
        }

        var currentResult = results.children('li.' + selectClass);

        if (!currentResult.length)
            currentResult = false;

        return currentResult;

    }

    function selectCurrentResult() {

        currentResult = getCurrentResult();

        if (currentResult) {
            input.val(currentResult.text());
            results.hide();
            if ($("#category").val() != "") {
                input = $("#subCategory");
                try {
                    results.bgiframe();
                } catch (e) { }


                if ($.browser.mozilla)
                    input.keypress(processKey);
                else
                    input.keydown(processKey);
            }

            //            if (options.onSelect)
            //                options.onSelect.apply($input[0]);

        }

    }

    function firstResult() {

        results.children('li:first-child').addClass(selectClass);
    }

    function nextResult() {

        currentResult = getCurrentResult();

        if (currentResult)
            currentResult
						.removeClass(selectClass)
						.next()
							.addClass(selectClass);
        else
            results.children('li:first-child').addClass(selectClass);

    }

    function prevResult() {

        currentResult = getCurrentResult();

        if (currentResult)
            currentResult
						.removeClass(selectClass)
						.prev()
							.addClass(selectClass);
        else
            results.children('li:last-child').addClass(selectClass);

    }

    function GetCategorySuggest(name, suggestDiv) {
        var category = $("#category");
        var categorySuggest = $("#categorySuggest");
        var subCategory = $("#subCategory");
        var subCategorySuggest = $("#subCategorySuggest");
        var html = '<ul class="ac_results">'
        $.ajaxSetup({ cache: false });
        $.getJSON("/api/1/getCategories?categoryName=" + name, function(data) {
            for (var i = 0; i < data.Results.length; i++) {
                html += "<li>" + data.Results[i].UrlName + "</li>";
            }
            html += "</ul>";
            suggestDiv.html(html);
            var categorySuggestLi = $("#categorySuggest li");
            var subCategorySuggestLi = $("#subCategorySuggest li");

            categorySuggestLi.mouseover(function() {
                categorySuggestLi.removeClass("ac_over");
                $(this).addClass("ac_over");
            });

            subCategorySuggestLi.mouseover(function() {
                subCategorySuggestLi.removeClass("ac_over");
                $(this).addClass("ac_over");
            });

            categorySuggestLi.click(function() {
                category.val($(this).html());
                categorySuggest.hide();
                results = $("#subCategorySuggest ul");
                input = $("#subCategory");
            });

            subCategorySuggestLi.click(function() {
                subCategory.val($(this).html());
                subCategorySuggest.hide();
            });
        });
    }
}));


//qTips
function applyTooltips() {
    $(".thumb").mouseover(function() {
        $(this).children(".support").addClass("thumbHover");
    });

    $(".thumb").mouseout(function() {
        $(".thumb").children(".support").removeClass("thumbHover");
    });

    $('.thumb').each(function() {
        var content = $(this).children('.qTip').html();
        if (content != null) {
            $(this).qtip(
      {
          content: content,
          position: {
              corner: {
                  tooltip: 'bottomMiddle',
                  target: 'topMiddle'
              },
              adjust: { x: 0, y: 10 }
          },
          show: { effect: { type: 'fade', length: 1 }, delay: 200, solo: true },
          hide: {
              fixed: true // Make it fixed so it can be hovered over
          },
          style: {
              tip: true, // Give it a speech bubble tip with automatic corner detection
              name: 'blue', // Inherit from preset style
              width: 200,
              padding: 10,
              color: 'black',
              textAlign: 'center',
              border: {
                  width: 5,
                  radius: 5,
                  color: '#006699'
              }
          }
      });
        }
    });
}

function applyBrandingHelperTooltips(title) {
    $('.annotation').each(function() {
        var content = $(this).children('.brandingExplanation').html();
        var title = $(this).children('.brandingExplanation h3').html();
        if (content != null) {
            $(this).qtip(
      {
          content: { title: {
            text: 'Branding',
            button: 'Close'
            }, 
            text: content
          },
          position: {
              target: $(document.body), // Position it via the document body...
              corner: 'center' // ...at the center of the viewport
          },
          show: {
              when: 'click', // Show it on click
              solo: true, // And hide all other tooltips
              delay: 200
          },
          hide: false,
          style: {
              width: { max: 800 },
              padding: '14px',
              border: {
                  width: 9,
                  radius: 9,
                  color: '#666666'
              },
              name: 'light'
          },
          api: {
              beforeShow: function() {
                  // Fade in the modal "blanket" using the defined show speed
                  $('#qtip-blanket').fadeIn(this.options.show.effect.length);
              },
              beforeHide: function() {
                  // Fade out the modal "blanket" using the defined hide speed
                  $('#qtip-blanket').fadeOut(this.options.hide.effect.length);
              }
          }
      });
        }
    });

    $('<div id="qtip-blanket">')
      .css({
          position: 'absolute',
          top: $(document).scrollTop(), // Use document scrollTop so it's on-screen even if the window is scrolled
          left: 0,
          height: $(document).height(), // Span the full document height...
          width: '100%', // ...and full width

          opacity: 0.7, // Make it slightly transparent
          backgroundColor: 'black',
          zIndex: 5000  // Make sure the zIndex is below 6000 to keep it below tooltips!
      })
      .appendTo(document.body) // Append to the document body
      .hide(); // Hide it initially

      $('a[href=#]').live('click', function() {
          return false;
      });
  }