/*
  tool.js - Last Revised 10/7/2014.
  This file comprises a toolkit of handy functions for website design.
  All code has been passed through JSLint and verifies completely.
  (jslint browser: true, sloppy: true, indent: 2);
  
  Shortcuts:
  ele(), nam(), tag(), val(), valnam(), valset(), valsetnam() are shortcuts to long,
  hard to remember (much less type _in proper case_) javascript commands.
  Other functions call upon these shortcuts for clarity of code.
  ie() is a monstrosity. Unfortunately, IE is a piece of shit and I must soft degrade.
  ios() is it's match for ios mobile devices.
  
  Event Triggering:
  addEvent() is a cross-browser method for adding post-execute javascript functions.
  I use it all the time, to have my javascript add itself to existing page elements.
  For example, a button with id 'charley', popping up a SuperAlert.
  addEvent(ele("charley"),"click",function(){
    SuperAlert("You clicked me!");
  });
  
  enter() is a function created to allow on-keypress of "enter" to trigger a function.
  Useful when you're doing a login form or something and want it to call js when enter is pressed.
   
  Form Validation and Other Form Work:
  isnum(), isalpnum(), isblank(), isemail(), are useful for form validation.
  go() takes a url and array of values, generates a form and submits it.
  
  UI:
  The global wh() variable contains current window width and height (wh.w,wh.h),
  Updates on document load, window resize.
  focus(), hide(), show(), swap() are useful for controlling visibility of page
  elements and interchanging them. Good for UI.
  asyncimg() loads an image after the page has loaded. Speeds layout generation.
  SuperAlert() is my own custom alert/prompt box, designed to mimic the natives in Mozilla Firefox.
  It's use is self-explanatory to anyone who's ever used javascript prompts.
  As of 11/17/2013, uses the global wh() variable.
  tog(), tog_draw() use a hidden textfield to back an img tag. Name the img as {datafield}_img.
*/
/* Shortcuts */
function ele(id) {return document.getElementById(id); }
function nam(id) {return document.getElementsByName(id)[0]; }
function tag(id) {return document.getElementsByTagName(id)[0]; }
function val(id) {return ele(id).value; }
function valnam(id) {return nam(id).value; }
function valset(id, val) {ele(id).value = val; }
function valsetnam(id, val) {nam(id).value = val; }
function ie() { return (navigator.appName === 'Microsoft Internet Explorer'); }
function ios() { return navigator.userAgent.match(/(iPod|iPhone|iPad)/) && navigator.userAgent.match(/AppleWebKit/); }
/* Event Triggering */
function addEvent(obj, evt, fn) {
  if (obj) {
    if (obj.addEventListener) {
      obj.addEventListener(evt, fn, false);
    } else if (obj.attachEvent) {
      obj.attachEvent("on" + evt, fn);
    }
  }
}
function enter(evt, func) {
  /* Monitors keypresses and fires off a function of your choice if enter is pressed */
  var k = evt.keyCode || evt.which;
  if (k === 13) {
    if (func && (typeof func === "function")) {
      func();
    }
  }
  return false;
}
/* Form Validation and Other Form Work */
function isnum(value) {return (/^[0-9]+$/).test(value); }
function isalpnum(value) {return (/^[a-zA-Z0-9 _]+$/).test(value); }
function isblank(value) {if (value === null) {return true; } if (value === "") { return true; } if (value.length === 0) { return true; } return false; }
function isemail(value) {return (/^[a-zA-Z0-9]+@[a-zA-Z0-9]+\.[a-zA-Z0-9]+$/).test(value); }
function between(value,start,end){
  /* Finds data in value between start, end. Returns null if notfound */
  var temp = value;
  var startpos = temp.indexOf(start);
  if (startpos === -1) { return null };
  temp = temp.substring(startpos + start.length); 
  var endpos = temp.indexOf(end);
  if (endpos === -1) { return null };
  temp = temp.substring(0,endpos);
  return temp;
}
function go(path, params, method) {
  /* takes a dictionary of parameters and submits them as a form to path */
  method = method || "post"; // Set method to post by default, if not specified.
  if (method == "post"){
    var form, key, hiddenField;
    form = document.createElement("form");
    form.setAttribute("method", method);
    form.setAttribute("action", path);
    for (key in params) {
      if (params.hasOwnProperty(key)) {
        hiddenField = document.createElement("input");
        hiddenField.setAttribute("type", "hidden");
        hiddenField.setAttribute("name", key);
        hiddenField.setAttribute("value", params[key]);
        form.appendChild(hiddenField);
      }
    }
    document.body.appendChild(form);
    form.submit();
  } 
  if (method == "get"){
    window.location.href = path;
  }
  if (method == "new"){
    window.open(path);
  }
}
function setCookie(c_name,value){
  var exdate=new Date();
  exdate.setDate(exdate.getDate() + 365);
  var c_value=escape(value) + "; expires="+exdate.toUTCString();
  document.cookie=c_name + "=" + c_value;
}
function getCookie(c_name){
  var c_value = document.cookie;
  c_start = c_name+"=";
  c_end = ";";
  return unescape(between(c_value,c_start,c_end));
}
/* UI */
var wh = new Array();
function windowSize(){
  wh.w = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
  wh.h = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
};
addEvent(window,"load",windowSize);
addEvent(window,"resize",windowSize);
function focus(id) { setTimeout(function() { if (ele(id) !== null) { ele(id).focus(); } }, 10); }
function setCursorByID(id, cursorStyle) { if (ele(id) !== null) { ele(id).style.cursor = cursorStyle; } }
function hide(id) { if (ele(id) !== null) { ele(id).style.display = 'none'; } }
function show(id) { if (ele(id) !== null) { ele(id).style.display = 'inline'; } }
function asyncimg(id,url){ addEvent(window,'load',function(e) { ele(id).src=url; }); }
function swap(id1, id2) { var x, y; x = ele(id1).style.display; y = ele(id2).style.display; ele(id1).style.display = y; ele(id2).style.display = x; }
function collapse(field) { field.value = field.value.replace(/\s/g, ""); }
function getCaret(field) {
  var iCaretPos, oSel;
  iCaretPos = 0; // Initialize
  if (document.selection) {                             // IE Support - Detect IE-only function.
    field.focus();                                      // Set focus on the element   
    oSel = document.selection.createRange();            // To get cursor position, get empty selection range
    oSel.moveStart('character', -field.value.length);   // Move selection start to 0 position
    iCaretPos = oSel.text.length;                       // The caret position is selection length
  } else if (field.selectionStart || field.selectionStart === '0') { // Firefox, WebKit, Standards-Compliant support
    iCaretPos = field.selectionStart;
  }
  return iCaretPos;// Return results
}
function setCaret(field, pos) { // Set the selection range = exactly no characters, this position.
  field.selectionStart = pos;
  field.selectionEnd = pos;
}
function ucase(field) {
  /* This one was an interesting request from a friend.
     Uppercase the value of a field onKeypress, but retain your position within the textfield.
     Browser inconsistencies galore led to getCaret/setCaret above.
  */
  var caret;
  caret = getCaret(field);           // Store our location in textfield.
  field.value = field.value.toUpperCase(); // Set field value to uppercase of itself.
  setCaret(field, caret);                // Restore location in textfield.
}
function SuperAlert(message) {
  /* 
     Generates a modal alert box in all browsers, like the Mozilla FireFox native one.
     Usage: SuperAlert(message);
     All ID's and Z-indexes are done as variables so that if your page uses these, they can be altered easily.
     Message may contain html, so if you want to add form elements, just include them in your message, hook up your actions.
  */
  var PageBodyID, SuperAlertID, SuperAlertNode, SuperAlertZ, SuperAlertShadeID, SuperAlertShadeNode, SuperAlertShadeZ, SuperAlertInnerID, SuperAlertInnerNode, SuperAlertCloseID;
  PageBodyID = tag("body");
  SuperAlertID = "SuperAlertBox";
  SuperAlertZ = 32769;
  SuperAlertShadeID = "SuperAlertShade";
  SuperAlertShadeZ = 32768;
  SuperAlertInnerID = "SuperAlertInner";
  SuperAlertCloseID = "SuperAlertClose";

  // Build background modality div.
  SuperAlertShadeNode = document.createElement('div');
  SuperAlertShadeNode.id = SuperAlertShadeID;
  PageBodyID.appendChild(SuperAlertShadeNode);
  ele(SuperAlertShadeID).style.opacity = '.5';
  ele(SuperAlertShadeID).style.position = 'absolute';
  ele(SuperAlertShadeID).style.top = '0px';
  ele(SuperAlertShadeID).style.left = '0px';
  ele(SuperAlertShadeID).style.backgroundColor = '#000000';
  ele(SuperAlertShadeID).style.filter = 'alpha(opacity=50)';
  ele(SuperAlertShadeID).style.height = (PageBodyID.offsetHeight < wh.h) ? wh.h + 'px' : PageBodyID.offsetHeight + 20 + 'px';
  ele(SuperAlertShadeID).style.display = 'block';
  ele(SuperAlertShadeID).style.zIndex = SuperAlertShadeZ;
  ele(SuperAlertShadeID).style.width = '100%';
  ele(SuperAlertShadeID).style.height = (PageBodyID.offsetHeight < wh.h) ? wh.h + 'px' : PageBodyID.offsetHeight + 20 + 'px';

  // Build Alert Outer div.
  SuperAlertNode = document.createElement('div');
  SuperAlertNode.id = SuperAlertID;
  PageBodyID.appendChild(SuperAlertNode);
  ele(SuperAlertID).style.border = '1px solid black';
  ele(SuperAlertID).style.position = 'absolute';
  ele(SuperAlertID).style.backgroundColor = '#DDDDDD';
  ele(SuperAlertID).style.width = '320px';
  ele(SuperAlertID).style.zIndex = SuperAlertZ;
  ele(SuperAlertID).style.display = 'block';
  ele(SuperAlertID).style.top = parseInt((document.documentElement.scrollTop + (wh.h / 3)), null) + 'px';
  ele(SuperAlertID).style.left = parseInt(((PageBodyID.offsetWidth - 315) / 2), null) + 'px';

  // Build Alert Inner div.
  SuperAlertInnerNode = document.createElement('div');
  SuperAlertInnerNode.id = SuperAlertInnerID;
  ele(SuperAlertID).appendChild(SuperAlertInnerNode);
  ele(SuperAlertInnerID).style.padding = '10px';
  ele(SuperAlertInnerID).style.textAlign = 'center';
  SuperAlertInnerNode.innerHTML = '<p>' + message + '</p><input type="button" id="' + SuperAlertCloseID + '" value="OK" style="width:80px;">';

  // Add event to close the dialog.
  addEvent(ele(SuperAlertCloseID), "click",  function() {
    ele(SuperAlertID).innerHTML = '';
    ele(SuperAlertID).parentNode.removeChild(ele(SuperAlertID));
    ele(SuperAlertShadeID).parentNode.removeChild(ele(SuperAlertShadeID));
  });
}
function tog_draw(id) { if (ele(id) !== null) { var onimg, offimg; onimg = "/resource/images/Toggle-On.png"; offimg = "/resource/images/Toggle-Off.png"; if (val(id) === "1") { ele(id + "_img").src = onimg; } else { ele(id + "_img").src = offimg; } } }
function tog(id) { if (ele(id) !== null) { if (val(id) === "1") { valset(id, "0"); } else { valset(id, "1"); } tog_draw(id); } }

