var Cookie = {
  set: function( name, value, expires, path, domain, secure ) {
      var today = new Date();
      today.setTime( today.getTime() );
      if ( expires ){
          expires = expires * 1000 * 60 * 60 * 24;
      }
      var expires_date = new Date( today.getTime() + (expires) );

      document.cookie = name + "=" +escape( value ) +
        ( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) +
        ( ( path ) ? ";path=" + path : "" ) +
        ( ( domain ) ? ";domain=" + domain : "" ) +
        ( ( secure ) ? ";secure" : "" );
  },
  get:function( check_name ) {
  	var a_all_cookies = document.cookie.split( ';' );
  	var a_temp_cookie = '';
  	var cookie_name = '';
  	var cookie_value = '';
  	var b_cookie_found = false;

  	for ( i = 0; i < a_all_cookies.length; i++ ) {
  		a_temp_cookie = a_all_cookies[i].split( '=' );
  		cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');
  		if ( cookie_name == check_name )
  		{
  			b_cookie_found = true;
  			if ( a_temp_cookie.length > 1 ){
  				cookie_value = unescape( a_temp_cookie[1].replace(/^\s+|\s+$/g, '') );
  			}
  			return cookie_value;
  			break;
  		}
  		a_temp_cookie = null;
  		cookie_name = '';
  	}
  	
  	if ( !b_cookie_found ) {
  		return null;
  	}
  },
  erase:function( name, path, domain ) {
      if ( Cookie.get( name ) ) {
        document.cookie = name + "=" +
            ( ( path ) ? ";path=" + path : "") +
            ( ( domain ) ? ";domain=" + domain : "" ) +
            ";expires=Thu, 01-Jan-1970 00:00:01 GMT";
      }
  }  
};


function toggle_extended_descriptions( id, dom_obj, popup, form_type ) {
	if (!popup) {
		var extended_dec = $('offer_' + id + '_extended_description');
		extended_dec.toggle();
		(extended_dec.style.display == 'none') ? dom_obj.innerHTML = "Learn more..." : dom_obj.innerHTML = "(X) Close";}
	else {
	  url = '/offer_description/' + id + '?form_type=' + form_type
	  window.open(url, '', 'width=600, height=400, toolbar=no, statusbar=no, resizeable=yes, locationbar=no, menubar=no, scrollbars=yes');
	}
};

function toggle_mini_descriptions( id, dom_obj, popup, form_type ) {
	if (!popup) {
		var extended_dec = $('offer_' + id + '_extended_description');
		extended_dec.toggle();
		(extended_dec.style.display == 'none') ? dom_obj.innerHTML = "more" : dom_obj.innerHTML = "(X) Close";}
	else {
	  url = '/offer_description/' + id + '?form_type=' + form_type
	  window.open(url, '', 'width=600, height=400, toolbar=no, statusbar=no, resizeable=yes, locationbar=no, menubar=no, scrollbars=yes');
	}
};

var	ExitPop = {
	ttl: 1, url: '', width: 500, height: 500, restrict_popup: false,
	load: function() {
		$$('a', 'input[type=submit]').each( function( dom ) {
			if ( dom.innerHTML != "Learn More..." ) {
				dom.observe( 'click', ExitPop.set_restrict_popup_flag );
			}
		});
	},
	unload: function(){
		if (!ExitPop.restrict_popup) {
			new_window_dim = 'height=' + ExitPop.height + ',width=' + ExitPop.width;
			var new_window=window.open( ExitPop.url, 'name', new_window_dim );
			new_window.blur();
		}
	},

	set_restrict_popup_flag: function() { ExitPop.restrict_popup = true; }, 
	
	initialize: function(url, width, height) {
		ExitPop.url = url;
		ExitPop.width = width;
		ExitPop.height = height;
		Event.observe( window, 'unload', ExitPop.unload );
		Event.observe( window, 'load', ExitPop.load );
	}

};

var JsCheck = {
	by_hidden_field: function() {
		hidden_field = new Element('input', {type:'hidden', name:'jscheck', value:1} )
		$$('form').each( function(form){ form.appendChild(hidden_field); });
	},
	initialize: function() {
		Event.observe( window, 'load', JsCheck.by_hidden_field );
	}
};

