/** detection */

var sUserAgent = navigator.userAgent;
var fAppVersion = parseFloat(navigator.appVersion);
function getIEVersionNumber() {
    var ua = navigator.userAgent;
    var MSIEOffset = ua.indexOf("MSIE ");
    
    if (MSIEOffset == -1) {
        return 0;
    } else {
        return parseFloat(ua.substring(MSIEOffset + 5, ua.indexOf(";", MSIEOffset)));
    }
}

var isOpera = sUserAgent.indexOf("Opera") > -1;
var isKHTML = sUserAgent.indexOf("KHTML") > -1
                || sUserAgent.indexOf("Konqueror") > -1
                || sUserAgent.indexOf("AppleWebKit") > -1;

var isIE = sUserAgent.indexOf("compatible") > -1
            && sUserAgent.indexOf("MSIE") > -1
            && !isOpera;

var isMoz = sUserAgent.indexOf("Gecko") > -1 && !isKHTML;
 // begin external7_pitch
    var examples_data = {
            "pediatrician" :
            {   "img_url" : "/images/join/1_Pediatricians.gif",
                "subject" : "Should I switch pediatricians?",
                "caption" : "Detailed reviews of trusted pediatricians, from moms who have recently used them."
            },
             "highschool" :
            {   "img_url" : "/images/join/2-High-school.gif",
                "subject" : "Which schools should I consider?",
                "caption" : "Get honest feedback from moms who have children at every school."
            },
            "activities" :
            {   "img_url" : "/images/join/3-Activities.gif",
                "subject" : "What&rsquo;s a fun place to take the kids?",
                "caption" : "Read moms&rsquo; reviews on the favorites you already know -- and discover a few new ones!"
            },
            "daycare" :
            {   "img_url" : "/images/join/4-Daycare.gif",
                "subject" : "Need to find great childcare?",
                "caption" : "Ask nearby moms for their most trusted childcare and daycare referrals."
            },
            "birthday" :
            {   "img_url" : "/images/join/5-Birthday-party-locations.gif",
                "subject" : "Where can I have a special birthday party?",
                "caption" : "See the amazing, tried-and-true birthday party ideas other moms have come up with."
            },
            "swim" :
            {   "img_url" : "/images/join/6-Swim-lessons.gif",
                "subject" : "Is my child water-safe?",
                "caption" : "Find the best, mom-recommended instructors for swimming -- or any other activity, art or language."
            },
            "Automotive" :
            {   "img_url" : "/images/join/Automotive.gif",
                "subject" : "Should I get a SUV or a Minivan?",
                "caption" : "Read Moms&rsquo; opinions about which cars and minivans they prefer-- and why."
            },
           "Beauty_Fitness" :
            {   "img_url" : "/images/join/Beauty_Fitness.gif",
                "subject" : "Where can I get a great haircut?",
                "caption" : "Find highly recommended hair stylists in your area."
            },
            "ClubsandGroups" :
            {   "img_url" : "/images/join/ClubsandGroups.gif",
                "subject" : "Are there any playgroups and Mothers&rsquo; groups near me?",
                "caption" : "Find out about playgroups, Moms&rsquo; groups -- or organize your own here."
            },
           "Employment" :
            {   "img_url" : "/images/join/Employment.gif",
                "subject" : "Am I ready to go back to work?",
                "caption" : "Read Moms&rsquo; honest opinions and ideas on balancing home and work life."
            },
            "Family_Parenting" :
            {   "img_url" : "/images/join/Family_Parenting.gif",
                "subject" : "How can I curb this annoying behavior?",
                "caption" : "Read Moms&rsquo; suggestions on proven ways to make a positive change."
            },
           "Finance_Legal" :
            {   "img_url" : "/images/join/Finance_Legal.gif",
                "subject" : "What can I do about my tenant situation?",
                "caption" : "Ask Moms for ideas on financial or legal questions you have."
            },
            "Food_Eating" :
            {   "img_url" : "/images/join/Food_Eating.gif",
                "subject" : "Where can I find a wonderful local bakery?",
                "caption" : "Read Moms&rsquo; reviews of local cafes, restaurants and more. Get recipe ideas and timesaving meal ideas for home too."
            },
           "Home-Maintenance" :
            {   "img_url" : "/images/join/Home-Maintenance.gif",
                "subject" : "Where do I start picking out new cabinets for the kitchen?",
                "caption" : "Read Moms&rsquo; reviews about local home maintenance and improvement businesses. Some businesses listed are owned by members and may offer a discount!"
            },
            "Newborns_Infants" :
            {   "img_url" : "/images/join/Newborns_Infants.gif",
                "subject" : "Why is bath time a struggle all of a sudden?",
                "caption" : "Ask for and read Moms&rsquo; helpful tips and tricks about baby&rsquo;s care."
            },
           "Pets" :
            {   "img_url" : "/images/join/Pets.gif",
                "subject" : "How can I change my dog&rsquo;s bad habits?",
                "caption" : "Find out what has helped other Moms curb bad pet behavior."
            },
            "Pregnancy" :
            {   "img_url" : "/images/join/Pregnancy.gif",
                "subject" : "Wow, what must I absolutely know before I have the baby?",
                "caption" : "Moms have been there. Just ask them any question you have about anything that&rsquo;s on your mind."
            },
           "Religion_Spirituality" :
            {   "img_url" : "/images/join/Religion_Spirituality.gif",
                "subject" : "Are there any clubs that focus on spirituality and personal growth?",
                "caption" : "Find like-minded Moms who share an interest and make new friends."
            },
            "Senior_Care" :
            {   "img_url" : "/images/join/Senior_Care.gif",
                "subject" : "How can I help Mom get a hearing aid?",
                "caption" : "Ask for and receive great information about senior care issues."
            },
           "Shopping" :
            {   "img_url" : "/images/join/Shopping.gif",
                "subject" : "Where can I buy a ...",
                "caption" : "Find out where to buy whatever you are looking for -- or list reviews of your favorite shops and services and spread the word to local Moms."
            },
            "Special_Needs" :
            {   "img_url" : "/images/join/Special_Needs.gif",
                "subject" : "I need advice from a Mom who has experience with my child&rsquo;s condition.",
                "caption" : "Find like-minded Moms who can share their knowledge and offer support."
            },
           "Travel" :
            {   "img_url" : "/images/join/Travel.gif",
                "subject" : "How do I plan a family vacation that everyone will enjoy?",
                "caption" : "Ask and read Moms&rsquo; tips for a stress-free and fun trip."
            },
           "Activity_Lessons_reqs" :
            {   "img_url" : "/images/join/Activity_Lessons_reqs.gif",
                "subject" : "Where are the best summer camps for my child?",
                "caption" : "Ask local moms which camps and activities they recommend."
            },
           "Auto_biz" :
            {   "img_url" : "/images/join/Auto_biz.gif",
                "subject" : "Where can I take my car for a tune up?",
                "caption" : "Read which businesses moms in the area trust and benefit from their experiences."
            },
           "Beauty_Fitness_req" :
            {   "img_url" : "/images/join/Beauty_Fitness_req.gif",
                "subject" : "How am I going to lose this baby weight?",
                "caption" : "Read what has worked for other busy moms and get encouragement along the way."
            },
           "Childcare_SWH" :
            {   "img_url" : "/images/join/Childcare_SWH.gif",
                "subject" : "Where can I find excellent day care providers?",
                "caption" : "Ask other Moms for ideas, and let them know how you make out."
            },
           "Childcare_req" :
            {   "img_url" : "/images/join/Childcare_req.gif",
                "subject" : "Does anyone know of affordable, high quality childcare in the area?",
                "caption" : "Let other Moms help you find what you need, just ask."
            },
           "ClubsandGroups_Bookclub_req" :
            {   "img_url" : "/images/join/ClubsandGroups_Bookclub_req.gif",
                "subject" : "Would any Moms like to join a local book club?",
                "caption" : "Find other moms and join - or start a book club in your area."
            },
           "Education_Biz_rev" :
            {   "img_url" : "/images/join/Education_Biz_rev.gif",
                "subject" : "What resources are available for my special education concerns?",
                "caption" : "Read reviews from other Moms who&rsquo;ve rated the business and shared their experience."
            },
           "Employment_Req" :
            {   "img_url" : "/images/join/Employment_Req.gif",
                "subject" : "How do I do it all?",
                "caption" : "Ask busy moms how and what they do -- and don&rsquo;t."
            },
           "Events_Planning_Biz_review" :
            {   "img_url" : "/images/join/Events_Planning_Biz_review.gif",
                "subject" : "Looking for unique performers for a birthday party?",
                "caption" : "Read reviews of the best party entertainers, and get a jump on planning your next event."
            },
           "Events_Planning_Spotlight" :
            {   "img_url" : "/images/join/Events_Planning_Spotlight.gif",
                "subject" : "How do I start planning for my son&rsquo;s 1st birthday party?",
                "caption" : "Read Moms&rsquo; tried and true solutions to pulling off a fantastic day."
            },
           "Family_Parenting_Biz" :
            {   "img_url" : "/images/join/Family_Parenting_Biz.gif",
                "subject" : "What is a fun holiday craft to do with my boys?",
                "caption" : "Find resources for crafts, games and activities both at home and in the area."
            },
           "Family_Parenting_Req" :
             {   "img_url" : "/images/join/Family_Parenting_Req.gif",
                "subject" : "How do I divide my time between my children?",
                "caption" : "Read what works for busy Moms -- or ask your own question and get solutions."
            },
           "Family_Parenting_SWH" :
            {   "img_url" : "/images/join/Family_Parenting_SWH.gif",
                "subject" : "Help! How do I get through the &quot;tween&quot; years?",
                "caption" : "Get answers to tough problems -- and don&rsquo;t forget to let the Moms know &quot;so what happened&quot;."
            },
           "Finance_Legal_Biz_browse" :
             {   "img_url" : "/images/join/Finance_Legal_Biz_browse.gif",
                "subject" : "Should I go for a 2nd mortgage?",
                "caption" : "Get in touch with recommended local businesses that Moms have reviewed."
            },
           "Food_Eating_SWH" :
            {   "img_url" : "/images/join/Food_Eating_SWH.gif",
                "subject" : "What can I whip up for dinner quickly?",
                "caption" : "Read up on Moms' recipes and timesavers in the kitchen."
            },
           "Health_Medical_Topics"   :
            {   "img_url" : "/images/join/Health_Medical_Topics.gif",
                "subject" : "Where can I find top quality health providers for my family?",
                "caption" : "Learn which doctors and health providers are rated the best from Moms near you."
            },
           "Health_Medical_SWH" :
            {   "img_url" : "/images/join/Health_Medical_SWH.gif",
                "subject" : "Where should I go for my child&rsquo;s glasses?",
                "caption" : "Moms find answers to many questions here, including where to get glasses for a 22 month old. It&rsquo;s all part of the community of Mamasource."
            },
           "Home-Maintenance_biz" :
            {   "img_url" : "/images/join/Home-Maintenance_biz.gif",
                "subject" : "Which local carpet cleaner is the best?",
                "caption" : "Find out where other Moms like you turn for carpet cleaners and much more."
            },
           "Home-Maintenance_req" :
            {   "img_url" : "/images/join/Home-Maintenance_req.gif",
                "subject" : "How do I get a small garden started?",
                "caption" : "Ask Moms for tips on which local nurseries are the best to buy plants, and questions about how to get started."
            },
           "Leisure_Entertainment_Poll" :
            {   "img_url" : "/images/join/Leisure_Entertainment_Poll.gif",
                "subject" : "Where can I take my relatives when they come?",
                "caption" : "Learn about some new, unique places in your own backyard to bring your family and friends."
            },
           "Leisure_Entertainment_Topic" :
            {   "img_url" : "/images/join/Leisure_Entertainment_Topic.gif",
                "subject" : "What&rsquo;s new for family outings?",
                "caption" : "No matter what your family likes to do for fun, you&rsquo;re bound to find it here. And if you don&rsquo;t see it, ask Moms for suggestions."
            },
           "Newborn_Infant-Biz" :
            {   "img_url" : "/images/join/Newborn_Infant-Biz.gif",
                "subject" : "Where can I get those cabinet locks and outlet protectors?",
                "caption" : "Locate where to find what you&rsquo;re looking for, and get it all done in one trip. "
            },
           "Newborn_Infant_MOB_Biz" :
            {   "img_url" : "/images/join/Newborn_Infant_MOB_Biz.gif",
                "subject" : "Shouldn&rsquo;t breastfeeding be easier?",
                "caption" : "Read reviews of all kinds of services from moms like you, and learn who they rely on when they really need help."
            },
           "Pets_req" :
            {   "img_url" : "/images/join/Pets_req.gif",
                "subject" : "Is there a way to explain pet loss to the kids in a way they&rsquo;ll understand? ",
                "caption" : "Get information from other moms, and read what worked for them in difficult times."
            },
           "Pets_Biz_rev" :
            {   "img_url" : "/images/join/Pets_Biz_rev.gif",
                "subject" : "My cat sitter moved, how will I replace her?",
                "caption" : "Read reviews from local Moms about their favorite pet care providers -- and add your own reviews too."
            },
           "Pregnancy_biz_rev" :
            {   "img_url" : "/images/join/Pregnancy_biz_rev.gif",
                "subject" : "Are there any facilities for us while we are trying for another?",
                "caption" : "See reviews from other moms about clinics and physicians in the area."
            },
           "Pregnancy_req_SWH" :
            {   "img_url" : "/images/join/Pregnancy_req_SWH.gif",
                "subject" : "Can I eat anything while expecting?",
                "caption" : "Get the real scoop from moms-in- the- know.  Ask away."
            },
           "Religion_Spirituality_biz" :
            {   "img_url" : "/images/join/Religion_Spirituality_biz.gif",
                "subject" : "Where can I find a special 1st Communion gift?",
                "caption" : "Find the best local businesses that will have exactly what you&rsquo;re looking for."
            },
           "Senior_Care_topics" :
            {   "img_url" : "/images/join/Senior_Care_topics.gif",
                "subject" : "Where can I go for elder care information?",
                "caption" : "Learn what resources are available locally for seniors, and don&rsquo;t forget to ask Moms for help if you need additional suggestions."
            },
           "Shopping_req" :
            {   "img_url" : "/images/join/Shopping_req.gif",
                "subject" : "How can I get a wedding dress altered?",
                "caption" : "Easily find the best seamstress for the job. Read reviews from local Moms about this and many kinds of specialty services."
            },
           "Shopping_biz_rev" :
            {   "img_url" : "/images/join/Shopping_biz_rev.gif",
                "subject" : "Who can I trust for our family portrait?",
                "caption" : "Learn about the best-reviewed photographers -- and why they rated so highly, from other Moms in the area."
            },
           "Special_Needs_req" :
            {   "img_url" : "/images/join/Special_Needs_req.gif",
                "subject" : "Where can I get some follow up tests done for my child?",
                "caption" : "Ask Moms for advice and information to help you solve the issues you need to tackle."
            },
           "Travel_browse_reqs" :
            {   "img_url" : "/images/join/Travel_browse_reqs.gif",
                "subject" : "Are the kids old enough to enjoy Disney world?",
                "caption" : "Get answers from Moms who once had the same questions as you. Learn from their experience -- and let them know how great your vacation turns out."
            }
    };

    g_prev_selected_link = null;
    g_links_locked = false;

    function callback_lock_links(obj) {
        g_links_locked = true;
    }
    function callback_release_links(obj) {
        g_links_locked = false;
    }
    function update_external_details(link, key) {
        if (!g_links_locked) {
            if (g_prev_selected_link) {
                 $(g_prev_selected_link).href = "#";
                 Element.removeClassName(g_prev_selected_link, "selected_link");
            }
            Element.scrollTo('practical_tips')
            new Effect.Highlight('example_details_text', {startcolor:'#ffff99',
                endcolor:'#ffffff',
                duration: 1.0,
                beforeStart: callback_lock_links,
                afterFinish: callback_release_links
                });
            $("sample_image").src = examples_data[key].img_url;
            $("example_subject").innerHTML = examples_data[key].subject;
            $("example_caption").innerHTML = examples_data[key].caption;
            Element.addClassName(link, "selected_link");
            $(link).removeAttribute("href");
            g_prev_selected_link = link;
        }
    }
 // end external7_pitch
