jQuery.fn.DefaultValue = function(text){
  return this.each(function(){
    if (this.type != 'text' && this.type != 'password' && this.type != 'textarea') 
      return;
    var fld_current = this;
    if (this.value == '') {
      this.value = text;
      $(this).css('color', '#9d9d9d');
    }
    else {
      return;
    }
    $(this).focus(function(){
      if (this.value == text || this.value == '') {
        this.value = '';
        $(this).css('color', 'black');
      }
    });
    $(this).blur(function(){
      if (this.value == text || this.value == '') {
        this.value = text;
        $(this).css('color', '#9d9d9d');
      }
    });
    $(this).parents("form").each(function(){
      $(this).submit(function(){
        if (fld_current.value == text) {
          fld_current.value = '';
        }
      });
    });
  });
}
jQuery.fn.outerHTML = function(s) {
return (s)
? this.before(s).remove()
: jQuery("&lt;p&gt;").append(this.eq(0).clone()).html();
}
// STYLING FILE INPUTS 1.0 | Shaun Inman <http://www.shauninman.com/> | 2007-09-07
if (!window.SI) { var SI = {}; };
SI.Files = {
  htmlClass : 'SI-FILES-STYLIZED',
  fileClass : 'fileField',
  wrapClass : 'fileEntry',
  
  fini : false,
  able : false,
  init : function(){
    this.fini = true;
    
    var ie = 0 //@cc_on + @_jscript_version
    if (window.opera || (ie && ie < 5.5) || !document.getElementsByTagName) { return; } // no support for opacity or the DOM
    this.able = true;
    
    var html = document.getElementsByTagName('html')[0];
    html.className += (html.className != '' ? ' ' : '') + this.htmlClass;
  },
  stylize : function(elem){
    if (!this.fini) { this.init(); };
    if (!this.able) { return; };
    
    elem.parentNode.file = elem;
    elem.parentNode.onmousemove = function(e)
    {
      if (typeof e == 'undefined') e = window.event;
      if (typeof e.pageY == 'undefined' &&  typeof e.clientX == 'number' && document.documentElement)
      {
        e.pageX = e.clientX + document.documentElement.scrollLeft;
        e.pageY = e.clientY + document.documentElement.scrollTop;
      };

      var ox = oy = 0;
      var elem = this;
      if (elem.offsetParent)
      {
        ox = elem.offsetLeft;
        oy = elem.offsetTop;
        while (elem = elem.offsetParent)
        {
          ox += elem.offsetLeft;
          oy += elem.offsetTop;
        };
      };

      var x = e.pageX - ox;
      var y = e.pageY - oy;
      var w = this.file.offsetWidth;
      var h = this.file.offsetHeight;

      this.file.style.top   = y - (h / 2)  + 'px';
      this.file.style.left  = x - (w - 30) + 'px';
    };
  },
  
  stylizeById : function(id)
  {
    this.stylize(document.getElementById(id));
  },
  
  stylizeAll : function()
  {
    if (!this.fini) { this.init(); };
    if (!this.able) { return; };
    
    var inputs = document.getElementsByTagName('input');
    for (var i = 0; i < inputs.length; i++)
    {
      var input = inputs[i];
      if (input.type == 'file' && input.className.indexOf(this.fileClass) != -1 && input.parentNode.className.indexOf(this.wrapClass) != -1)
      {
        this.stylize(input);
      };
    };
  }
};

