// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults
function match_email(value1, value2, invalid_id){
  //if one isn't filled out yet, I don't want to say they don't match...
  if (value1.length == 0 || value2.length == 0) {
    $(invalid_id).hide();
  }else{
    if (value1 == value2) {
      $(invalid_id).hide();
    }
    else {
      $(invalid_id).show();
    }
  }
}
function email_confirm(element,invalid_id){
  var value = element.value;
  var valid_email = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,6})+$/;
  if (valid_email.test(element.value)) {
    $(invalid_id).hide();
  }else{
    $(invalid_id).show();
    element.focus();
  }
}
function show_inner_form(id)
{
	var obj_string = 'reject_inner_form_' + id;
	if ($(obj_string).style.display == 'none')
	{
		new Effect.Appear($(obj_string));
	}
	
}

function counter(box,counter,max,words){
	if(words){
		num = $(box).value.split(" ").length
	}else{
		num = $(box).value.length
	}
	
	if(num > max){
		$(counter).style.color = "red";
		$(counter).innerHTML = num + " Too many characters: " + max + " max.";
	
	}else{
		$(counter).style.color = "black"
		$(counter).innerHTML = num 
	}
}

function overflow_clip(div){
  maxHeight = $(div.parentNode).getHeight();
	if (div.getHeight() > maxHeight) {
		var inner = div.innerHTML;
		while (div.getHeight() > maxHeight-3) {
			inner = div.innerHTML;
      div.innerHTML = inner.substr(0, inner.length - 20);
    }
    inner = div.innerHTML;
    div.innerHTML += "..."
  }
}

Event.observe(window, 'load', function(){
    $$("div.overflow-clip").each(function(elem){
        overflow_clip(elem);
    });
  }
);


function hide_inner_form(id)
{
	var obj_string = 'reject_inner_form_' + id;
	if (!($(obj_string).style.display == 'none'))
	{
		new Effect.Fade($(obj_string));
	}
}

function checkPassword(password_field)
{
  var other_field = 0;
  var dd_text = $("password_status");
  if (password_field.id == "user_password") {
    other_field = $("user_password_confirmation");
  }
  else {
    other_field = $("user_password");
  }
  // if either is length 0, ignore this for now
  if( other_field.value.length * password_field.value.length == 0 ) {
    return;
  }
  if (password_field.value == other_field.value) {
    dd_text.style.color="green";
    dd_text.innerHTML = "Passwords Match";
  }
  else {
    dd_text.style.color="red";
    dd_text.innerHTML = "Passwords Do Not Match";
  }
}

function popUp(url) {
  if (document.all)
    var xMax = screen.width, yMax = screen.height;
  else if (document.layers)
    var xMax = window.outerWidth, yMax = window.outerHeight;
  else 
    var xMax = 800, yMax= 640; 
  var xOffset = (xMax - 800)/2, yOffset = (yMax - 640)/2; 
  window.open(url,'ff','width=800,height=640, resizable=1, scrollbars=1,screenX='+xOffset+',screenY='+yOffset+',top='+yOffset+',left='+xOffset+''); 
}

function popUpGame(url) {
	var xSize = 855, ySize = 750;
  if (document.all)
    var xMax = screen.width, yMax = screen.height;
  else if (document.layers)
    var xMax = window.outerWidth, yMax = window.outerHeight;
  else 
    var xMax = 800, yMax= 640; 
  var xOffset = (xMax - xSize)/2, yOffset = (yMax - ySize)/2; 
  window.open(url,'ff','width='+xSize+',height='+ySize+', resizable=0, scrollbars=0,screenX='+xOffset+',screenY='+yOffset+',top='+yOffset+',left='+xOffset+''); 
}

function pollpopup(url,width,height){
	width = typeof(width) != 'undefined' ? width : 490;
  height = typeof(height) != 'undefined' ? height : 530;
	mywin = window.open(url,"Poll",'toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=0,resizable=0,width=' + width + ',height=' + height);
}
function emailit(url) {
	mywin = window.open(url,"emailit",'toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=0,resizable=0,width=490,height=530');
}