addEvent(window,"load",function(e) {
   addEvent(ele("logo"), "mouseover",  function(e) {
     show("menu"); 
   });
   addEvent(ele("logo"), "click",  function(e) {
     show("menu"); 
   });
   addEvent(ele("content"), "mouseover", function(e) {
     $(".menu").not(".menu_lock_menu").hide();
   });
   addEvent(ele("content"), "click", function(e) {
     $(".menu").not(".menu_lock_menu").hide();
     
   });
});

addEvent(window,"load",function(e) {
  addEvent(ele("menu_home"), "click",  function(e) {
    go("/home",'','get');
  });    
  addEvent(ele("menu_forum"), "click",  function(e) {
    go("/forum",'','get');
  });    
  addEvent(ele("menu_characters"), "click",  function(e) {
    go("/characters",'','get');
  });    
  addEvent(ele("menu_comics"), "click",  function(e) {
    go("/comics",'','get');
  });    
  addEvent(ele("menu_gaming"), "click",  function(e) {
    go("/gaming",'','get');
  });    
  addEvent(ele("menu_shows"), "click",  function(e) {
    go("/shows",'','get');
  });    
  addEvent(ele("menu_music"), "click",  function(e) {
    go("/music","","get");
  });    
  addEvent(ele("menu_fancontent"), "click",  function(e) {
    go("/fancontent","","get");
  });    
  addEvent(ele("menu_links"), "click",  function(e) {
    go("/links","","get");
  });    
  addEvent(ele("menu_users"), "click",  function(e) {
    go("/users","","get");
  });    
  addEvent(ele("menu_sorting"), "click",  function(e) {
    go("/sorting","","get");
  });    
  addEvent(ele("menu_uploads"), "click",  function(e) {
    go("/uploads","","get");
  });
  addEvent(ele("menu_help","","get"), "click",  function(e) {
    go("/forum/6","","get");
  });
});