/*

// obsoleted by simpler non-js system

function switch_transmitter_type(new_type) {
  elements = $('transmitter_types').childElements();
  hidden_types = [];
  
  elements.each(function(e) {
    if (e.identify() == new_type) {
      if(!e.visible()) {
        e.show();
        e.select('input,textarea').each(function(i) {
          i.enable();
          id = i.identify();
          name = i.readAttribute('name');
          i.setAttribute('id', id.substring(0, id.length - 9));
          i.setAttribute('name', name.substring(0, name.length - 9));
          console.log('enabling ' + id);
        });
      }
    }
    else {
      hidden_types.push(e);
    }
  });
  
  // We have to do this part last to avoid problems with the radio buttons temporarily sharing names
  hidden_types.each(function(e) {
    if(e.visible()) {
      e.hide();
      e.select('input,textarea').each(function(i) {
        i.disable();
        id = i.identify();
        name = i.readAttribute('name');
        i.setAttribute('id', id + '_disabled');
        i.setAttribute('name', name + '_disabled');
        console.log('disabling ' + id);
      });
    }
  });
};

function initialize_disabled(transmitter_type) {
  console.log("initialize_disabled called");
  elements = $('transmitter_types').childElements();
  elements.each(function(e) {
    if(e.identify() != transmitter_type) {
      e.select('input,textarea').each(function(i) {      
        i.disable();
        id = i.identify();
        name = i.readAttribute('name');
        i.setAttribute('id', id + '_disabled');
        i.setAttribute('name', name + '_disabled');
        console.log('disabling ' + id);
      });
    }
  });
};
*/

var Verification ={
     hightlightErrors: function( ids ) {
        ids.each(function(id){
            var selector = '#verification_' + id + ' label';
            $$(selector).each(function(label){
                label.addClassName('error');
            })
        });
    },
    remove: function( ids ) {
        ids.each(function(id){
            var verification = $('verification_'+id);
            if ( verification != null )
                verification.remove();
        });
    }
};

// This function is used for the phone_number question type
function auto_switch_fields(element) {
  if (element.value.length == element.maxLength) {  
    main_div = element.parentNode;
    inputs = main_div.getElementsByTagName('input');
    for (var i = 0; i < inputs.length - 1; i++) {
      if (inputs[i] == element) {
        inputs[i+1].focus();
      }
    }
  }
};


var OfferStats = { warned: false };

function check_for_offer() {
  if(!OfferStats.warned) {
    var offer_selected = false;
    offer_selectors = document.getElementsByClassName('offer_checkbox');
    for(i=0; i<offer_selectors.length; i++) {
      if (offer_selectors[i].checked) {
        offer_selected = true;
        break;
      }
    }
    if(offer_selected) {
      return true;
    } else {
      var text_message = Element('div', {'id':'NoOfferSelected'}).update('You have not made any selections. In order to receive school information, you must select one or more schools.');
      $$('form').first().childElements().first().insert( { before:text_message } );
      OfferStats.warned = true;
      window.location.href = "#";
      return false;
    }
  }
};
    
function toggle_incrementals(offer_id) {
  checkbox = $('offers_' + offer_id);
  incrementals = $('incrementals_' + offer_id);
  incrementals.style.clear = "both";

  if(incrementals) {
    if(checkbox.checked) {
      if(incrementals.style.display == "none") {
        Effect.BlindDown(incrementals.id, { duration: 0.7 });
      }
    }
    else {
      Effect.BlindUp(incrementals.id, { duration: 0.7 });
    }
  }
};

function valid_emailaddress() {
  if($('confirm_email_1').value.length > 0 &&
	$('confirm_email_1').value.match(/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*\.(\w{2}|(com|net|org|edu|int|mil|gov|arpa|biz|aero|name|coop|info|pro|museum))$/)
	){
	  return true;
  }
  else
  {
    $('email_1').addClassName('error');
    $('email_2').addClassName('error');
    return false;
  }
};

function emailaddress_match() {
  if($('confirm_email_1').value == $('confirm_email_2').value ) {
    return true;
  }
  else
  {
    $('email_1').addClassName('error');
    $('email_2').addClassName('error');
    return false;
  }
};

function valid_phonenumber() {
  if($('confirm_phone').value.length > 0 &&
    $('confirm_phone').value.match(/^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/)
	){
	  return true;
  }
  else
  {
    $('phone_1').addClassName('error');
    return false;
  }
};

function validate_emailaddress() {
  if($('email_1').hasClassName('error')){
    $('email_1').removeClassName('error');
    $('email_2').removeClassName('error');    
  }
  if (valid_emailaddress() && emailaddress_match()) {
    $('form_emailaddress').value = $('confirm_email_1').value;
		$('formRow_3').up().submit();
  };
};

function validate_phonenumber() {
  if($('phone_1').hasClassName('error')){
    $('phone_1').removeClassName('error');
  }    
  if (valid_phonenumber() ) {
    $('form_homephonenumber').value = $('confirm_phone').value;
		$('formRow_20').up().submit();
  };
};

