﻿var distinctWikiTags = {};
$(document).ready(function() {
    $.ajaxSetup({
        error: function(xhr, status, error) {
            //alert("An AJAX error occured: " + status + "\nError: " + error);
        }
    });

    GetWikiTags();
    var wikiMenuHeight = 0;

    $('[wikiTooltip]').each(
    function() {
        $(this).addClass("wikiTooltip");
        var tag = $(this).attr('wikiTooltip');

        if (!distinctWikiTags[tag]) distinctWikiTags[tag] = [];
        distinctWikiTags[tag].push($(this));
    }
    );
    $('body').append('<ul id="wikibar" ></ul>');
    //alert('Preparing the bar');
    $('#wikibar li').remove();
    for (var key in distinctWikiTags) {
        //alert('adding ' + key);
        wikiMenuHeight += 20;
        var text = distinctWikiTags[key][0].text();
        $('#wikibar').append('<li><span wikiTooltip="' + key + '">' + text + '</span></li>');

    }
    if (wikiMenuHeight != 0) {
        wikiMenuHeight += 50;
        if (wikiMenuHeight < 140) wikiMenuHeight = 140;
        $('#wikibar').sidebar({ injectWidth: 15, width: 290, height: wikiMenuHeight });
    }



    // Use the each() method to gain access to each elements attributes
    $('[wikiTooltip]').each(function() {
        //alert('adding qtip for ' + $(this).text());


        var tag = $(this).attr('wikiTooltip');
        $(this).qtip(
          {
              title: $(this).text(),
              content: 'Loading...', // Give it a loading message while request is being sent
              position: {
                  corner: {
                      target: 'topRight',
                      tooltip: 'bottomLeft'
                  },
                  adjust: { screen: true }
              },
              show: {
                  when: 'click', // Show it on click...
                  solo: true // ...but hide all others when its shown
              },
              hide: 'unfocus', // Hide when it loses focus...
              style: {
                  tip: true, // Create speech bubble tip at the set tooltip corner above
                  textAlign: 'center',
                  name: 'dark'
              },
              api: {
                  // Retrieve the content when tooltip is first rendered
                  onRender: function() {
                      var self = this;
                      var url = "../Wiki/GetWiki.aspx?tag=" + tag;
                      //alert('url = '+url);
                      var strReturn = 'Not loaded';
                      //$.get(url, function(data) {
                      //    self.updateContent(data);
                      //});
                      $.ajax({
                          type: "POST",
                          url: appRoot + "/Messaging/WikiService.asmx/GetWiki",
                          cache: false,
                          contentType: "application/json; charset=utf-8",
                          data: "{tag:'" + tag + "'}",
                          dataType: "json",
                          success: function(data, status) { self.updateContent(data.d); },
                          async: false
                      });
                  }
              }
          });
    });

});

function handleGetWikiTags(data, status) {
    for (var i in data.d) {
        $('#contentBox').highlight(data.d[i].Tag, data.d[i].Tag);
    }
}
function GetWikiTags() {
    $.ajax({
        type: "POST",
        url: appRoot + "/Messaging/WikiService.asmx/GetWikiTags",
        cache: false,
        contentType: "application/json; charset=utf-8",
        data: "{}",
        dataType: "json",
        success: handleGetWikiTags,
        async: false,
        error: failedGetWikiTags
    });
}

function GetWiki(tag) {
    
}
function failedGetWikiTags(xmlRequest) {
    //alert(xmlRequest.status + ' \n\r ' + xmlRequest.statusText + '\n\r' + xmlRequest.responseText);
}

/*

highlight v3

Highlights arbitrary terms.

<http://johannburkard.de/blog/programming/javascript/highlight-javascript-text-higlighting-jquery-plugin.html>

MIT license.

Johann Burkard
<http://johannburkard.de>
<mailto:jb@eaio.com>

*/

jQuery.fn.highlight = function(pat, tag) {
    function innerHighlight(node, pat, tag) {
        var skip = 0;
        if (node.nodeType == 3) {
            var pos = node.data.toUpperCase().indexOf(pat);
            if (pos >= 0) {
                var spannode = document.createElement('span');
                $(spannode).attr('wikiTooltip', pat)
                spannode.className = 'highlight';
                var middlebit = node.splitText(pos);
                var endbit = middlebit.splitText(pat.length);
                var middleclone = middlebit.cloneNode(true);
                spannode.appendChild(middleclone);
                middlebit.parentNode.replaceChild(spannode, middlebit);
                skip = 1;
            }
        }
        else if (node.nodeType == 1 && node.childNodes && !/(script|style)/i.test(node.tagName)) {
            for (var i = 0; i < node.childNodes.length; ++i) {
                i += innerHighlight(node.childNodes[i], pat);
            }
        }
        return skip;
    }
    return this.each(function() {
        innerHighlight(this, pat.toUpperCase(), tag);
    });
};

jQuery.fn.removeHighlight = function() {
    return this.find("span.highlight").each(function() {
        this.parentNode.firstChild.nodeName;
        with (this.parentNode) {
            replaceChild(this.firstChild, this);
            normalize();
        }
    }).end();
};