// Wrapper prevents section code from being called in other sections.
$( document ).ready(function(){
  $('.section').each(function(){
    if ($(this).text() == 'comics'){
      function issue_chooser(){
        var iss = parseInt(issue, 10);
        var icount = parseInt(issues, 10);
        var navi = "";
        navi += comic_name;
        navi += "&nbsp;<select class='issue_choose'>";
        for (i=1;i<=icount;i++){
          if(i == iss){
            navi += "<option value="+i+" selected='selected'>"+issuenames[i-1]["name"]+"</option>";
          } else {
            navi += "<option value="+i+">"+issuenames[i-1]["name"]+"</option>";
          }
        }
        navi += "</select>";
        $('.issue_current').each(function(){
          $(this).html(navi);        
        });
        $('.issue_choose').change(function() {
          var iss = $('.issue_choose').val();
          go("/comics/"+comic+"/"+iss,"","get");
        });
        $('.issue_prev').click(function() {
          var iss = $('.issue_choose').val();
          iss = parseInt(iss, 10) - 1;
          if (iss > 0){
            go("/comics/"+comic+"/"+iss,"","get");
          }
        });
        $('.issue_next').click(function() {
          var iss = $('.issue_choose').val();
          iss = parseInt(iss, 10) + 1;
          if (iss < issues){
            go("/comics/"+comic+"/"+iss,"","get");
          }
        });
      }
      $('.up_level').click(function() {
	      go("/comics/","","get");
      });
      issue_chooser();
    };
  });
});

