function ptCrewShow(data) {
  var u = mtGetUser();
  if(u && u.can_post)
	$(data).find('.pt-crew').show();
}

function kwExtLinks(data) {
  $(data).find('a[href][rel*="external"]').each(function(i) {
    this.target = '_blank';
  });
}

var base64chars = '0123456789:;ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split("");
var base64inv = new Array(256); for(var i=0;i<base64chars.length;i++){base64inv[base64chars[i].charCodeAt(0)] = i;}
function kwMailLinks(data) {
  $(data).find('a[href^="mailto:"]').each(function(i) {
    var xr = this.href.match(/^mailto:([A-Za-z0-9:;+]+)$/);
    var k = 156 & 255;
    if(!xr) return;
    var s = xr[1];
    var a = new Array();
    var p = (s.charAt(s.length-1) == '+' ? (s.charAt(s.length-2) == '+' ? 'AA' : 'A') : '');
    var r = '';
    s = s.substr(0, s.length - p.length) + p;
    for (var c = 0; c < s.length; c += 4) {
      var n = (base64inv[s.charCodeAt(c)] << 18) + base64inv[s.charCodeAt(c+3)] +
              (base64inv[s.charCodeAt(c+1)] << 12) + (base64inv[s.charCodeAt(c+2)] << 6);
      a.push((n >>> 16) & 255, (n >>> 8) & 255, n & 255);
    }
    if(p.length >= 1) { a.pop();}
    if(p.length == 2) { a.pop();}
    var b = 0;
    s = '';
    for(var i=0;i<a.length;i++) {
      s += String.fromCharCode(b ^= a[i]^k);
    }
    xr = s.split(/\|/);
    this.href = 'mailto:' + xr[0];
    if(xr.length > 1) $(this).html(xr[1]);
  });
}

// Random encryption key feature by Andrew Moulden, Site Engineering Ltd
// This code is freeware provided these four comment lines remain intact
// A wizard to generate this code is at http://www.jottings.com/obfuscator/

var __MTTBLINK__;
var __MTTBID__;
function obfuscator(coded, key, mode, path, hidden) {
        shift = coded.length;
        link = "";
        
        for(i=0;i<coded.length;i++) {
                if (key.indexOf(coded.charAt(i))==-1) {
                        ltr = coded.charAt(i);link+=(ltr);
                } else {
                        ltr = (key.indexOf(coded.charAt(i)) - shift + key.length) % key.length;
                        link += (key.charAt(ltr));
                }
        }
        if(mode == 'hidden_input') {
                document.write('<input type="hidden" name="CCode" value="' + link + '" />');
        } else if(mode == '__MTTBLINK__') {
                __MTTBLINK__ = path + link;
                if(hidden) return;
                document.write(link);
        } else if(mode == '__MTTBID__') {
                __MTTBID__ = link;
                if(hidden) return;
                document.write(link);
        }
}

$(function(){
  $('div.toggle-show').each(function(i){
    $this = $(this);
    $this.wrapInner('<div/>').children().hide().end()
      .prepend('<a class="hide" href="javascript:void(0);">'+$this.attr('title')+'</a>')
      .attr('title', '')
      .children(':first').click(function(event){
        event.preventDefault();
        $(this).toggleClass('hide').siblings().slideToggle('normal');
      });
  });
});

$(function() {
  $('#header-search-form').attr('action', '/mt/'+'search.fcgi');
  $('#comments-form').attr('action','/mt/'+'comments.fcgi');
  $('#comments-form').bind('form-pre-serialize',
  function(event, form, opt, veto) {
    var text = $('#comment-text').val();
    text = text.replace(/\r?\n/g, '[:br:]');
    text = text.replace(/\s+/g, ' ');
    var $text = '';
    if('function' === typeof innerXHTML) {
      $text = $('<div/>')[0];
      innerXHTML($text, text);
      $text = innerXHTML($text);
    } else {
      $text = $('<div/>').html(text).html();
    }

    $text = $text.replace(/<img start="fileopen" loop="1"/g, '<img');
    $text = $text.replace(/<((br|img|hr)[^>]*)><\/\2>/g, '<$1/>');
    $text = $text.replace(/<(\/?\w+)>\s*<\/\1>/g, '');
    $text = $text.replace(/\[:br:\]/g, '\n');

    text = text.replace(/\[:br:\]/g, '\n');

    if(text == $text) {
      veto.veto = false;
      return;
    }
    var dmp = new diff_match_patch();
    var d = dmp.diff_main(text, $text);
    dmp.diff_cleanupSemantic(d);
    var ds = dmp.diff_prettyXHtml(d);

    $('#comment-preview-box').html('<div class="comment-error"><p>Comment submission or preview failed: Invalid format detected.  Please review the following corrections that have been made to your comment.</p><pre class="diff">'+ds+'</pre></div>');
    var text = $('#comment-text').val($text);
    xommentFormOkay();
    veto.veto = true;
  });
});