function inject_youtube_movie(movie_data) {
	if ($(movie_data.id)){
		$(movie_data.id).remove();

	}
	var movie_str = "<object ";
	movie_str += createParamAttr('id', movie_data.id);
	movie_str += createParamAttr('type', 'application/x-shockwave-flash');
	movie_str += createParamAttr('onclick', movie_data.onclick);
	movie_str += createParamAttr('data', movie_data.data_source);
	movie_str += ">";

	var params = $H({
		enableJSURL: 'false',
		enableHREF: 'false',
		saveEmbedTags: 'true',
		wmode: 'transparent',
		FlashVars: 'playerMode=embedded',
		allowScriptAccess: 'never',
		allownetworking: 'internal',
		movie: movie_data.data_source
	});
	var tmpParam = "";
	params.each(function(pair){
		tmpParam += "<param name=\"" + pair.key + "\" value=\"" + pair.value + "\"></param>";
	});
	movie_str += tmpParam;
	movie_str += "</object>";
	if ($('movie_wrapper')) {
		$('movie_wrapper').innerHTML = movie_str;
	}
	if (movie_data.clickable == true) {
		setup_movie_click();
	}
}

function setup_movie_click() {
	Event.observe('movie', 'mousedown', function(event) {
		 load_play_alt_movie();
	});
}