// 'Contact Me' link
$( document ).ready(function(){
  $('#contact_miles').click(function() {
    SuperAlert("Miles Prower may be reached via miles.t.prower at gmail dot com, gtalk.");
  });  
  setCursorByID("contact_miles","pointer");
});

// Wrapper prevents section code from being called in other sections.
$( document ).ready(function(){
  $('.section').each(function(){
    if ($(this).text() == 'forum'){
      function page_chooser(){
        var pag = parseInt(page, 10);
        var pcount = parseInt(page_count, 10);
        var navi = "";
        navi += topic_name;
        navi += " (Page ";
        navi += "<select class='page_choose'>";
        for (i=1;i<=pcount;i++){
          if(i == pag){
            navi += "<option value="+i+" selected='selected'>"+i+"</option>";
          } else {
            navi += "<option value="+i+">"+i+"</option>";
          }
        }
        navi += "</select>";
        navi += " of "+(pcount)+")";
        $('.page_current').each(function(){
          $(this).html(navi);        
        });
        $('.page_choose').change(function() {
          var pag = $('.page_choose').val();
          go("/forum/"+topic+"/"+pag,"","get");
        });
        $('.page_prev').click(function() {
          var pag = $('.page_choose').val();
          pag = parseInt(pag, 10) - 1;
          if (pag > 0){
            go("/forum/"+topic+"/"+pag,"","get");
          }
        });
        $('.page_next').click(function() {
          var pag = $('.page_choose').val();
          pag = parseInt(pag, 10) + 1;
          if (pag < page_count){
            go("/forum/"+topic+"/"+pag,"","get");
          }
        });
        $('.up_level').click(function() {
            go("/forum/","","get");
        });
      }
      page_chooser();
window.forum_post_edit = function (ftid,fpid){
  var id = "forum_post_"+fpid+"_outer";
  var tboxid = "forum_post_"+fpid+"_box";
  var textid = "forum_post_"+fpid+"_inner";
  var updateid = "forum_post_"+fpid+"_update";
  var deleteid = "forum_post_"+fpid+"_delete";
  var cancelid = "forum_post_"+fpid+"_cancel";
  var old_content = $("#"+id).html();
  var text = $("#"+textid).html();
  $("#"+id).empty();
  var tex = "<textarea id='"+tboxid+"' rows='10' cols='30'></textarea>";
  tex = tex + "<br/>";
  tex = tex + "<input type='button' id='"+cancelid+"' class='forum_post_send' value='Cancel'>";
  tex = tex + "<input type='button' id='"+updateid+"' class='forum_post_send' value='Update'>";
  tex = tex + "<input type='button' id='"+deleteid+"' class='forum_post_delete' value='Delete'>";
  $(tex).appendTo("#"+id);
  $("#"+tboxid).html(text);
  refreshmceid(tboxid); 
  addEvent(ele(cancelid), "click", function() {
  	$("#"+id).html(old_content);
  });
  addEvent(ele(updateid), "click", function() {
     var content = tinyMCE.activeEditor.getContent();
     content = content.replace(/\r\n/ig,'');
     content = content.replace(/\r/ig,'');
     content = content.replace(/\n/ig,'');
     if(content !== ""){
       if (val(updateid) !== "Updating..."){
         valset(updateid,"Updating...");
          params = { 'a':'forum_post_update', 'f':fpid, 'v':'post', 'd':content };
          post = $.post("/api/", params);
          post.done(function( data ) {
          var response;
          console.log(data);
          response = $.parseJSON(data);
          console.log(response);
          if (response.status == 1){ // API responded with an OK.
            SuperAlert(response.result);
            go("/forum/"+ftid,"");
          } else {
            SuperAlert(response.error);
            return 0;
          }
        });
       } else {
         SuperAlert("Hold on, your post is being processed...");
       }
     } else {
       SuperAlert("You must enter something to post.");
     }
   });
   addEvent(ele(deleteid), "click", function() {
     params = { 'a':'forum_post_update', 'f':fpid, 'v':'deleted', 'd':'1' };
     post = $.post("/api/", params);
     post.done(function( data ) {
       var response;
       console.log(data);
       response = $.parseJSON(data);
       console.log(response);
       if (response.status == 1){ // API responded with an OK.
         SuperAlert(response.result);
         go("/forum/"+ftid,"","get");
       } else {
         SuperAlert(response.error);
         return 0;
        }
      });
    });
      
}
  addEvent(ele("forum_post_send"), "click", function() {
     var content = tinyMCE.activeEditor.getContent();
     content = content.replace(/\r\n/ig,'');
     content = content.replace(/\r/ig,'');
     content = content.replace(/\n/ig,'');
     if(content !== ""){
       if (val("forum_post_send") !== "Posting..."){
         valset("forum_post_send","Posting...");
          params = { 'a':'forum_post_add', 'topic':ftid, 'post':content };
          post = $.post("/api/", params);
          post.done(function( data ) {
          var response;
          console.log(data);
          response = $.parseJSON(data);
          console.log(response);
          if (response.status == 1){ // API responded with an OK.
            SuperAlert(response.result);
            go("/forum/"+ftid,"");
          } else {
            SuperAlert(response.error);
            return 0;
          }
        });
       } else {
         SuperAlert("Hold on, your post is being processed...");
       }
     } else {
       SuperAlert("You must enter something to post.");
     }
   });
    };
  });
});