$(function() {
var u = mtGetUser();
if (u && u.is_authenticated) {
  return true;
}
$('form.poll-form').hide();
$('div.poll-container').append('<p class="poll-greeting">\<a href="javas\cript:void(0)" onclick="return mtSignInOnClick(\'comment-greeting\')"\>Sign in\<\/a\> to vote.</p>');
return true;
});

function checkVote(id) {
return true;
}

function ptCheckVotes() {
    var u = mtGetUser();
    if ( !(u && u.is_authenticated) ) {
        return true;
    }
    $('form.poll-form').show();
    $('p.poll-greeting').hide();

    var id = $('div.poll-container input[name="poll_id"]').val();
    var type  = $('#type_' + id).val();
    var voted = mtGetCookie( type + '_id' );
    if (!voted) {
        return;
    }
    var voted_array = voted.split(',');
    for (var poll in voted_array) {
        if (voted_array[poll] == id) {
            var $vform = $('#' + type + '-form-' + id);
            $vform.hide();
            if (!$('#' + type + '-results-' + id).html()) {
                $vform.get(0).results_only.value = '1';
                submitVote(id);
            }
        }
    }   
}

mtAttachEvent('usersignin', ptCheckVotes);

function _checkVote(id) {
    var type  = $('#type_' + id).val();
    var voted = mtGetCookie( type + '_id' );
    var u = mtGetUser();
    if(!(u && u.can_comment)) {
        $('form.poll-form').hide().after('<p>You must sign in to vote.  Please refresh after logging in to view the poll.</p>');
    }
    if (!voted) {
        return;
    }
    var voted_array = voted.split(',');
    for (var poll in voted_array) {
        if (voted_array[poll] == id) {
            var $vform = $('#' + type + '-form-' + id);
            $vform.hide();
            if (!$('#' + type + '-results-' + id).html()) {
                $vform.get(0).results_only.value = '1';
                submitVote(id);
            }
        }
    }

}

function viewResults(id) {
    var type  = $('#type_' + id).val();
    var $vform = $('#' + type + '-form-' + id);
    $vform.get(0).results_only.value = '1';
    submitVote(id);
    $vform.show();
}

function submitVote(id) {
    var type  = $('#type_' + id).val();
    var handleSuccess = function(responseText, status) {
        var $div = $('#' + type + '-results-' + id);
        if(responseText !== undefined){
            if ( responseText.match('unpublished') ) {
                $div.html('<p class="unpublished">' + responseText + '</p>');
            }
            else if ( responseText.match('currently closed') ) {
                $div.html('<p class="currently-closed">' + responseText + '</p>');
            }
            else if ( responseText.match('not a valid option') ) {
                $('#' + type + '-form-' + id ).show();
                $div.html('<p class="error">' + responseText + '</p>');
            }
            else { // Successful vote
                $div.html(responseText);
                var $vform = $('#' + type + '-form-' + id);
                if ($vform.get(0).results_only.value=='0') {
                    var cname = type + '_id';
                    var cur = mtGetCookie(cname);
                    if (cur) {
                        var cvalue = cur + ',' + id;
                    } else {
                        var cvalue = id;
                    }
                    var now = new Date();
                    mtFixDate(now);
                    now.setTime(now.getTime()+999*24*60*60*1000);
                    mtSetCookie(cname, cvalue, now, '/');
                }
                $vform.get(0).results_only.value = '0';
            }
        }
    };

    var handleFailure = function(req,statusText,status) {
        $('#' + type + '-form-' + id).show();
        var $div = $('#' + type + '-results-' + id);

        if (responseText !== undefined) {
            div.html( "<p><strong>Error</strong><br />"
                    //+ "Transaction id: " + o.tId + "<br />"
                    + "HTTP status: " + status + "</br />"
                    + "Status code message: " + statusText + "</p>"
                    );
        }
    };

    var $vform = $('#' + type + '-form-' + id);
    // Check that visitor has selected an option before submitting
    for (var i = 0; i < $vform.get(0).poll_choice.length; i++) {
        if ($vform.get(0).poll_choice[i].checked) {
            var selected = 1;
        }
    }
    if ( selected || ($vform.get(0).results_only.value == '1') ) {
        $vform.ajaxSubmit({
            success: handleSuccess,
            error: handleFailure,
            url: "/mt/plugins/PollPosition/vote.fcgi"
            });
        $('#'+type + '-results-' + id).html('<img src="http://pandasthumb.org/mt-static/images/indicator.gif" width="66" height="66" />');
        $vform.hide();
        return false;
    }
    else {
        alert('Please make a selection before submitting to this ' + type);
        return false;
    }
}

if('function' === typeof onLoadComments) {
  onLoadComments(kwExtLinks);
  onLoadComments(kwMailLinks);
  onLoadComments(ptCrewShow);
} else {
  $(function(){
    kwExtLinks(document);
    kwMailLinks(document);
    ptCrewShow(document);
  });
}