// adds or removes the class 'show_help' to #body to toggle the display of help information
function toggle_help() {
  elt = document.getElementsByTagName('body')[0];
  if( Element.hasClassName( elt, 'show_help' ) ) {
    Element.removeClassName( elt, 'show_help' )
    $('help_button').innerHTML = 'Show Help';
  } else {
    Element.addClassName( elt, 'show_help' )
    $('help_button').innerHTML = 'Hide Help';
  }
}



// Hide and show the "busy" indicators

Ajax.Responders.register({
  onCreate: function() {
    if($('busy') && Ajax.activeRequestCount>0)
      Effect.Appear('busy',{duration:0.5,queue:'end'});
  },
  onComplete: function() {
    if($('busy') && Ajax.activeRequestCount==0)
      Effect.Fade('busy',{duration:0.5,queue:'end'});
  }
});


// Hide the Parent E-mail form item if the user is over 12

function show_hide_parent_email(year) {
  var country = $("user_country");
	if($('parent_email') && country) {
		var country_val = country[country.selectedIndex].value;
    var birthDate = new Date()
    birthDate.setFullYear($('birthday_year').value,$('birthday_month').value - 1,$('birthday_day').value)
    if (!isNaN(Date.parse($('birthday_month').value - 1 + '/' + $('birthday_day').value + '/' + $('birthday_year').value))) {
      if (calcAge(birthDate.getDate(), birthDate.getMonth() + 1, birthDate.getFullYear()) < 13 && country_val == "US")
          Effect.Appear('parent_email',{duration:0.5,queue:'end'})
      else
          Effect.Fade('parent_email',{duration:0.5,queue:'end'})
    }
  }
}

function makeDaysOfMonth(){
  var i = 0;
  this[i++] = 0; // dummy
  this[i++] = 31;
  this[i++] = 29;
  this[i++] = 31;
  this[i++] = 30;
  this[i++] = 31;
  this[i++] = 30;
  this[i++] = 31;
  this[i++] = 31;
  this[i++] = 30;
  this[i++] = 31;
  this[i++] = 30;
  this[i  ] = 31;
  this.length = i;
}

function calcAge(dd, mm, yy){
  var t, mon, day, year, DD, MM, YY, age;
  var MTB = new makeDaysOfMonth();
  YY   = parseInt(yy);	// year of birth (4 digits)
  MM   = parseInt(mm);	// month of birth (1-12)
  DD   = parseInt(dd);	// date of birth (1-31)
  if (MTB[MM] < DD || DD < 1) return -2;
  t    = new Date();	// get current date
  year = t.getFullYear();	// get year of current
  mon  = t.getMonth() + 1;	// get month of current
  day  = t.getDate();	// get date of current
  if (MM == 2 && DD == 29){	// check leap year
    if (!(((YY % 4 == 0) && (YY % 100 != 0)) || (YY % 400 == 0))){
      alert("The year " +YY+ " ends at 28th of "+MM+" month\nPlease check the date.");
      return -1;
    }
  }
  age = year - YY;
  if ((MM > mon) || (MM == mon && day < DD)) age --;

  return age;
}

/*-- SORTABLES --*/
function toggleSortable(element,tag) {
  if(Element.hasClassName(element,'sorting')) {
    Element.removeClassName(element, 'sorting');
    Sortable.destroy(element);
  } else {
    $(element).addClassName('sorting');
    Sortable.create(element, {
       tag: tag,
       constraint: false,
       handle: 'handle',
       overlap: 'horizontal'
     });
  }
}

function updateOrder(url,element,tag) {
  new Ajax.Request(url, {
     asynchronous: true, 
     evalScripts: true, 
     parameters: Sortable.serialize(element)
   })
 toggleSortable(element,tag);
}

function validate_text(compare_text) {
	if (compare_text.match(/fuck|asshole|shit/i)) {
		return false;
	} else {
		return true;
	}
}

function reset_field_unless_valid_text(field,old_value) {
  if (!validate_text(field.value)) {
    alert("Hey now, no swearing please.");
    field.value = old_value;
  }
}