addEvent(window,"load",function(e) {
   addEvent(ele("help"), "click",  function(e) {
     go("/forum/8","","get");
   });
});

// Wrapper prevents section code from being called in other sections.
$( document ).ready(function(){
  $('.section').each(function(){
    if ($(this).text() == 'links'){


function category_chooser(){
  var cat = parseInt(category, 10);
  var catcount = parseInt(categories, 10);
  var navi = "";    
  navi += "<select class='category_choose'>";
  for (i=1;i<=catcount;i++){
		if(i == cat){
			navi += "<option value="+i+" selected='selected'>"+categorynames[i-1]+"</option>";
    } else {
      navi += "<option value="+i+">"+categorynames[i-1]+"</option>";
    }
  }
  navi += "</select>";
  $('.category_current').html(navi);        
  $('.category_choose').change(function() {
		var cat = $('.category_choose').val();
    go("/links/"+cat,"","get");
  });
  $('.category_prev').click(function() {
		var cat = $('.category_choose').val();
    cat = parseInt(cat, 10) - 1;
    if (cat > 0){
	    go("/links/"+cat,"","get");
    }
  });
  $('.category_next').click(function() {
		var cat = $('.category_choose').val();
    cat = parseInt(cat, 10) + 1;
    if (cat < categorys){
  	  go("/links/"+cat,"","get");
    }
  });
}
function submitter(){
	$('#submit').click(function() {
		var content = tinyMCE.activeEditor.getContent();
		content = content.replace(/\r\n/ig,'');
	  content = content.replace(/\r/ig,'');
	  content = content.replace(/\n/ig,'');
	  if(content !== ""){
			if (val("submit") !== "Submitting..."){
			  oldval = val("submit")
		    valset("submit","Submitting...");
  	    params = { 'a':'link_add', 'name': $("#name").val(), 'url': $("#url").val(), 'description':content, 'adult': $("#adult").is(":checked") };
  	    console.log(params);
	      post = $.post("/api/", params);
	      post.done(function( data ) {
		      var response;
		      console.log(data);
		      response = $.parseJSON(data);
		      console.log(response);
		      if (response.status == 1){ // API responded with an OK.
		        SuperAlert(response.result);
			      go("/links/","");
				  } else {
			  	  SuperAlert(response.error);
				    valset("submit",oldval);
			      return 0;
			    }
			  });
		  } else {
			  SuperAlert("Hold on, your link is being processed...");
  	  }
		} else {
  	  SuperAlert("You must enter a description for your link.");
	  }
  });
}

category_chooser();
submitter();

    };
  });
});