function load_play_alt_movie() {
    gMovieData.data_source = "http://www.youtube.com/v/flPBGCSB4P4&autoplay=1&rel=0";
	gMovieData.clickable = false;
	inject_youtube_movie(gMovieData);
}

function write_cj_ad() {
	document.write('<SCRIPT type="text/javascript" LANGUAGE="javascript" src="http://www.qksz.net/1e-e9jy"> </SCRIPT>');
}

function write_cj_text_ad() {
	document.write('<SCRIPT type="text/javascript" LANGUAGE="javascript" src="http://www.qksz.net/1e-e70h"> </SCRIPT>');
}

function createParamAttr(key, value) {
	return  key	+ "=\"" + value + "\" ";
}

function show_tooltip(item) {
	$(item).style.visibility = "visible";
}

function hide_tooltip(item) {
	$(item).style.visibility = "hidden";
}

function submit_form(frm_name, method) {
// Can be assigned as an event handler to any form element
// Method argument is optional
	var args = submit_form.arguments;
	$(frm_name).method = (args.length > 1 && args[1] != null) ? method : 'post';
	$(frm_name).submit();
	return false;
}

// used by coreg

function add_child_age_menu_handlers(form_id) {
	var select_items = $(form_id).select('select');
	select_items.each(function(item) {
		Event.observe(item, 'change', function(e) {
			// do the ajax post only when the month/year pairs
			// are both selected
			var sibling = Event.element(e).adjacent('select')[0];
			if ($F(Event.element(e)) && $F(sibling)) {
				new Ajax.Updater('child_age_form_wrapper', '/home/cr1', {
					parameters: $(form_id).serialize(true),
					onComplete: function() {
						add_child_age_menu_handlers(form_id);
					}
				});
			}
			return false;
		})
	});
}