/* Template Picker */
function pick_color(color)
{
	$('selected').value = color + 1;
	switch(color)		
	{
		case 0:
			$('profile-body').style.backgroundColor="#CC0000";
			$('header').style.backgroundColor="#CC0000";
			$$('.sidebar').each(function(value,index) { 
				value.style.borderColor="#DB7605";
			});
			$$('.sidebarheader').each(function(value,index) { 
				value.style.backgroundColor="#DB7605";
			});			
			break;			
		case 1:
			$('profile-body').style.backgroundColor="#175E75";
			$('header').style.backgroundColor="#175E75";
			$$('.sidebar').each(function(value,index) { 
				value.style.borderColor="#0298E6";
			});
			$$('.sidebarheader').each(function(value,index) { 
				value.style.backgroundColor="#0298E6";
			});			
			break;
		case 2:
			$('profile-body').style.backgroundColor="#33AA00";
			$('header').style.backgroundColor="#33AA00";
			$$('.sidebar').each(function(value,index) { 
				value.style.borderColor="#D7E52F";
			});
			$$('.sidebarheader').each(function(value,index) { 
				value.style.backgroundColor="#D7E52F";
			});
			break;
		case 3:
			$('profile-body').style.backgroundColor="#DDDD00";
			$('header').style.backgroundColor="#DDDD00";
			$$('.sidebar').each(function(value,index) { 
				value.style.borderColor="#CC1111";
			});
			$$('.sidebarheader').each(function(value,index) { 
				value.style.backgroundColor="#CC1111";
			});
			break;
		case 4:
			$('profile-body').style.backgroundColor="#000000";
			$('header').style.backgroundColor="#000000";
			$$('.sidebar').each(function(value,index) { 
				value.style.borderColor="#000000";
			});
			$$('.sidebarheader').each(function(value,index) { 
				value.style.backgroundColor="#000000";
				value.style.color="#ffffff";
			});
			break;
		case 5:
			$('profile-body').style.backgroundColor="#FFFFFF";
			$('header').style.backgroundColor="#FFFFFF";			
			$$('.sidebar').each(function(value,index) { 
				value.style.borderColor="#000000";
			});
			$$('.sidebarheader').each(function(value,index) { 
				value.style.backgroundColor="#000000";
				value.style.color="#ffffff";
			});
			break;
	}
}		

function move_box() {
    var offset = 0; // set offset (likely equal to your css top)
    var element = $('template_picker');

    element.style.top = (document.documentElement.scrollTop + offset) + 'px';
}
//  End -->

var FriendSorter = Class.create({
    perPage: 75,
    initialize: function(element, pager, type, friendCount) {
      this.node = element;
      this.friendCount = friendCount;
      this.type = type;
      this.pager = pager;
    },
    pageShown: function(element) {
      Sortable.create(this.node, { constraint: false, overlap: 'horizontal' });
    },
    showPage: function(element, pagenum) {
      new Ajax.Updater( this.node, location.href+"/../friend_sort_page/?type="+this.type+"&page"+pagenum, {evalScripts: true, onComplete: this.pageShown.bind(this) } );

      this.node.show();
      this.drawPager(pagenum);
    },
    drawPager: function(currentPage) {
      this.pager.empty();
      this.pager.update("Page: ")
      var pages = Math.ceil(this.friendCount / this.perPage);
      
      for(var i = 0; i < pages; i++)  {
        if( i+1 == currentPage) {
          var pageLink = new Element('span').update(i+1);
        }
        else {
          var pageLink = new Element('a').update(i+1);
          pageLink.observe('click', function() { this.showPage(i); }.bind(this));
        }
        this.pager.appendChild(pageLink);
      }
    }
  });

/* For main nav*/
//swap class_start with class_end on object with id
function swap_class(class_end,class_start,id){
  $(id).removeClassName(class_start);
  $(id).addClassName(class_end);
}

var InputWatcher = Class.create({
    dirty: false,
    mark: function() {
      this.dirty = true;
    },
    unmark: function() {
      this.dirty = false;
    },
    initialize: function(elements, warning) {
      this.warning = warning;
      elements.collect(function(element) { element.observe('change', function() { this.mark();}.bind(this) )}.bind(this));
      Event.observe(window, 'beforeunload', function(e) { 
          if(this.dirty) { Event.stop(e); e.returnValue = warning; return this.warning; } 
      }.bind(this));
    }
  })