function dologin(){
  params = { 'a':'login', 'u':$('#uname').val(), 'p':$('#pword').val() };
  post = $.post("/api/", params);
  post.done(function( data ) {
    var response;
    response = $.parseJSON(data);
    console.log(response);
    if (response.status == 1){ // API responded with an OK.
      //SuperAlert(response.result);
      window.location = "/";
    } else {
      SuperAlert(response.error);
      return 0;
    }
  });
}; 
   
addEvent(window,"load",function(e) {
  addEvent(ele("logout"), "click", function(e) {
    params = { 'a':'logout' };
    post = $.post("/api/", params);
    post.done(function( data ) {
      var response;
      response = $.parseJSON(data);
      console.log(response);
      if (response.status == 1){ // API responded with an OK.
        //SuperAlert(response.result);
        window.location = "/";
      } else {
        SuperAlert(response.error);
        return 0;
      }
    });
   });
   addEvent(ele("login"), "click", function() {
    dologin();
   });
   addEvent(ele("uname"), "keypress", function(e) {
    if (e.keyCode == 13) {
      dologin();
      return false;
    }
   });
   addEvent(ele("pword"), "keypress", function(e) {
    if (e.keyCode == 13) {
      dologin();
      return false;
    }
   });
   addEvent(ele("register"), "click", function(e) {
     window.location = "/register";
   });    
});

// Wrapper prevents section code from being called in other sections.
$( document ).ready(function(){
  $('.section').each(function(){
    if ($(this).text() == 'register'){
      addEvent(ele("registerdo"), "click", function(e) {
        if (isblank(val("username"))){
          SuperAlert("Username may not be blank.");
          return false;
        }
        if (!isalpnum(val("username"))){
          SuperAlert("Username may only contain a-z,A-Z,0-9, Space, Underscore");
        }
        if (isblank(val("password"))){
          SuperAlert("Password may not be blank.");
          return false;
        }
        if (isblank(valnam("recaptcha_response_field"))){
          SuperAlert("ReCaptcha must be filled out.");
          return false;
        }
        /* If we reach here, everything's ok. */
        params = { 'a':'user_register', 'u':val("username"), 'p':val("password"), 'rc':valnam("recaptcha_challenge_field"), 'rr':valnam("recaptcha_response_field") };
        console.log(params);
        post = $.post("/api/", params);
        post.done(function( data ) {
          var response;
          response = $.parseJSON(data);
          console.log(response);
          if (response.status == 1){ // API responded with an OK.
            SuperAlert(response.result);
            go('/user/'+encodeURIComponent(val("username").toLowerCase()),'','get');
          } else {
            SuperAlert(response.error);
            Recaptcha.reload();
            return 0;
          }
        });
      });
    }
  });  
});
// Wrapper prevents section code from being called in other sections.
$( document ).ready(function(){
  $('.section').each(function(){
    if ($(this).text() == 'shows'){
      function episode_chooser(){
        var iss = parseInt(episode, 10);
        var icount = parseInt(episodes, 10);
        var navi = "";
        navi += show_name;
        navi += "&nbsp;<select class='episode_choose'>";
        for (i=1;i<=icount;i++){
          if(i == iss){
            navi += "<option value="+i+" selected='selected'>"+episodenames[i-1]["name"]+"</option>";
          } else {
            navi += "<option value="+i+">"+episodenames[i-1]["name"]+"</option>";
          }
        }
        navi += "</select>";
        $('.episode_current').each(function(){
          $(this).html(navi);        
        });
        $('.episode_choose').change(function() {
          var iss = $('.episode_choose').val();
          go("/shows/"+show+"/"+iss,"","get");
        });
        $('.episode_prev').click(function() {
          var iss = $('.episode_choose').val();
          iss = parseInt(iss, 10) - 1;
          if (iss > 0){
            go("/shows/"+show+"/"+iss,"","get");
          }
        });
        $('.episode_next').click(function() {
          var iss = $('.episode_choose').val();
          iss = parseInt(iss, 10) + 1;
          if (iss < episodes){
            go("/shows/"+show+"/"+iss,"","get");
          }
        });
      }
      $('.up_level').click(function() {
	      go("/shows/","","get");
      });
      episode_chooser();
    };
  });
});
function show_choose(cid){
  go("/shows/"+cid,"","get");
}
function show_choose_episode(cid,ciid){
  go("/shows/"+cid+"/"+ciid,"","get");
}
addEvent(window,"load",function(e) {
  addEvent(ele("show_change"), "click",  function(e) {
    go(document.URL,{action:"section",section:"shows"});
  });
});
addEvent(window,"load",function(e) {
  addEvent(ele("show_change_episode"), "click",  function(e) {
    go(document.URL,{action:"show_choose_episode",show_episode:''});
  });
});