function preview_biz_share(biz_id, msg_body_field_id){
// fetch a mother-owned-business share email preview
	show_loading_msg();
	var url = "/share/preview_share"
	var params = "business_id=" + biz_id + "&" + msg_body_field_id + "=" + $F(msg_body_field_id);
	var myAjax = new Ajax.Updater(
		'email_preview_popup_content', 
		url, 
		{
			method: 'post', 
			parameters: params,
			onComplete: show_biz_share_preview
		});
	return false;
}

function show_loading_msg() {
	Element.show('loading_msg');
}

function show_biz_share_preview(request) {
	Element.show('email_preview_popup_wrapper');
	Element.hide('loading_msg');
}

function hide_biz_share_preview() {
	Element.hide('email_preview_popup_wrapper');
	return false;
}

function jump_to(base_url, jump_param_name, jump_param_value) {
	if (jump_param_value != "") {
		window.location = base_url + "?" + jump_param_name + "=" + jump_param_value;
	}
	return false; 
}

function show_selected_poll_card(el){
    var jump_to_pod = $A(document.getElementsByClassName("jump_to"));
	jump_to_pod.each(function(pod_element){
                Element.removeClassName(pod_element, "jump_to");
                }); 
	var paginated_pod = $A(document.getElementsByClassName("poll_pod_is_paginated"));
	paginated_pod.each(function(pod_element){
                Element.removeClassName(pod_element, "poll_pod_is_paginated");
                }); 
	Element.addClassName(el, "poll_pod_is_paginated");
}

