// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :default

var ajax_loading = false;

var headline_count;
var headline_interval;
var next_headline = 0;
var headline = 0;

function prepForAjax(link, link_removed)
{
  ajax_loading = true;
  if(link != null)
  {
    if(link_removed == false || link_removed == null)
    {
      link.style.cursor = "progress";  
    }
    document.body.style.cursor = "progress"; 
  }  
}

function ajaxComplete(link, link_removed)
{
  if(link != null)
  {
    if(link_removed == false || link_removed == null)
    {
      link.style.cursor = "pointer";  
    }     
    document.body.style.cursor = "default";    
  }
  ajax_loading = false;  
}

function trim(stringToTrim) {
	return stringToTrim.replace(/^\s+|\s+$/g,"");
}

function ltrim(stringToTrim) {
	return stringToTrim.replace(/^\s+/,"");
}

function rtrim(stringToTrim) {
	return stringToTrim.replace(/\s+$/,"");
}

function redirect_to_page_setup_wizard(form)
{
  form.action += '?wizard=true'
  form.submit();
}

function stripHTML(oldString) {

  return oldString.replace(/(<([^>]+)>)/ig,""); 
  
}

function escapeHTML(string)
{
  return string.replace(/&/g,'&amp;').replace(/>/g,'&gt;').replace(/</g,'&lt;').replace(/"/g,'&quot;');
}

function limitText(id, limit) 
{
  if (document.getElementById(id).value.length > limit)
  {
    document.getElementById(id).value = document.getElementById(id).value.substring(0, limit);
  }
}

function bioInformationClicked(checkbox)
{
  $("#bio_info_fields").slideToggle(function(){
    if(!checkbox.checked)
    {
      document.edit_patient_info.patient_date_of_birth_2i.value = null;
      document.edit_patient_info.patient_date_of_birth_3i.value = null;
      document.edit_patient_info.patient_date_of_birth_1i.value = null;
      document.edit_patient_info.patient_time_of_birth_1i.value = null;
      document.edit_patient_info.patient_time_of_birth_4i.value = null;
      document.edit_patient_info.patient_time_of_birth_5i.value = null;
      document.edit_patient_info.patient_gender.value = null;
      document.edit_patient_info.patient_weight.value = null;
      document.edit_patient_info.patient_weight_remainder.value = null;
      document.edit_patient_info.patient_height.value = null;
      document.edit_patient_info.patient_height_remainder.value = null;      
      document.edit_patient_info.patient_hair_color.value = null;
      document.edit_patient_info.patient_eye_color.value = null;
    }    
  });
}

function isAcceptingVisitorsClicked(checkbox)
{
  $("#visitation_info_fields").slideToggle();
  if(!checkbox.checked){
    document.getElementById.byId("patient_visitation_requires_call").checked = false;  
  }  
}

function visitationRequiresCallClicked(checkbox)
{
  if(checkbox.checked){
    document.getElementById("patient_is_accepting_calls").checked = true;
    $("#phone_call_info_fields").slideDown();
    document.getElementById("patient_country_code").setAttribute('class','required');
    document.getElementById("patient_country_code").value = 1;
    document.getElementById("patient_area_code").setAttribute('class','required');
    document.getElementById("patient_phone_prefix").setAttribute('class','required');
    document.getElementById("patient_phone_suffix").setAttribute('class','required');
  }
}

function isAcceptingCalls(checkbox)
{
  $("#phone_call_info_fields").slideToggle();
  if(checkbox.checked){
    document.getElementById("patient_country_code").setAttribute('class','required');
    document.getElementById("patient_country_code").value = 1;
    document.getElementById("patient_area_code").setAttribute('class','required');
    document.getElementById("patient_phone_prefix").setAttribute('class','required');
    document.getElementById("patient_phone_suffix").setAttribute('class','required');
  }
  else{
    document.getElementById("patient_visitation_requires_call").checked = false;
    document.getElementById("patient_country_code").setAttribute('class','');
    document.getElementById("patient_country_code").value = null;
    document.getElementById("patient_area_code").setAttribute('class','');
    document.getElementById("patient_area_code").value = null;
    document.getElementById("patient_phone_prefix").setAttribute('class','');
    document.getElementById("patient_phone_prefix").value = null;
    document.getElementById("patient_phone_suffix").setAttribute('class','');
    document.getElementById("patient_phone_suffix").value = null;
    document.getElementById("patient_extension").value = null;    
  }
}

function editPatientInfoCancelled()
{
  tb_remove();
  $('#patient_info_loader').show();
  $('#patient_info_form').hide();
} 

function editContactInfoCancelled()
{
  tb_remove();
  $('#contact_info_loader').show();
  $('#contact_info_form').hide();     
}

function editStyleCancelled(style_sheet)
{
  tb_remove();
  document.edit_page_style.page_style_sheet.value = style_sheet;
  style_sheet_selection_changed(document.edit_page_style.page_style_sheet);
}

function style_sheet_selection_changed(selection)
{
  document.getElementById('template_preview').src = '/images/template_previews/'+selection.value+'.jpg'; 
}                       

function measurementSystemChanged(selection)
{
  if(selection.value == 'U.S.')
  {
    document.getElementById("primary_weight_unit").innerHTML = "lbs";
    document.getElementById("secondary_weight_unit").innerHTML = "oz";
    document.getElementById("primary_height_unit").innerHTML = "ft";
    document.getElementById("secondary_height_unit").innerHTML = "in";    
  }
  else
  {
    document.getElementById("primary_weight_unit").innerHTML = "kg";
    document.getElementById("secondary_weight_unit").innerHTML = "g";
    document.getElementById("primary_height_unit").innerHTML = "m";
    document.getElementById("secondary_height_unit").innerHTML = "cm";    
  }
  
  document.getElementById("patient_weight").value = null;
  document.getElementById("patient_weight_remainder").value = null; 
  document.getElementById("patient_height").value = null;
  document.getElementById("patient_height_remainder").value = null;     
}

function showLoginForm()
{
  jQuery("div#panel").animate({
  	height: "245px"
  })
  .animate({
  	height: "229px"
  }, "fast");
  jQuery("div.panel_button").toggle();	  
}

function hideLoginForm()
{
  jQuery("div#panel").animate({
  	height: "245px"
  })
  .animate({
    height: "0px"
  }, "fast", null, function(){
    jQuery("div.panel_button").toggle();
  });
  $('#login_form').validate().resetForm();   
}

function toggleStatusUpdate(status_update_id)
{  
  jQuery("div#status_update_"+status_update_id+"_body").slideToggle("slow");
  jQuery("a#expand_status_update_"+status_update_id).toggle();
  jQuery("a#collapse_status_update_"+status_update_id).toggle();
}

function honoraryDonationChecked(checkbox)
{
  $('#donor_label').slideToggle();
  $('#honoree_label').slideToggle();
  $('#notification_email_label').slideToggle();
  $('#donor_field').slideToggle();
  $('#honoree_field').slideToggle();
  $('#notification_email_field').slideToggle();  
  
  if(!checkbox.checked)
  {    
    document.new_donation.donation_donor.value = '';
    document.new_donation.donation_honoree.value = '';
    document.new_donation.donation_notification_email.value = '';    
  }
}

function showLoader()
{
  $('#main_content').fadeOut('fast', function(){
    $('#loader').fadeIn('fast');
  }); 
}

function uploadUserImage(file_field)
{
  $('#main_content').fadeOut('fast', function(){
    $('#loader').fadeIn('fast', function(){
      file_field.form.submit();
      if (parent.document.getElementById('upload_gallery_images_li') && parent.document.getElementById('upload_gallery_images_li').className.indexOf('complete') == -1) {
        parent.document.getElementById('upload_gallery_images_li').className = parent.document.getElementById('upload_gallery_images_li').className+' complete';       
      }        
    });
  });
}

function uploadPageImage(form)
{
  $('#main_content').fadeOut('fast', function(){
    $('#loader').fadeIn('fast', function(){
      form.submit();
      if (parent.document.getElementById('upload_gallery_images_li') && parent.document.getElementById('upload_gallery_images_li').className.indexOf('complete') == -1) {
        parent.document.getElementById('upload_gallery_images_li').className = parent.document.getElementById('upload_gallery_images_li').className+' complete';       
      }       
    });
  });  
 
}

function getCarouselItemHTML(image, page_id)
{  
  var tb_height = image.height; 
  if(image.caption != '')
  {
    tb_height += 100;
  }
  return '<a href="" onclick="getPageImage('+page_id+','+image.id+'); tb_show(null, &quot;#TB_inline?height='+tb_height+'&width='+(image.width+10)+'&inlineId=page_image_'+image.id+'_tb&quot;, false); return false;" title="'+escapeHTML(image.caption)+'"><img alt="'+escapeHTML(image.caption)+'" src="'+image.public_filename_thumb+'"></a>'
}

function getSlideshowItemHTML(image, page_id)
{  
  var image_height = image.thumb_height;
  if(image_height > 192)
  {
    image_height = 192;
  }
  var tb_height = image.height; 
  if(image.caption != '')
  {
    tb_height += 100;
  }
  return '<a href="" onclick="getPageImage('+page_id+','+image.id+'); tb_show(null, &quot;#TB_inline?height='+tb_height+'&width='+(image.width+10)+'&inlineId=page_image_'+image.id+'_tb&quot;, false); return false;" title="'+escapeHTML(image.caption)+'"><img alt="'+escapeHTML(image.caption)+'" src="'+image.public_filename_thumb+'" class="slideshowimage" height="'+image_height+'"></a>'
}

function returnToInviteFriends(wizard)
{
  if(wizard)
  {
    $('#wizard_content').fadeOut("fast", function(){      
      $('#loader').fadeIn("fast", function(){
        $('#invite_step2').hide();
        $('#invite_step1').show();
        $('#loader').fadeOut("fast", function(){
          $('#wizard_content').fadeIn("slow");
        });                
      });
    });     
  }
  else
  {   
    $('#memberships').fadeOut("fast", function(){       
      $('#memberships_loader').fadeIn("fast", function(){
        $('#invite_step2').hide();
        $('#invite_step1').show();
        $('#memberships_loader').fadeOut("fast", function(){
          $('#memberships').fadeIn("slow");
        });
      });
    });     
  }  
}

$(document).ready(function(){ 
	
  addFieldFocusAndBlurEvents();
	
	$(".benefit_header").click(function() {
		$(this).next().slideToggle();
		$(this).children("img").toggle();
	}) 

  $('#banners_cycle').cycle({timeout: 7000, speed: 3000});
  
  if($('#sortable_images'))
  {
    $('#sortable_images').sortable();   
  }	
  
  $('#access_the_classic_site').hover(function() {
		$('#access_the_classic_site_content').fadeIn(200);
		},
		function() {
		$('#access_the_classic_site_content').fadeOut(200);
	})
  
  $('#what_happens_next').hover(function() {
		$('#what_happens_next_content').fadeIn(200);
		},
		function() {
		$('#what_happens_next_content').fadeOut(200);
	})
	
  $('#how_it_works').hover(function() {
		$('#how_it_works_content').fadeIn(200);
		},
		function() {
		$('#how_it_works_content').fadeOut(200);
	})
	
  $('#security_and_privacy').hover(function() {
		$('#security_and_privacy_content').fadeIn(200);
		},
		function() {
		$('#security_and_privacy_content').fadeOut(200);
	})
 
  $('#sharing').hover(function() {
		$('#sharing_content').fadeIn(200);
		},
		function() {
		$('#sharing_content').fadeOut(200);
	})

  $('#switch_mode_link').hover(function() {
		$('#switch_mode_popup').fadeIn(200);
		},
		function() {
		$('#switch_mode_popup').fadeOut(200);
	})
	
  if($("#quotes_carousel .quote"))
  {
  	headline_count = $("#quotes_carousel .quote").size();
  	$("#quotes_carousel .quote:eq(" + next_headline + ")").css('top', '2px');
  	setTimeout(headline_rotate,8000);    
  }
  
  resizeImages('page_background');
  setWmodeForFlash('page_background');    
  resizeImages('status_updates');
  setWmodeForFlash('status_updates');    
  resizeImages('messages');
  setWmodeForFlash('messages');  	
});//end of .ready commands

function createToolTip (target, text) {
 $(target).qtip({
   content: text,
   show: 'mouseover',
   hide: 'mouseout click',
   style: {
   		name:'dark',
		tip: {
			corner: 'topLeft',
			size: {
				x: 5,
				y: 6
			  }
			}
		},
   position: {
      corner: {
         target: 'bottomLeft',
         tooltip: 'topLeft'
      }
   }
  })
}

function headline_rotate()
{
  next_headline = (headline + 1) % headline_count;
	var height= $("#quotes_carousel .quote:eq(" + headline + ")").height();
	var speed = height*150;
	if (height >= 58) {
		$("#quotes_carousel .quote:eq(" + headline + ")").animate({top: -(height-56)},speed, "linear",function(){
			setTimeout(fadeOutQuote,5000);
		});
	}
	
	else {
		fadeOutQuote();
	}
}

function fadeOutQuote()
{
	$("#quotes_carousel .quote:eq(" + headline + ")").fadeOut(2000,function(){
		headline = next_headline;
		$("#quotes_carousel .quote:eq(" + next_headline + ")").css('top', '2px');
		$("#quotes_carousel .quote:eq(" + next_headline + ")").fadeIn(2000,function(){
			setTimeout(headline_rotate, 8000)
		})
	})
};

function resizeImages(id)
{
  if(document.getElementById(id))
  {
    var images = document.getElementById(id).getElementsByTagName('img');
    for(i=0; i<images.length;i++)
    {
      if(images[i].width > 256)
      {
        images[i].width = 256;
      }
    }      
  }
}

function setWmodeForFlash(id)
{
  if(document.getElementById(id))
  {
    var embeds = document.getElementById(id).getElementsByTagName('embed');
    for(i=0; i<embeds.length; i++)
    {
      var s = '<embed type="'+embeds[i].getAttribute('type')+'" src="'+embeds[i].src+'" wmode="transparent" />'
      var div = document.createElement('div');
      div.innerHTML = s;
      var temp = embeds[i].parentNode;
      embeds[i].parentNode.replaceChild(div, embeds[i]);
    }           
  }
}

function setLocale(locale)
{
	var date = new Date();
	date.setTime(date.getTime()+(1000*365*24*60*60*1000));
	var expires = "; expires="+date.toGMTString();
  document.cookie = "locale="+locale+expires+"; path=/";
}

function switchModes(select, page_id)
{
   if(select.value == 'normal')
   {
     document.location = '/pages/'+page_id;
   }
   else if(select.value == 'admin')
   {
     document.location = '/pages/'+page_id+'/edit';
   }
   else
   {
     document.location = '/page_setup_wizard/'+page_id;
   }     
}

function titleize(val)
{
	val = val.replace(/[^\s]+/g, function(word){
		return word.substring(0,1).toUpperCase() + word.substring(1);
	});
  
  return val;  
}

function addFieldFocusAndBlurEvents()
{
	$("input").focus(function(){
		if ($(this).attr('class') == 'error' || $(this).attr('class') == 'required error') {
			$("label.error").hide();
			$(this).next().show();
		}
	});
  
	$("input").blur(function(){
		if ($(this).attr('class') == 'error' || $(this).attr('class') == 'required error') {
			$(this).next().hide();
		}
	});
  
	$("textarea").focus(function(){
		if ($(this).attr('class') == 'error' || $(this).attr('class') == 'contactlist-error') {
			$("label.error").hide();
			$(this).next().show();
		}
	});
  
	$("textarea").blur(function(){
		if ($(this).attr('class') == 'error' || $(this).attr('class') == 'contactlist-error') {
			$(this).next().hide();
		}
	}); 
  
	$("select").focus(function(){
		if ($(this).attr('class') == 'error') {
			$("label.error").hide();
			$(this).next().show();
		}
	});
  
	$("select").blur(function(){
		if ($(this).attr('class') == 'error') {
			$(this).next().hide();
		}
	});         
}