$(document).ready(function(){
  
  //Facebox
  $('a[rel*=facebox]').facebox();

  $('#donate').click(function () {
    $("#donate_slider").slideToggle("slow");
  });
  
  $('#subscribe').click(function () {
    $("#subscribe_slider").slideToggle("slow");
  });
  
  $('#subscribe-link').click(function () {
    $("#subscriptions").slideDown("fast");
    $('#subscribe-link').addClass("selected");
  });
  
  $('a.credits_link').click(function () {
    $('#overlay').show().fadeTo("fast", 0.5);
    $('#credits').slideDown("fast");
  });
  
  $('a.close_credits').click(function () {
    $('#credits').slideToggle("fast");
    $('#overlay').fadeOut("fast");
  });
  
  // Add hint to text field based on Title
  $('input.hint').hint();
  
  // Landing page cycling slides
  $('#landing_slides').cycle({
      speed: 1000
  });
  
});


function clearMe(obj, text) {
	if(obj.value == text) {
		obj.value = '';
	}
}

function popUp(url, width, height, scrollbars) {
	day = new Date();
	id = day.getTime();
	eval("page" + id + " = window.open(url, '" + id + "', 'toolbar=0,scrollbars=" + scrollbars + ",location=0,statusbar=0,menubar=0,resizable=0,width=" + width + ",height=" + height + ",left=" + ((screen.availWidth-width)/2) + ",top=" + ((screen.availHeight-height)/2) + "');");
}

function validateAmount(amount) {
	if(amount.value.match( /^[0-9]+(\.([0-9]+))?$/)){
		return true;
	} else {
		alert('You must enter a valid donation.');
		amount.focus();
		return false;
	}
}

function validateSubscribe(name, email) {
	if(name.value == "Your Name") {
		alert('Please provide your name');
		name.focus();
		return false;
	} else if(email.value == "Email Address") {
		alert('Please provide your email');
		email.focus();
		return false;
	} else {
		return true;
	}
}

function toggleSubscriptionDropdown(element) {
	new Effect.toggle(element, 'slide',
	     { duration: 1.0,
				 beforeStart: function () {
					if ($('subscribe-link').hasClassName('selected') == false) {
						$('subscribe-link').addClassName('selected');
					}
				 },
				 afterFinish: function () {
					if ($('subscribe-link').hasClassName('selected') == true && $('subscriptions').style.display == 'none') {
						$('subscribe-link').removeClassName('selected');
					}
				 }
	     });
}

function popUp(url, width, height, scrollbars) {
	day = new Date();
	id = day.getTime();
	eval("page" + id + " = window.open(url, '" + id + "', 'toolbar=0,scrollbars=" + scrollbars + ",location=0,statusbar=0,menubar=0,resizable=0,width=" + width + ",height=" + height + ",left=" + ((screen.availWidth-width)/2) + ",top=" + ((screen.availHeight-height)/2) + "');");
}


/* Utility function: fprintf
 * From: http://markos.gaivo.net/blog/?p=63 */
function fprintf(S, L) {
  var nS = "";
  var tS = S.split("%s");
  if (tS.length != L.length+1) throw "Input error";

  for(var i=0; i<L.length; i++)
  nS += tS[i] + L[i];
  return nS + tS[tS.length-1];
}

/* MessageManagers care about the message size.
 */
var MessageManager = Class.create();

MessageManager.prototype = {
  maxCharacters : null,
  maxLines : null,
  maxCharsInLine : null,
  textAreaId : null,
  statsDivId : null,
 
  initialize : function(textAreaId, statsDivId, statsMessage, maxLines, maxCharacters, maxCharsInLine) {
    this.textAreaId = textAreaId;
    this.maxLines = maxLines;
    this.maxCharacters = maxCharacters;
    this.maxCharsInLine = maxCharsInLine;
    this.statsDivId = statsDivId;
    this.statsMessage = statsMessage;
   
    this.textChanged();
  },
 
  textChanged : function() {
    var lineData = this.processTextToLines($(this.textAreaId).value);
    var charactersUsed = $(this.textAreaId).value.length;
               
    if ($(this.textAreaId).value.length > lineData.offset) {
      $(this.textAreaId).value = $(this.textAreaId).value.slice(0, lineData.offset);
      charactersUsed = $(this.textAreaId).value.length;
    }
    if (charactersUsed > this.maxCharacters) {
      $(this.textAreaId).value = $(this.textAreaId).value.slice(0, this.maxCharacters);
      charactersUsed -= 1;
    }

    lineData = this.processTextToLines($(this.textAreaId).value);

    $(this.statsDivId).innerHTML = fprintf(this.statsMessage, [ this.maxCharacters, this.maxLines, charactersUsed, lineData.lines ]);
  },
 
  /**
   * Computes the number of lines a given text has assuming that a line can have
   * a maximum of this.maxCharsInLine.
   *
   * Returns an anonymous object with the properties "lines" and "offset".
   * result.lines contains an integer with the number of lines and "offset"
   * contains the offset of the last character allowed in the string.
   *
   * You can cut away everything after this character.
   */
  processTextToLines : function(text) {
    // cut at newline characters
    lines = text.split("\n");
   
    // cut each line at this.maxCharsInLine
    var offset = 0;
    var split_lines = new Array();
    for (var i = 0; i < lines.length; i++) {
      var match = lines[i].match(new RegExp(".{1," + this.maxCharsInLine +"}", "g"));
      if (match === null) {
        split_lines.push(lines[i]);
       
        offset += lines[i].length;
        if (split_lines.length <= this.maxLines) {
          offset += 1; // +1 for "\n"
                                }
      } else {
        match[match.length - 1] += "\n"
        for (var j = 0; j < match.length; j++) {
          split_lines.push(match[j]);
         
          if (split_lines.length <= this.maxLines) {
            offset += split_lines[split_lines.length - 1].length
          }
        }
      }
    }
    if(split_lines.length >= (this.maxLines + 1) && text.charAt(text.length - 1) == "\n") {
      offset -= 1;
    }
    return { lines : split_lines.length, offset : offset }
  }
}