// Wrapper prevents section code from being called in other sections.
$( document ).ready(function(){
  $('.section').each(function(){
    if ($(this).text() == 'uploads'){
    
addEvent(window,"load",function(e) {   
   /* Upload */
   addEvent(ele("upload"), "click", function() {
     var content = tinyMCE.activeEditor.getContent()
     content = content.replace(/\r\n/ig,'');
     content = content.replace(/\r/ig,'');
     content = content.replace(/\n/ig,'');
     valset("upload_description",content);
     if (content){
       if (!val("upload_folder") == ''){
         ele("upload_file").click();        
       } else {
         SuperAlert("You must choose a folder first.");
       }
     } else {
       SuperAlert("You must enter a description first.");
     }
   });
   addEvent(ele("upload_file"), "change", function() {    
/*     var value;
     value = val("upload_file").split(/(\\|\/)/g).pop();
     value = value.replace(".","");
     value = value.replace("-","");
     value = value.replace("_","");
     value = value.replace("[","");
     value = value.replace("]","");
     value = value.replace("(","");
     value = value.replace(")","");
     if (!isalpnum(value)){
       SuperAlert("You must select a filename containing only a-z, A-Z, 0-9, _, -, ., (, ), [, ], space.");
     } else {
     */
       // Everyone else just submits. IE, IOS, show the button.
       if(ie() || ios()) {
         hide("upload");
         show("upload_submit");
       } else {             
         ele("upload_submit").click();
       } 
   
   /*  } */
   });
   show("upload");
});

		}
  });
});

