// Custom js code for integrating wow macro langauage and LUA
(function($){
  $.EA = {
    isTesting: function() {
      if ($("#hlinks .mod-flair").attr('title') == 'administrator')
      {
        $.EA.isTesting = function() {return true;};
        return true;
      }
      $.EA.isTesting = function() {return false;};
      return false;
    },
    log: function() {
      if ($.EA.isTesting() && typeof console != 'undefined' && console.log)
      {
        $.EA.log = console.log; // call console.log from now on
        return console.log.apply(console,arguments);
      } else {
        $.EA.log = function() {}; // empty this if we can't access console.log
      }
    }
  };
  
  var profiles = $.EA.profiles = {
    factions: [{name:'Neutral', className:'neut'}, {name:'Alliance', className:'alliance'}, {name:'Horde', className:'horde'}],
    profiles: {},
    defaultProfile: {
      faction: 0
    },
    requests: [],
    addRequest: function(userId, callback){
      profiles.requests.push({userId: userId, callback:callback});
      if (!profiles.queryTimeout) {
        profiles.queryTimeout = {timeout: setTimeout(profiles.updateProfiles, 100)};
      }
    },
    requesting: false,
    updateProfiles: function() {
      if (profiles.requesting) {
        profiles.queryTimeout = {timeout: setTimeout(profiles.updateProfiles, 100)};
        return;
      }
      profiles.queryTimeout = false;
      var callbacks = {};
      var ids = [];
      $.each(profiles.requests,function(key, req) {
        if (profiles.profiles[req.userId])
        {
          callback(profiles.profiles[req.userId]);
          return;
        }
        if (!callbacks[req.userId]) {
          callbacks[req.userId] = [req.callback]; 
          ids.push(req.userId);
        } else callbacks[req.userId].push(req.callback);
      });
      profiles.requests = [];
      $.ajax({
        url: profiles.getUrl('/profile/list'),
        data: {ids: ids.join(",")},
        jsonp: 'jsonp',
        dataType: 'jsonp',
        success: function(data) {
          profiles.sessionKey = data.sessionKey;
          $.extend(profiles.profiles, data.userProfiles);
          $.each(callbacks,function(userId, funcs) {
            if (!profiles.profiles[userId]) profiles.profiles[userId] = profiles.defaultProfile;
            $.each(funcs, function(idx,f) {f(profiles.profiles[userId]);});
          });
          profiles.requesting = false;
        },
        error: function() {
          $.EA.log('Error', arguments);
        }
      });
      profiles.requesting = true;
    },
    sessionKey: +new Date(),
    getFaction: function(factionId) {
      if (!factionId || !profiles.factions[factionId]) return profiles.factions[0];
      return profiles.factions[factionId];
    },
    getUrl: function(action) {
      if (!action) action = '';
      // if ($.EA.isTesting()) return "http://epicadvice"+action;
      return "http://profile.epicadvice.com"+action;
    },
    getRealmString: function(profile) {
      var string = '';
      if (profile.region) {
        string = string + "["+profile.region.toUpperCase() + "] ";
        if (profile.realm) string = string + profile.realm;
      }
      return string;
    },
    getProfileData: function(userId, callback) {
      if (profiles.profiles[userId]) {
        callback(profiles.profiles[userId]);        
      } else {
        profiles.addRequest(userId, callback);
      }      
    },
    register: function(){
      // setup document.ready
      $(function() {

        // do nothing unless testing
        // if (!$.EA.isTesting()) return;
        
        // user view page
        var result = document.location.href.match(/\/users\/(\d+)/);
        if (result) {
          $(".user-detail").each(function() {
            $("a[href$=flair]",this).attr('href', 'http://profile.epicadvice.com/badge?logo=1&user=' + (result[1]));
          });
          profiles.getProfileData(result[1], function(profile) {
            var faction = profiles.getFaction(profile.faction);
            $(".user-details tbody").append("<tr><td>Faction</td><td>"+faction.name+"</td></tr>");
            if (profile.region) {
              $(".user-details tbody").append("<tr><td>Region/Realm</td><td>"+profiles.getRealmString(profile)+"</td></tr>");
            }            
            if (profile.character) {
              var text = profile.character;
              if(profile.armorylink) {
                text = $("<a/>").attr('href', profile.armorylink).text(text).wrap('<div>').parent().html();
              }
              $(".user-details tbody").append("<tr><td>Character</td><td>"+text+"</td></tr>");
            }
            $(".user-detail").addClass(faction.className);
            if (profile.tooltip) $(".user-detail > tbody > tr > td:eq(2)").append($(profile.tooltip).css({
             margin: '5px' 
            }));
          });
        }
        
        // user edit page:
        $("#user-edit-form").each(function() {
          $.getScript("/script/realms.js");
          var $form = $(this);
          var userId = $form.attr('action').match(/users\/edit\/(\d+)/);
          if (userId) userId = userId[1];
          $.EA.profiles.getProfileData(userId, function(profile) {
            var $tbody = $("table tbody", $form);
            var $factionSelector = $("<select/>");
            var $formSubmit = $("input[type=submit]", $form);
            $.each($.EA.profiles.factions, function(id, faction) {
              var option = $("<option value='"+id+"' />").text(faction.name);
              if (id == profile.faction) option.attr('selected','selected');
              $factionSelector.append(option);
            });

            var factionRow = $("<tr />").append("<td>Faction</td>", $("<td />").append($factionSelector));
            factionRow.prependTo($tbody);

            var $regionSelect = $("<select/>");
            var $realmSelect = $("<select/>").css('display','inline').hide();
          
            $regionSelect.append("<option value=''>--</option>");
          
            // realm selection:
            (function checkRealms() {
              if (typeof jsonRealms == 'undefined') {
                setTimeout(checkRealms, 100);
                return;
              } 
              var realmList = jsonRealms;
              var regionRealms = {};
              $.each(realmList, function(region,realms) {
                var regionOpt = $("<option value='"+region+"' />").text(region.toUpperCase());
                if (profile.region == region) {
                  regionOpt.attr('selected', 'selected');
                }
                $regionSelect.append(regionOpt);
                regionRealms[region] = [];
                $.each(realms, function(i, realm) {
                  var $ro = $("<option />").attr('value', realm).text(realm);
                  if (region == profile.region && realm == profile.realm) {
                    $ro.attr('selected', 'selected');
                  }
                  regionRealms[region].push($ro);
                });
              });
              $regionSelect.change(function() {
                $realmSelect.val('').empty().hide();
                var realms = regionRealms[$(this).val()];
                if (realms) {
                  $realmSelect.show().append($("<option value=''>--Select a Realm--</option>"));
                  $.each(realms,function(i,v) {$realmSelect.append(v);});
                  $realmSelect.val('').val(profile.realm);
                }
              });
              $regionSelect.change();
            })();
          
            var $character = $("<input type='text'/>").bind("keyup change",function(e) {
              setTimeout(function() {
                $character.val($character.val().replace(/\s+/,''));
              },0);
            }).val(profile.character||'');
            var realmRow = $("<tr />").append("<td>Realm</td>", $("<td />").append($regionSelect, $realmSelect));
            var characterRow = $("<tr />").append("<td>Character Name</td>", $("<td />").append($character));
            $tbody.prepend(realmRow, characterRow);
            
            $form.submit(function(e) {
              $form.find("input[type=submit]").attr('disabled','disabled');
              if (($factionSelector.val() != profile.faction) ||
                  ($realmSelect.val() != profile.realm) ||
                  ($character.val() != profile.character) ||
                  ($regionSelect.val() != profile.region))
              {
                var errorTimeout = setTimeout(function() {
                  alert('There was an error saving extended profile information');
                  $form.get(0).submit();
                }, 10000);
                var profileText = $("#AboutMe").val();
                $("#AboutMe").val(profileText + "\n--sessionKey:"+$.EA.profiles.sessionKey+"--");
                $form.ajaxSubmit({
                  success: function() {
                    $formSubmit.val('Saving Extended Profile');
                    var ajax = {
                      url: $.EA.profiles.getUrl("/profile/edit/id/"+userId),
                      dataType: 'jsonp',
                      jsonp: 'jsonp',
                      data: {sessionKey: $.EA.profiles.sessionKey, faction: $factionSelector.val(), region: $regionSelect.val(), realm: $realmSelect.val(), character: $character.val()},
                      success: function() {
                        clearTimeout(errorTimeout);
                        $formSubmit.val('Saving Profile');
                        $form.get(0).submit();
                      }
                    };
                    $.ajax(ajax);
                  },
                  error: function() {
                    $.EA.log('Errored:', arguments);
                    alert('There was an error saving extended profile information');
                    $form.get(0).submit();
                  }
                });
                $formSubmit.val('Authorizing Extended Profile Change').addClass('ajax-active');
                $("#AboutMe").val(profileText);
                e.preventDefault();
                return false;
              }
            });
          });
        });
        
        // other user info blocks
        var profileCheck = function() {          
          $('.user-info .user-details').each(function() {
            if ($.data(this, 'profile')) return;
            var $ud = $(this);
            var $ui = $ud.closest('.user-info');
            var userId = 0;
            $("a", $ud).each(function() {
              var match = this.href.match(/\/users\/(\d+)/);
              if (match) {
                userId = match[1];
                return false;
              }
            });
            if (userId) {
              profiles.getProfileData(userId, function(profile) {
                if ($.data($ud[0], 'profile') === profile) return;
                var faction = profiles.getFaction(profile.faction);
                $ui.addClass(faction.className);
                if (profile.armorylink) {
                  $ui.append($("<a class='armorylink'>WoW Armory</a>").attr('href', profile.armorylink).css('float','left'));                  
                }
                if (profile.tooltip) {
                  profile.tooltip = $(profile.tooltip).css({
                    position: 'absolute',
                    zIndex: '3000',
                    display: 'none'
                  });
                  function over(e) {
                    var tipX = e.pageX + 12;
                		var tipY = e.pageY + 12;
                		$("body").append(profile.tooltip.hide());
                		var css = {
                		  width: $.browser.msie?profile.tooltip.outerWidth(true):profile.tooltip.width(),
                		  left: tipX,
                		  top: tipY
                		};
                		profile.tooltip.css(css).fadeIn('medium');
                  }
                  function move(e) {
                    var tipX = e.pageX + 12;
                		var tipY = e.pageY + 12;
                		var tipWidth = $("#simpleTooltip").outerWidth(true);
                		var tipHeight = $("#simpleTooltip").outerHeight(true);
                		if(tipX + tipWidth > $(window).scrollLeft() + $(window).width()) tipX = e.pageX - tipWidth;
                		if($(window).height()+$(window).scrollTop() < tipY + tipHeight) tipY = e.pageY - tipHeight;
                		
                    profile.tooltip.css({
                      left: tipX,
                      top: tipY
                    });
                  }
                  function out(e) {
                    profile.tooltip.remove();
                  }
                  $ui.hover(over, out); 
                  $ui.bind('mousemove', move);
                }
                // if (profile.region)
                // {
                //   $ud.append("<br/><span class='realm'>"+profiles.getRealmString(profile)+"</span>");                  
                // }
                $.data($ud[0], 'profile', profile);
              });
            }
            $.data(this, 'profile', profiles.defaultProfile);
          });
        };
        profileCheck();
        setInterval(profileCheck, 100);

        // var script = profiles.getUrl('/js/hook.js');
        // console.log("Loading Script: "+script);
        // $.getScript(script);
      });
    }
  };  
  
  // register EA Profile Extensions:
  profiles.register();

  var tagger = $.EA.tags = {
    cache: {},
    exprs: [
      {re: /^(alliance|death-knight|druid|horde|hunter|mage|paladin|priest|rogue|shaman|warlock|warrior|blood|frost|unholy|balance|feral|restoration|beast-mastery|marksmanship|survival|arcane|fire|frost|holy|protection|retribution|discipline|shadow|assassination|combat|subtlety|elemental|enhancement|affliction|demonology|destruction|arms|fury|enchanting|tailoring|leatherworking|blacksmithing|engineering|inscription|mining|herbalism|skinning|jewelcrafting)$/,
       replace: function(img) { return "http://profile.epicadvice.com/images/icons/"+img+".gif"; } }
    ],
    paint: function() {
      $(".post-tag").each(function() {
        var $tag = $(this), totest = $tag.text().replace(/^\s+|\s+$/g,'');
        $tag.find("img").remove();
        if (!tagger.cache.hasOwnProperty(totest))
        {
          tagger.cache[totest] = [];
          $.each(tagger.exprs,function(i, tester) {
            if (totest.match(tester.re)) { tagger.cache[totest].push("<img class=\"tagimg\" src=\"" + 
              totest.replace(tester.re, tester.replace) + "\" width=\"18\" height=\"18\" />&nbsp;");
            }
          });
        }
        $.each(tagger.cache[totest],function(i,img) {
          $tag.prepend(img);
        });
        
      });
    },
    register: function() {
      var oldFunc = getTagsSelector;
      if (oldFunc) getTagsSelector = function getTagsSelector(jPrefs) {
        return oldFunc(jPrefs).replace(/div.t-\s+([^,]+,?)/g,"div.t-$1");
      };
      $(tagger.paint);
    }
  };
  
  tagger.register();

  
  PR.registerLangHandler(
      PR.createSimpleLexer(
          [
           // Whitespace
           [PR.PR_PLAIN,       /^[\t\n\r \xA0]+/, null, '\t\n\r \xA0'],
           // A double or single quoted, possibly multi-line, string.
           [PR.PR_STRING,      /^(?:\"(?:[^\"\\]|\\[\s\S])*(?:\"|$)|\'(?:[^\'\\]|\\[\s\S])*(?:\'|$))/, null, '"\'']
          ],
          [
           // A comment is either a line comment that starts with two dashes, or
           // two dashes preceding a long bracketed block.
           [PR.PR_COMMENT, /^--(?:\[(=*)\[[\s\S]*?(?:\]\1\]|$)|[^\r\n]*)/],
           // A long bracketed block not preceded by -- is a string.
           [PR.PR_STRING,  /^\[(=*)\[[\s\S]*?(?:\]\1\]|$)/],
           [PR.PR_KEYWORD, /^(?:and|break|do|else|elseif|end|false|for|function|if|in|local|nil|not|or|repeat|return|then|true|until|while)\b/, null],
           // A number is a hex integer literal, a decimal real literal, or in
           // scientific notation.
           [PR.PR_LITERAL,
            /^[+-]?(?:0x[\da-f]+|(?:(?:\.\d+|\d+(?:\.\d*)?)(?:e[+\-]?\d+)?))/i],
           // An identifier
           [PR.PR_PLAIN, /^[a-z_]\w*/i],
           // A run of punctuation
           [PR.PR_PUNCTUATION, /^[^\w\t\n\r \xA0][^\w\t\n\r \xA0\"\-\+=]*/] //" -- fixing code formatting
          ]),
      ['lua']);
  
  PR.registerLangHandler(
    PR.createSimpleLexer(
      [
        // Whitespace:
        [PR.PR_PLAIN, /^[\t\n\r \xA0]+/, null, '\t\n\r \xA0']
        // Strings:
      ],
      [
        ['lang-lua', /^\/(?:run|script) ([^\r\n]+)/i],
        [PR.PR_KEYWORD, /^([\/#]\S+)/],
        [PR.PR_LITERAL, /^\[([^\]]+)\]/],
        [PR.PR_PUNCTUATION, /^[^\w\t\n\r \xA0][^\w\t\n\r \xA0\"\-\+=]*/] //" -- fixing code formatting
      ]
    ),
    ['wowmacro']
  );
  
  window.styleCode = function() {
    var hascode = false;
    var useLua;
    $("pre code").parent().each(function() {
      if (!$(this).hasClass('prettyprint')) {
        var text = $(this).text();
        // detect WOW Macro
        var macroLines=0, unknownLines = 0,totalLines = 0;
        text.replace(/(?:^|[\r\n]+)\s*(.)/g,function() {
          totalLines++;
          if (arguments[1] == '#' || arguments[1] == '/')
          {
            macroLines++;
          } else {
            unknownLines++;
          }
        });
        if (macroLines > unknownLines)  // simple for now...
        {
          $(this).addClass('lang-wowmacro');
        } else {
          if (typeof useLua == 'undefined') {
            useLua = false;
            $('#question .post-taglist .post-tag').each(function() {
              if ($(this).text().match(/lua|addon|macro/i))
              {
                useLua = true;
                return false;
              }
            });
          } 
          if (useLua) $(this).addClass('lang-lua');
          
        }
        $(this).addClass('prettyprint');
        hascode = true;
      }
    });
    if (hascode) { prettyPrint(); }
  };

  $(function() {
    var $topbar = $("#topbar");
    var rep = $topbar.find(".reputation-score").text().replace(/,|\s/g,'');
    if (rep.match(/\d+K/i)) rep = rep.replace(/K/g, '') * 1000;
    if (rep && (rep = parseInt(rep, 10)))
    {
      var abilities = [
        {rep: 15, text: 'Vote Up, Flag Offensive'},
        {rep: 50, text: 'Leave Comments'},
        {rep: 100, text: 'Vote Down (costs rep), Edit Community Wiki Posts'},
        {rep: 200, text: 'Reduced Advertising'},
        {rep: 250, text: 'Vote to Close/Reopen your questions, Create new tags'},
        {rep: 500, text: 'Retag Questions'},
        {rep: 2000, text: 'Edit other peoples posts'},
        {rep: 3000, text: 'Vote to close or reopen any questions'},
        {rep: 10000, text: 'Delete closed questions, access to moderation tools'}
      ];
			var levels = [0,1,15,30,50,75,100,125,150,175,200,225,250,275,300,325,350,375,400,425,450,475,500,550,600,650,700,750,800,850,900,950,1000,1050,1100,1150,1200,1250,1300,1350,1400,1450,1500,1550,1600,1650,1700,1750,1800,1850,1900,1950,2000,2100,2200,2300,2400,2500,2600,2700,2800,2900,3000,3100,3200,3300,3400,3500,3750,4000,4250,4500,4750,5000,5500,6000,7000,8000,9000,10000];
			
      var $xpbar = $("<div class='xpbar'><div class='value' /><div class='repvalue' /><span class='text'></div>");
      var $value = $xpbar.find('.value');
      var $repvalue = $xpbar.find('.repvalue');
      var $text = $xpbar.find('.text');

      var lastLevel = { level: 0, rep: 0};
      var nextLevel = { level: 80, rep: 10000};

      var lastRepStage = {rep: 0, text: 'Created Account'};
      var nextRepStage = {rep: 100000, text: 'Become a Legend'};
      var currentLevel = 1;
      var currentRepLevel = 0;


      $.each(levels, function(level, reputation) {
        if (rep < reputation) {
          nextLevel = {rep: reputation, level: level};
          return false; // break loop
        }
        if (rep >= reputation) {
          lastLevel = {rep: reputation, level: level};
          currentLevel = level;
        }
      });

      $.each(abilities, function(level, abil) {
        if (rep < abil.rep) {
          nextRepStage = abil;
          return false; // break loop
        }
        if (rep >= abil.rep) {
          lastRepStage = abil;
          currentRepLevel = level;
        }
      });
  
      var abilProgress = Math.round(((rep - lastRepStage.rep)*100) / (nextRepStage.rep - lastRepStage.rep));
      var levelProgress = Math.round(((rep - lastLevel.rep)*100) / (nextLevel.rep - lastLevel.rep));
      $value.animate({width: levelProgress+'%'}, 2000);
      $repvalue.animate({width: abilProgress+'%'}, 2000);
  
      var toLevel = nextLevel.rep - rep;
      var toProgress = nextRepStage.rep - rep;
  
      $text.html('<span class="level-text">Level: '+currentLevel+'</span> - Reputation until next Level: '+toLevel+' - '+(rep-lastLevel.rep)+'/'+(nextLevel.rep-lastLevel.rep)+' ('+levelProgress+'%)');
      $xpbar.attr('title', 
        'Next Ability: '+nextRepStage.text+' ('+nextRepStage.rep+')  '+
        'Reputation Needed: '+toProgress+' ('+abilProgress+'%)'
      );
      $xpbar.css('cursor', 'pointer').click(function() {
        window.location = '/faq#replevels';
      }).insertAfter($('#hlogo').height(130));
  
    }  
    $(".module:has(h4:contains('Formatting Reference')) p:last-child").each(function() {
      $("<p>Link your <a href='http://www.wowhead.com/?item=37674'>Items</a>, Spells, Quests, etc. to <a href='http://wowhead.com/'>Wowhead</a> to show tooltips on mouseover</p>").insertBefore(this);
    });
  });
  $(function() {

          // load youtubin
        $.youtubin({
          swfWidth : 655,
          swfHeight : 530
        });

    // amazon affiliate ID replacement
    $(".post-text a[href*=amazon.co]").each(function() {
      if (this.href.match(/https?:\/\/[^\/]+amazon\.co/i)) {
        this.target = "_blank";
        this.href = this.href.replace(/(?:\?.*)?$/, function(text) {
          text = text.replace(/tag=[^&]+(?:&|$)/i, '');
          if (!text || text.length<2) return "?tag=epicadvcom-20";
          return text + "&tag=epicadvcom-20";
        });
      }
    });
  });
})(jQuery);

$(function() {

  if ($("#post-editor").length) {
    $.ajax({url:"http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/jquery-ui.min.js", 
     dataType:'script', cache: true});
    $.ajax({url:"http://profile.epicadvice.com/ea/editor.js", 
     dataType:'script', cache:true,
     success:function() {
      var loop = setInterval(function() {
        if (Attacklab && Attacklab.panels) {
          attachWowheadEditor();
          clearInterval(loop);
        }
      }, 100);
    }});
  }
   

});