/**** timed popups */
var g_open_popup = null;
var g_popup_closer_timeout = 0;
var POPUP_CLOSE_DELAY = 5000;

function show_timed_popup(el) {
	try {
         if (g_open_popup) {
            Element.hide(g_open_popup);
            if ($(g_open_popup).parentNode) {
                $(g_open_popup).parentNode.style.zIndex="1";
            }
        }
        $(el).parentNode.style.zIndex="21";
        Element.show(el);
		g_open_popup = el;
    } catch (e) {
		//
	}
}

function hide_timed_popup(el) {
    try {
		g_popup_closer_timeout = setTimeout(function() {
            if ($(el)) {
			    Element.hide(el);
                if ($(el).parentNode) {
                   $(el).parentNode.style.zIndex = 1; 
                }
            }

		}, POPUP_CLOSE_DELAY);
	} catch (e) {
		//
	}
}

function hide_any_popup() {
     if ($(g_open_popup)) {
        Element.hide(g_open_popup);
        if ($(g_open_popup).parentNode) {
            $(g_open_popup).parentNode.style.zIndex="1";
        }
        g_open_popup = null;
    }
}

function hide_popup(el) {
	try {
		cancel_hide_timed_popup();	
        $(el).parentNode.style.zIndex="1";
        Element.hide(el);
        g_open_popup = null;
    } catch (e) {
		//
	}
}