function validate_emailaddress_and_phonenumber() {
  if($('email_1').hasClassName('error')){
    $('email_1').removeClassName('error');
    $('email_2').removeClassName('error');    
  }
  if($('phone_1').hasClassName('error')){
    $('phone_1').removeClassName('error');
  }
  var phone = valid_phonenumber();
  var email = valid_emailaddress() && emailaddress_match();
  if (phone && email) {
    $('form_emailaddress').value = $('confirm_email_1').value;
    $('form_homephonenumber').value = $('confirm_phone').value;
    $('formRow_20').up().submit();
  };
};

var BuildValidationBox = { email: false, phone: false, button: false };

function build_email_validation_text_boxes(){
  if(!BuildValidationBox.email) {
    $('formRow_3').hide();
    $$('div.buttonContainer').each(function(button){button.remove();});
    var confirm_email_1_text = new Element('input', {'id':'confirm_email_1'});
    var confirm_email_2_text = new Element('input', {'id':'confirm_email_2'});
    if ($('validation_label')) {
      var label = $('validation_label');
      var textbox = $('validation_textbox');
    }
    else
    {
      var label = new Element('span', {'id':'validation_label','style': 'display:inline-block;'});
      var textbox = new Element('span', {'id':'validation_textbox','style': 'display:inline-block;'});
    };
    var confirm_email_1 = new Element('div');
    var confirm_email_2 = new Element('div');
    if($('formRow_emailaddress').down().hasClassName('error')){
      label.insert('<div><label id=\'email_1\' class=\'error\'>Email Address:*</label></div>');
      label.insert('<div><label id=\'email_2\' class=\'error\'>Re-Enter Email Address:*</label></div>');
    }
    else {
      label.insert('<div><label id=\'email_1\'>Email Address:*</label></div>');
      label.insert('<div><label id=\'email_2\'>Re-Enter Email Address:*</label></div>');
    };
    textbox.insert(confirm_email_1.insert(confirm_email_1_text));
    textbox.insert(confirm_email_2.insert(confirm_email_2_text));
    $('formRow_3').up().up().insert(label);
    $('formRow_3').up().up().insert(textbox);
    BuildValidationBox.email = true;
  };  
};

function build_phone_validation_text_box() {
  if(!BuildValidationBox.phone) {
    $('formRow_20').hide();
    $$('div.buttonContainer').each(function(button){button.remove();});
    var confirm_phone_text = new Element('input', {'id':'confirm_phone'});
    if ($('validation_label')) {
      var label = $('validation_label');
      var textbox = $('validation_textbox');
    }
    else
    {
      var label = new Element('span', {'id':'validation_label','style': 'display:inline-block;'});
      var textbox = new Element('span', {'id':'validation_textbox','style': 'display:inline-block;'});
    };
    var confirm_phone = new Element('div');
    if($('formRow_homephonenumber').down().hasClassName('error')){
      label.insert('<div><label id=\'phone_1\' class=\'error\'>Phone Number:*</label></div>');
    }
    else {
      label.insert('<div><label id=\'phone_1\'>Phone Number:*</label></div>');
    };
    textbox.insert(confirm_phone.insert(confirm_phone_text));
    $('formRow_20').up().up().insert(label);
    $('formRow_20').up().up().insert(textbox);    
    BuildValidationBox.phone = true;
  };
};

function build_email_validation_submit_button() {
  if(!BuildValidationBox.button) {
    var submit = new Element('div', {'class':'buttonContainer'});
    var button = new Element('input', {'class':'button', 'type':'submit', 'value':'Continue', 'name':'commit',
    'onClick':'validate_emailaddress();'});
    submit.insert(button);
    $('formRow_3').up().up().insert({bottom: submit});
    BuildValidationBox.button = true;
  }
};

function build_phone_validation_submit_button() {
  if(!BuildValidationBox.button) {
    var submit = new Element('div', {'class':'buttonContainer'});
    var button = new Element('input', {'class':'button', 'type':'submit', 'value':'Continue', 'name':'commit',
    'onClick':'validate_phonenumber();'});
    submit.insert(button);
    $('formRow_20').up().up().insert({bottom: submit});
    BuildValidationBox.button = true;
  }
};

function build_phone_and_email_validation_submit_button() {
  if(!BuildValidationBox.button) {
    var submit = new Element('div', {'class':'buttonContainer'});
    var button = new Element('input', {'class':'button', 'type':'submit', 'value':'Continue', 'name':'commit',
    'onClick':'validate_emailaddress_and_phonenumber();'});
    submit.insert(button);
    $('formRow_20').up().up().insert({bottom: submit});
    BuildValidationBox.button = true;
  }
}