//Functions
function checkhighlight(){
  var a;
  if (a = /#q([0-9]+)/.exec(document.location.toString())) 
    if (!document.forms.postform.message.value) 
      quote(">>" + a[1] + "\n");
  if (a = /#([0-9]+)/.exec(document.location.toString())) 
    highlight(a[1])
}

function highlight(a, b){
  $("td.highlight").removeClass("highlight");
  var c = $("#reply" + a);
  var d = c.parents("table");
  if (c.length || $('#postform [name=replythread]').val() == a) {
    if (c.length) 
      c.addClass("highlight");
    var e = /^([^#]*)/.exec(document.location.toString());
    document.location = e[1] + "#" + a;
    return false
  }
  return true
}

defaultMsg = "Your message";

function insert(a){
  var b = document.forms.post.msg;
  if (b) {
    if (b.value == defaultMsg) {
      b.value = '';
    }
    if (b.createTextRange && b.caretPos) {
      var c = b.caretPos;
      c.text = c.text.charAt(c.text.length - 1) == " " ? a + " " : a
    }
    else if (b.setSelectionRange) {
        var d = b.selectionStart;
        var e = b.selectionEnd;
        b.value = b.value.substr(0, d) + a + b.value.substr(e);
        b.setSelectionRange(d + a.length, d + a.length)
      }
      else {
        b.value += a + " "
      }
    b.focus();
    return false;
  }
}

function refreshThread(threadId,sole){
  if(sole){query='solereplylist';}else{query = 'boardreplylist';}  
  $.ajax({
    url: '/?t=' + threadId + '&a=' + query,
    dataType: 'html',
    success: function(data){
      $('#t' + threadId +' .uiList .listNub').remove();
      $('#t' + threadId +' .uiList .listReply').remove();
      $('#t' + threadId +' .uiList .ufiItem').remove();
      $('#t' + threadId +' .uiList').prepend(data);
    }
  });
}

function refreshThreads(){
  var soleRegexp = /\?t\=\d+/;
  if(soleRegexp.exec($(location).attr('search'))){sole=true}else{sole=false}
  $('.uiThread.unexpanded').each(function(){
    var threadId = $(this).attr('id').substr(1);
    refreshThread(threadId,sole);
  });
  $('.uiThread.expanded').each(function(){
    var threadId = $(this).attr('id').substr(1);
    refreshThread(threadId,true);
  });
  hookThumbs();
}

function refreshTimestamps(){
  $('.listReply .timeStamp').each(function(){
    var postId = $(this).parents('li.listReply').attr('id').substr(1);
    $.ajax({
      url: '/?t=' + postId + '&a=timeAgo',
      dataType: 'html',
      success: function(data){
        $('#r'+postId+' .timeStamp').html(data);
      }
    });
  });
  $('.uiThread').each(function(){
  	$(this).find('.timeStamp').each(function(){
    var postId = $(this).parents('.uiThread').attr('id').substr(1);
    $.ajax({
      url: '/?t=' + postId + '&a=timeAgo',
      dataType: 'html',
      success: function(data){
        $('#t'+postId+' .timeStamp').html(data);
      }
	  });	
    });
  });
}

function hookThumbs(){
  $('.listReply .smallThumb').each(function(){
    var typeRegexp = new RegExp("([a-zA-Z]{3}$)");
    var imgType = typeRegexp.exec($(this).attr('src'))[1];
    var imgId = $(this).attr('id').substr(1);
    var imgSrc = imgId+"s."+imgType;
    $(this).qtip({
      position: {
        target: $(this).parent().parent(),
        corner: {
          target: 'leftMiddle',
          tooltip: 'rightMiddle'
        }
      },
      content: {
        prerender: true,
        text: "<img src='t/"+imgSrc+"' style='max-width:150px;' />"
      },
      style: {
        'width': 'auto',
        'padding': '0',
        'margin': '0',
        'text-align': 'center',
        tip: {
          corner: 'rightMiddle',
          size: {x: 9, y: 9}
        },
        'background': '#75706E',
        'color': 'white',
        border: {
          width: 1,
          color: 'white'
        }
      }
    });
  });
  $('.uiThread .mediumThumb').each(function(){
    var typeRegexp = new RegExp("([a-zA-Z]{3}$)");
    var imgType = typeRegexp.exec($(this).attr('src'))[1];
    var imgId = $(this).attr('id').substr(1);
    var imgSrc = imgId+"."+imgType;
    $(this).qtip({
      position: {
        target: $(this).parent(),
        corner: {
          target: 'rightTop',
          tooltip: 'leftTop'
        }
      },
      content: {
        prerender: true,
        text: "<img src='i/"+imgSrc+"' style='max-width:405px;' />"
      },
      style: {
        'width': 'auto',
        'padding': '0',
        'margin': '0',
        'text-align': 'center',
        tip: {
          corner: 'leftTop',
          size: {x: 9, y: 9}
        },
        'background': '#75706E',
        'color': 'white',
        border: {
          width: 1,
          color: 'white'
        }
      }
    });
  });
}

//Postload
$(document).ready(function(){
  // get your select element and listen for a change event on it
  $('.leagueSelector, .seasonSelector').change(function() {
    // set the window's location property to the value of the option the user has selected
    window.location = $(this).val();
  });
  SI.Files.stylizeAll();
  submitText = $('.submitButton').html(); 
  $(".messageField").each(function(){
    if (!($(this) == $(".messageField").first())) {
      $(this).bind({
        focusin: function(){
            $(this).attr('rows','2');
            $(this).parent().find('.uiAddReplyButtons').css('display', 'block');
          }
      });
    }
  });
  $(".fileField").bind('change',function(){
//    $(this).parents("form").find(".fileName").html("../"+$(this).val().split('\\').pop());
//    $(this).parents("form").find(".submitButton").html($(this).val().split('\\').pop());
    $(this).parents("form").find(".submitButton").html(submitText+" "+$(this).val().split('\\').pop());
  });
  $(".replyLink").bind('click',function(){
    $(this).parents(".uiThread").find(".messageField").focus();
  });
  $(".seeMoreLink").bind('click',function(){
    $(this).parents('.text_exposed_root').addClass('text_exposed');
  });
  checkhighlight();
  hookThumbs();
});
/**
 * Function : dump()
 * Arguments: The data - array,hash(associative array),object
 *    The level - OPTIONAL
 * Returns  : The textual representation of the array.
 * This function was inspired by the print_r function of PHP.
 * This will accept some data as the argument and return a
 * text that will be a more readable version of the
 * array/hash/object that is given.
 * Docs: http://www.openjs.com/scripts/others/dump_function_php_print_r.php
 */
function dump(arr,level) {
  var dumped_text = "";
  if(!level) level = 0;
  
  //The padding given at the beginning of the line.
  var level_padding = "";
  for(var j=0;j<level+1;j++) level_padding += "    ";
  
  if(typeof(arr) == 'object') { //Array/Hashes/Objects 
    for(var item in arr) {
      var value = arr[item];
      
      if(typeof(value) == 'object') { //If it is an array,
        dumped_text += level_padding + "'" + item + "' ...\n";
        dumped_text += dump(value,level+1);
      } else {
        dumped_text += level_padding + "'" + item + "' => \"" + value + "\"\n";
      }
    }
  } else { //Stings/Chars/Numbers etc.
    dumped_text = "===>"+arr+"<===("+typeof(arr)+")";
  }
  return dumped_text;
}
function strpos (haystack, needle, offset) {
    // Finds position of first occurrence of a string within another  
    // 
    // version: 1109.2015
    // discuss at: http://phpjs.org/functions/strpos
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Onno Marsman    
    // +   bugfixed by: Daniel Esteban
    // +   improved by: Brett Zamir (http://brett-zamir.me)
    // *     example 1: strpos('Kevin van Zonneveld', 'e', 5);
    // *     returns 1: 14
    var i = (haystack + '').indexOf(needle, (offset || 0));
    return i === -1 ? false : i;
}
/**
 * Convert number of seconds into time object
 *
 * @param integer secs Number of seconds to convert
 * @return object
 */
function secondsToTime(secs){
    var hours = Math.floor(secs / (60 * 60));
   
    var divisor_for_minutes = secs % (60 * 60);
    var minutes = Math.floor(divisor_for_minutes / 60);
 
    var divisor_for_seconds = divisor_for_minutes % 60;
    var seconds = Math.ceil(divisor_for_seconds);
   
    var obj = {
        "h": hours,
        "m": minutes,
        "s": seconds
    };
    return obj;
}