function cancel_hide_timed_popup() {
	if (g_popup_closer_timeout > 0) {
		clearTimeout(g_popup_closer_timeout);
		g_popup_closer_timeout = 0;
	}
}

/** scanning for a class name is easier than passing the dynamically-generated
 * item id into the animation function .
* animate_share_link is attached to the window.load observer
* in business_details and details
*/
function animate_share_link(evt) {
	var links = $A(document.getElementsByClassName("share_link_primary")); 
	links.each(function(item) {
		new Effect.Highlight(item, {delay: 1.5, queue: 'end', duration: 5.0} );
	    }
	);
}

/** begin checkbox utilities */

function check_all(input_class_name) {
	var input_fields = $A(document.getElementsByClassName(input_class_name));
    input_fields.each(function(item) {item.checked = "checked";});    
}

function uncheck_all(input_class_name) {
	var input_fields = $A(document.getElementsByClassName(input_class_name));
    input_fields.each(function(item) {item.checked = "";});    
}
/** end checkbox utilities */

/** begin form utilities */

function update_children() {
	if ($('child_update_form')) {
	   $('child_update_form').submit();
	}
}

function textCounter(field,cntfield,maxlimit, e) {
	var fld = $(field);
	if (fld.value.length > maxlimit) {// if too long...trim it!
		fld.value = fld.value.substring(0, maxlimit);
		// otherwise, update 'characters left' counter
	} else {
		$(cntfield).innerHTML = maxlimit - fld.value.length;
	}
}
/**
any radio button whose class is 'radio_listener' will
auto-focus whichever form field that follows.

Target form field must be an adjacent sibling
 
Requires calling this function from a window onload observer
See _perk_fields.rhtml
*/
function initialize_radio_listeners() {
	var candidate_fields = $A(['input','textarea', 'select']);
	var radios = $$('input.radio_listener');
	var next_item;
	radios.each(function(item) {
		Event.observe(item, 'click', function(e) {
			candidate_fields.each(function(candidate) {
				next_item = item.next(candidate);
				if (next_item) {
					next_item.focus();
				}
			});	
		});
	});
}

function clearPwBox(field_id) {
	window.setTimeout(function() {
		var pw = $(field_id);
			pw.value = "";
	}, 1000);
}

function initialize_clearPwBox(field_id) {
	Event.observe(window, 'load', function(e) {
		 clearPwBox(field_id);
	});
}

