// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults
var HINT_COLOR="silver";
function checkRequiredFields(D,B)
{
   var E=true;
   for(var C=0;C<B.length;C++)
   {
      var A=D[B[C]];
	  if(!A)
	  {
	     continue
	  }
	  if(!A.value||A.style.color==HINT_COLOR)
	  {
	     A.style.backgroundColor="#feb8b8";
		 if(E)
		 {
		    A.focus()
		 }
		 E=false
	  }
	  else
	  {
	     A.style.backgroundColor="white"
	  }
	}
	return E
}
//
// arv!
//
var basic_click_events = function() {
  $$(".disabled").each(function(node) {
    Event.observe(node,"click",function(e) {
      Event.stop(e);
    });
  });
  $$(".popup-link").each(function(node) {
    Event.observe(node,"click",popups);
  });
  $$("[defaultValue]").each(function(node) {
    Event.observe(node,"focus",clear_default);
    Event.observe(node,"blur",replace_default);
    set_default(node);
  });
  $$(".validate").each(function(node) {
	  var valid = new Validation(node, {useTitles : true});
	  Validation.addAllThese([
	  	['validate-password', 'Your password must be more than 6 characters and not be \'password\'.', {
	  		minLength : 7,
	  		notOneOf : ['password','PASSWORD','1234567','0123456'],
	  		notEqualToField : 'name'
	  	}],
	  	['validate-password-confirm', 'Your confirmation password does not match your first password, please try again.', {
	  		equalToField : 'password'
	  	}],
	  	['validate-phone', 'Please check the phone format.', {
	  		pattern : new RegExp('^[2-9]\d{2}-\d{3}-\d{4}$')
	  	}],
	  	['default-value-required', 'This is a required field.', {
	  	  notEqualToAttr : 'defaultValue'
	  	}]
	  ]);
  })
}

/*
  ========================================
  FUNCTIONS

 General: Popuplink */
var popups = function(e) {
  var newUrl = this.getAttribute("href"); 
  var w = 800;
  var h = 600;
  var LeftPosition=(screen.width)?(screen.width-w)/2:100;
  var TopPosition=(screen.height)?(screen.height-h)/2:100;
  var myname = "WinOver";
  var settings = 'width='+w+',height='+h+',top='+TopPosition+',left='+LeftPosition+',scrollbars=yes,location=yes,directories=yes,status=yes,menubar=yes,toolbar=yes,resizable=yes';
  overWin = window.open(newUrl,myname,settings);
  overWin.focus();
  Event.stop(e);
}
/* General: Default-Value */
var clear_default = function() {
  if (this.value == this.attributes['defaultValue'].value) {
    this.value = "";
    this.removeClassName('default-value-field');
    if (this.hasClassName('validation-failed')) {
      this.removeClassName('validation-failed');
    }
  }
}
var replace_default = function() {
  if (this.value.blank()) {
    this.value = this.attributes['defaultValue'].value;
    this.addClassName('default-value-field');
  }
}
var set_default = function(node) {
  if (node.value.blank() || node.value==node.attributes['defaultValue'].value) {
    node.value = node.attributes['defaultValue'].value;
    node.addClassName('default-value-field');
  }
}
var remove_default_class = function() {
  $$("[defaultValue]").each(function(node) {
    if(node.value != node.attributes['defaultValue'].value) {
      node.removeClassName('default-value-field')
    }
  });
}

function populate_date(month, day, year) {
  ge('date_month').value = month;
  ge('date_day').value = day;
  ge('date_year').value = year;
}

function ge(elem) {
  return document.getElementById(elem);
}

/*
 * Ensure Facebook app is initialized and call callback afterward
 *
 */
function ensure_init(callback) {
  if(!window.api_key) {
    window.alert("api_key is not set");
  }

  if(window.is_initialized) {
    callback();
  } else {
    FB_RequireFeatures(["XFBML", "CanvasUtil"], function() {
        FB.FBDebug.logLevel = 4;
        FB.FBDebug.isEnabled = true;
        // xd_receiver.php is a relative path here, because The Run Around
        // could be installed in a subdirectory
        // you should prefer an absolute URL (like "/xd_receiver.php") for more accuracy
        FB.Facebook.init(window.api_key, window.xd_receiver_location);

        window.is_initialized = true;
        callback();
      });
  }
}

/*
 * "Session Ready" handler. This is called when the facebook
 * session becomes ready after the user clicks the "Facebook login" button.
 * In a more complex app, this could be used to do some in-page
 * replacements and avoid a full page refresh. For now, just
 * notify the server the user is logged in, and redirect to home.
 *
 * @param link_to_current_user  if the facebook session should be
 *                              linked to a currently logged in user, or used
 *                              to create a new account anyway
 */
function facebook_button_onclick() {

  ensure_init(function() {
      FB.Facebook.get_sessionState().waitUntilReady(function() {
          var user = FB.Facebook.apiClient.get_session() ?
            FB.Facebook.apiClient.get_session().uid :
            null;

          // probably should give some indication of failure to the user
          if (!user) {
            return;
          }

          // The Facebook Session has been set in the cookies,
          // which will be picked up by the server on the next page load
          // so refresh the page, and let all the account linking be
          // handled on the server side

          // This could be done a myriad of ways; for a page with more content,
          // you could do an ajax call for the account linking, and then
          // just replace content inline without a full page refresh.
          //refresh_page();
          window.location = window.facebook_authenticate_location;
        });
    });
}

/*
 * Do a page refresh after login state changes.
 * This is the easiest but not the only way to pick up changes.
 * If you have a small amount of Facebook-specific content on a large page,
 * then you could change it in Javascript without refresh.
 */
function refresh_page() {
  window.location = '/';
}

function logout() {
  window.location = '/user/logout';
}

/*
 * Show the feed form. This would be typically called in response to the
 * onclick handler of a "Publish" button, or in the onload event after
 * the user submits a form with info that should be published.
 *
 */
function facebook_publish_feed_story(form_bundle_id, template_data) {
  // Load the feed form
  FB.ensureInit(function() {
          FB.Connect.showFeedDialog(form_bundle_id, template_data);
          //FB.Connect.showFeedDialog(form_bundle_id, template_data, null, null, FB.FeedStorySize.shortStory, FB.RequireConnect.promptConnect);

      // hide the "Loading feed story ..." div
      // ge('feed_loading').style.visibility = "hidden";
  });
}