// Wrapper prevents section code from being called in other sections.
$( document ).ready(function(){
  $('.section').each(function(){
    if ($(this).text() == 'user'){
    
addEvent(window,"load",function(e) {
   /* Portrait */
   addEvent(ele("user_portrait_delete"), "click", function() {
		params = { 'a':'user_portrait_delete' };
		  post = $.post("/api/", params);
		  post.done(function( data ) {
    		var response;
		    response = $.parseJSON(data);
		    console.log(response);
    		if (response.status == 1){ // API responded with an OK.
		      SuperAlert(response.result);
    		  go('/user/'+user,'','get');
		    } else {
		      SuperAlert(response.error);
		      return 0;
		    }
  		});
   });
   addEvent(ele("user_portrait_upload"), "click", function() {
     ele("user_portrait_file").click();
   });
   addEvent(ele("user_portrait_file"), "change", function() {     
     // Everyone else just submits. IE, show the button.
     if(ie()) {
       show("user_portrait_submit");
     } else {
       ele("user_portrait_submit").click();
     } 
   });
   show("user_portrait_upload");
   show("user_portrait_delete");
   
   /* Description */
   addEvent(ele("user_description_save"), "click", function() {
     var content = tinyMCE.activeEditor.getContent()
     content = content.replace(/\r\n/ig,'');
     content = content.replace(/\r/ig,'');
     content = content.replace(/\n/ig,'');
     go("/user/"+user,{action:"user_update",tag:"description",value:content});
   });
   
   /* Adult */
   addEvent(ele("user_adult_img"), "click", function() {
     tog("user_adult"); 
     
     params = { 'a':'user_value_update', 'v':'adult', 'd':$("#user_adult").val() };
     console.log(params);
          post = $.post("/api/", params);
          post.done(function( data ) {
          var response;
          console.log(data);
          response = $.parseJSON(data);
          console.log(response);
          if (response.status == 1){ // API responded with an OK.
            /* SuperAlert(response.result); If ok, do we really need to know? */
            go('/user/'+user,"","get");
          } else {
            SuperAlert(response.error);
            return 0;
          }
   });
   });
	tog_draw("user_adult");

   /* Lock Menu */
   addEvent(ele("user_lock_menu_img"), "click", function() {
     tog("user_lock_menu"); 
     params = { 'a':'user_value_update', 'v':'lock_menu', 'd':$("#user_lock_menu").val() };
     console.log(params);
          post = $.post("/api/", params);
          post.done(function( data ) {
          var response;
          console.log(data);
          response = $.parseJSON(data);
          console.log(response);
          if (response.status == 1){ // API responded with an OK.
            /* SuperAlert(response.result); If ok, do we really need to know? */
            go('/user/'+user,"","get");
          } else {
            SuperAlert(response.error);
            return 0;
          }
   });
   });

   tog_draw("user_lock_menu");
   
   /* Lock Footer */
   addEvent(ele("user_lock_footer_img"), "click", function() {   
     tog("user_lock_footer"); 
          params = { 'a':'user_value_update', 'v':'lock_footer', 'd':$("#user_lock_footer").val() };
     console.log(params);
          post = $.post("/api/", params);
          post.done(function( data ) {
          var response;
          console.log(data);
          response = $.parseJSON(data);
          console.log(response);
          if (response.status == 1){ // API responded with an OK.
            /* SuperAlert(response.result); If ok, do we really need to know? */
            go('/user/'+user,"","get");
          } else {
            SuperAlert(response.error);
            return 0;
          }
   });
   });
   tog_draw("user_lock_footer");
   
   /* Lock Login */
   addEvent(ele("user_lock_login_img"), "click", function() {
     tog("user_lock_login"); 
          params = { 'a':'user_value_update', 'v':'lock_login', 'd':$("#user_lock_login").val() };
     console.log(params);
          post = $.post("/api/", params);
          post.done(function( data ) {
          var response;
          console.log(data);
          response = $.parseJSON(data);
          console.log(response);
          if (response.status == 1){ // API responded with an OK.
            /* SuperAlert(response.result); If ok, do we really need to know? */
            go('/user/'+user,"","get");
          } else {
            SuperAlert(response.error);
            return 0;
          }
   });
   });
     
   tog_draw("user_lock_login");
   
});
		}
  });
});

// Wrapper prevents section code from being called in other sections.
$( document ).ready(function(){
  $('.section').each(function(){
    if ($(this).text() == 'users'){
      function alpha_chooser(){
        var alp = alpha;
        var alpcount = parseInt(alphas, 10);
        var navi = "("+users+") Users Starting with ";
        var current = 0;
        navi += "<select class='alpha_choose'>";
        for (i=1;i<=alpcount;i++){
          if(alphalist[i-1] == alp){
            current = i-1;
          }
        }
        
        for (i=1;i<=alpcount;i++){
          if(alphalist[i-1] == alp){
            navi += "<option value="+i+" selected='selected'>"+alphalist[i-1]+"</option>";
          } else {
            navi += "<option value="+i+">"+alphalist[i-1]+"</option>";
          }
        }
        navi += "</select>";
        navi += " sorted by last visit.";
        if (boring == "1"){
          navi += "&nbsp;<a href = '/users/"+alphalist[current]+"/0'>Exclude boring people. (no desc).</a>";
        } else {
          navi += "&nbsp;<a href = '/users/"+alphalist[current]+"/1'>Include boring people. (no desc).</a>";
        }
        
    
        
        $('.alpha_current').each(function(){
          $(this).html(navi);        
        });
        $('.alpha_choose').change(function() {
          var alp = $('.alpha_choose').val();
          window.location = "/users/"+alphalist[alp-1]+"/"+boring;
        });
        $('.alpha_prev').click(function() {
          var alp = $('.alpha_choose').val();
          alp = parseInt(alp, 10) - 1;
          if (alp > 0){
            window.location = "/users/"+alphalist[alp-1]+"/"+boring;
            
          }
        });
        $('.alpha_next').click(function() {
          var alp = $('.alpha_choose').val();
          alp = parseInt(alp, 10) + 1;
          if (alp < alphas){
            window.location = "/users/"+alphalist[alp-1]+"/"+boring;
          }
        });       
      }
      alpha_chooser();
    }
  });  
});