function set_delayed_field_value(field_id, value_text) {
	window.setTimeout(function() {
		var field = $(field_id);
			field.value = value_text;
	}, 1000);
}

function initialize_set_field_value(field_id, value_text){
	Event.observe(window, 'load', function(e) {
		set_delayed_field_value(field_id, value_text);
	});
}

function add_link_targets() {
	var items = $A(document.getElementsByClassName('new_window'));
	items.each(function(item) {
		item.setAttribute('target', '_blank');
	});
}
// for use in forms that do not have help balloons
function initialize_focus_first_element(form_id) {
		Event.observe(window, 'load', function(e) {
		focus_first_element(form_id);
	});
}

// when you can't set an ID for a form OR you want to focus a field other than the first
// element in a form, pass in the input reference instead
function initialize_focus_element(id) {
		Event.observe(window, 'load', function(e) {
		$(id).focus();
	});
}

function focus_first_element(form_id) {
	  $(form_id).focusFirstElement();
}

/** end form utilities */

/** begin help balloon utilities */
function initialize_help_balloons() {
		Event.observe(window, 'load', function(e) {
		initialize_fields_with_balloons();
	});
}

// set up listeners for balloons 
function initialize_fields_with_balloons() {
	var fields_with_balloons = $A(document.getElementsByClassName('has_help_balloon'));
	var field_balloon;
	var curr_id;

	fields_with_balloons.each(function(item, curr_index) {
		$(item).up().addClassName('contains_help_ballons');
		field_balloon = document.getElementsByClassName('help_balloon')[curr_index];
		$(field_balloon).id = "help_balloon_" + curr_index;		
		Event.observe(item, 'focus', function() {
			curr_id = "help_balloon_" + curr_index;
			hide_help_balloons();
			$(curr_id).show();
		});
	});
}

function hide_help_balloons() {
	var balloons = $A(document.getElementsByClassName('help_balloon'));
	balloons.each(function(balloon) {
		$(balloon).hide();
	});
}
/** end help balloon utilities */

/** begin import_contacts module */

function set_manual_email_focus() {
	first_field = document.getElementsByClassName('manual_email_field')[0];
	$(first_field).activate();
}
var g_PE = null;
var g_PE_running = false;
var g_from_ic_widget = false;
var g_use_counter = false;

function init_contacts_import(from_ic_widget) {
	if (from_ic_widget) {
		g_from_ic_widget = true;
	}
	setup_vrf_contacts_submit_confirmation();
	setup_contact_items();
	disable_import_contacts_key_listeners();
	init_polling();
}
// ToDo: refactor DOM code after updating to prototype 1.6
g_vrf_import_contacts_message_element = null;

function setup_vrf_contacts_submit_confirmation() {

	Event.observe("contacts_message_form", 'submit', function(e) {

		 $('submit_button').disabled = "disabled";
		 $('submit_button').addClassName("disabled");
		if (g_from_ic_widget) {
			return false;
		} else {
			var confirm_text = "Thank you, your invitations have been sent!<br>Please wait one moment while we look up who you know on Mamasource.";
			g_vrf_import_contacts_message_element = $(document.createElement('div')).addClassName("vrf_import_submit_confirmation").setStyle({display: "none"}).update(confirm_text);
			var the_fieldset = $(document.getElementsByTagName('fieldset')[0]);
			the_fieldset.appendChild(g_vrf_import_contacts_message_element);
			$(g_vrf_import_contacts_message_element).show();
			return true;
		}
	});
}

function disable_import_contacts_key_listeners() {
	Event.observe("contacts_message_form", 'keypress', function(e1) {
		var portable_code = e1.charCode || e1.keyCode;
		if (portable_code < 32 && portable_code != Event.KEY_TAB && portable_code != Event.KEY_BACKSPACE){
			Event.stop(e1);
			return false;
		}
	});
}

function init_polling() {
	stop_polling();
    new PeriodicalExecuter(function(pe) {
        var is_disabled = true;
	    var selected_count = 0;
	    g_PE = pe;
        var input_fields = $A(document.getElementsByClassName('contacts_input'));
        input_fields.each(function(item) {
            if ($(item).checked) {
                is_disabled = false;
	            selected_count++;
            }
        });
	    if (g_use_counter) {
		    var text = selected_count;
			text += (selected_count == 1) ? "&nbsp;Mom selected" : "&nbsp;Moms selected";
			$('selected_count').innerHTML = text; 
	    }
        input_fields = $A(document.getElementsByClassName('manual_email_field'));
        input_fields.each(function(item) {
            if ($(item).value != "") {
                is_disabled = false;
            }
        });
	if ($('submit_button') != null){
	    if (is_disabled) {
		$('submit_button').disabled = true;
		$('submit_button').addClassName("disabled");
	    }   else {
			    $('submit_button').disabled = false;
		$('submit_button').removeClassName("disabled");
	    }
	}
    }, 0.5);
	g_PE_running = true;
}

function stop_polling() {
	if(g_PE) {
		g_PE.stop();
		g_PE_running = false;
	}
}

function adjust_contacts_box_height(num_contacts) {
	var calculated_height = ((num_contacts) > 20 ? 20 : num_contacts) * 27;
	$('contact_item_wrapper').style.height = calculated_height + "px";
}

function setup_contact_items() {
	var contact_items = $A(document.getElementsByClassName("contact_item"));
	contact_items.each(function(item) {
		if ($(item).down('input').checked) {
			$(item).addClassName('highlighted');
		}

		 Event.observe(item, 'click', function(event) {
			// restart polling mechanism if VRF backbutton loads contacts_import from cache
			if (!g_PE_running) {init_polling();} 
		   var clicked_item = Event.element(event);
			if (clicked_item.tagName.toUpperCase() != "INPUT" && ! $(clicked_item).hasClassName('contact_item')) {
			   var cb = $(clicked_item).up(0).getElementsByClassName('contacts_input')[0];
				if ($(cb).checked) {
					$(cb).checked = "";
				} else {
					$(cb).checked = "checked";
				}
			}

		  });
	});
}
/**
    The selected_class arg is optional. If set, it will add that class name
    to the highlighted item and remove it from an unselected item
 */

	function highlight_contact(rollover_item, is_mouse_over, selected_class) {
		var checkbox_checked = $(rollover_item).down('input').checked;
		if (!checkbox_checked) {
			if (is_mouse_over) {
				$(rollover_item).addClassName('highlighted');
			} else {
				$(rollover_item).removeClassName('highlighted');
			}
			if (selected_class) {
				$(rollover_item).removeClassName(selected_class);
			}

		} else {
			if (selected_class) {
				$(rollover_item).addClassName(selected_class);
			}
		}
	}

/** end import_contacts module */

function log(text){
   $('log').innerHTML = text + " <br>" + $('log').innerHTML ;
}

/** one-offs */
function update_response_form_view() {
	$("advice_form", "business_form", "message_form").invoke("hide");
	var selected_value = $F("respond_menu");
	$(selected_value).show();
}


/*following function is required to track the intra click events*/
function track_click(value)
{
	var d = new Date();
	var url=location.protocol + "//" + location.host + "/click" + location.pathname + "/" + value + "?" + d.getTime();
	var myAjax = new Ajax.Request(url, {method: 'get'});
}


/* Given an -element-, every instance of the -phrase- is wrapped with a span of -span_class- type */
function wrap_phrase_with_span(element, phrase, span_class){
	if (element && phrase && span_class){
		phrase = phrase.toLowerCase();
		var body_text = element.innerHTML;
		var lc_body_text = body_text.toLowerCase();

		var offset = 0; var i = 0; 
		while ( (i = lc_body_text.indexOf(phrase, i)) > -1 ){
			if (body_text.lastIndexOf(">", i) >= body_text.lastIndexOf("<", i)) { // Skip anything inside a HTML tag
				var bodyPhrase = body_text.substr(i + offset, phrase.length);
				var tag = '<span class="' + span_class + '">' + bodyPhrase + '</span>';
					
				body_text = body_text.substring(0, i + offset) + tag + body_text.substring(i + offset + bodyPhrase.length, body_text.length);
				offset += tag.length - phrase.length;
			}

			i += phrase.length;
		}

		element.innerHTML = body_text;
	}
}
