Ajax.Autocompleter.extract_value =
  function (value, className) {
    var result;
    var elements =
      document.getElementsByClassName(className, value);
    if (elements && elements.length == 1) {
      result = elements[0].innerHTML.unescapeHTML();
    }
    return result;
  };

// Extended Tooltip Javascript
// copyright 9th August 2002, 3rd July 2005
// by Stephen Chapman, Felgall Pty Ltd

// permission is granted to use this javascript provided that the below code is not altered
var DH = 0;var an = 0;var al = 0;var ai = 0;if (document.getElementById) {ai = 1; DH = 1;}else {if (document.all) {al = 1; DH = 1;} else { browserVersion = parseInt(navigator.appVersion); if ((navigator.appName.indexOf('Netscape') != -1) && (browserVersion == 4)) {an = 1; DH = 1;}}} function fd(oi, wS) {if (ai) return wS ? document.getElementById(oi).style:document.getElementById(oi); if (al) return wS ? document.all[oi].style: document.all[oi]; if (an) return document.layers[oi];}
function pw() {return window.innerWidth != null? window.innerWidth: document.body.clientWidth != null? document.body.clientWidth:null;}
function mouseX(evt) {if (evt.pageX) return evt.pageX; else if (evt.clientX)return evt.clientX + (document.documentElement.scrollLeft ?  document.documentElement.scrollLeft : document.body.scrollLeft); else return null;}
function mouseY(evt) {if (evt.pageY) return evt.pageY; else if (evt.clientY)return evt.clientY + (document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop); else return null;}
function popUp(evt,oi) {if (!$('big_image')){var asdf=document.createElement("div");asdf.innerHTML="<div id='big_image' class='tip' /></div>";document.body.appendChild(asdf);}if (DH) {var wp = pw(); ds = fd(oi,1); dm = fd(oi,0); st = ds.visibility; if (dm.offsetWidth) ew = dm.offsetWidth; else if (dm.clip.width) ew = dm.clip.width; if (st == "visible" || st == "show") { ds.visibility = "hidden"; } else {tv = mouseY(evt) + 20; lv = mouseX(evt) - (ew/4); if (lv < 2) lv = 2; else if (lv + ew > wp) lv -= ew/2; if (!an) {lv += 'px';tv += 'px';} ds.left = (parseInt(lv) + -200) + "px"; ds.top = tv; ds.visibility = "visible";}}}
function popUpforFamily(evt,oi) {if (!$('family_more_info')){var asdf=document.createElement("div");asdf.innerHTML="<div id='family_more_info' class='tip' />"+document.getElementById("family_more_info_text").innerHTML+"</div>";document.body.appendChild(asdf);}if (DH) {var wp = pw(); ds = fd(oi,1); dm = fd(oi,0); st = ds.visibility; if (dm.offsetWidth) ew = dm.offsetWidth; else if (dm.clip.width) ew = dm.clip.width; if (st == "visible" || st == "show") { ds.visibility = "hidden"; } else {tv = mouseY(evt) + 20; lv = mouseX(evt) - (ew/4); if (lv < 2) lv = 2; else if (lv + ew > wp) lv -= ew/2; if (!an) {lv += 'px';tv += 'px';} ds.left = (parseInt(lv) + 100) + "px"; ds.top = tv; ds.visibility = "visible";}}}
function popUpforSenior(evt,oi) {if (!$('senior_more_info')){var asdf=document.createElement("div");asdf.innerHTML="<div id='senior_more_info' class='tip' />"+document.getElementById("senior_more_info_text").innerHTML+"</div>";document.body.appendChild(asdf);}if (DH) {var wp = pw(); ds = fd(oi,1); dm = fd(oi,0); st = ds.visibility; if (dm.offsetWidth) ew = dm.offsetWidth; else if (dm.clip.width) ew = dm.clip.width; if (st == "visible" || st == "show") { ds.visibility = "hidden"; } else {tv = mouseY(evt) + 20; lv = mouseX(evt) - (ew/4); if (lv < 2) lv = 2; else if (lv + ew > wp) lv -= ew/2; if (!an) {lv += 'px';tv += 'px';} ds.left = (parseInt(lv) + 100) + "px"; ds.top = tv; ds.visibility = "visible";}}}
function hidePopup(evt,oi){ if($(oi)) {$(oi).innerHTML = "" ;$(oi).style.visibility = "hidden"}}

// Returns the target element of an event. Accepts a single argument, the event.
function sourceElement(e) {
    if (e.srcElement) { //IE
        var target = e.srcElement.value;
    } else { //Others
        var target = e.target.value;
    }
    return target;
}

/***********************************/
/************* custom javascript***/
/*********************************/
function submitEditForm(formName){
    document.forms[formName].submit();
}


function Delete_Cookie( name, path, domain ) {
    if ( Get_Cookie( name ) ) document.cookie = name + "=" +
    ( ( path ) ? ";path=" + path : "") +
    ( ( domain ) ? ";domain=" + domain : "" ) +
    ";expires=Thu, 01-Jan-1970 00:00:01 GMT";
}

    function Get_Cookie( check_name ) {
            // first we'll split this cookie up into name/value pairs
            // note: document.cookie only returns name=value, not the other components
            var a_all_cookies = document.cookie.split( ';' );
            var a_temp_cookie = '';
            var cookie_name = '';
            var cookie_value = '';
            var b_cookie_found = false; // set boolean t/f default f

            for ( i = 0; i < a_all_cookies.length; i++ )
            {
                    // now we'll split apart each name=value pair
                    a_temp_cookie = a_all_cookies[i].split( '=' );

                    // and trim left/right whitespace while we're at it
                    cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');

                    // if the extracted name matches passed check_name
                    if ( cookie_name == check_name )
                    {
                            b_cookie_found = true;
                            // we need to handle case where cookie has no value but exists (no = sign, that is):
                            if ( a_temp_cookie.length > 1 )
                            {
                                    cookie_value = unescape( a_temp_cookie[1].replace(/^\s+|\s+$/g, '') );
                            }
                            // note that in cases where cookie is initialized but no value, null is returned
                            return cookie_value;
                            break;
                    }
                    a_temp_cookie = null;
                    cookie_name = '';
            }
            if ( !b_cookie_found )
            {
                    return null;
            }
    }

/* args[0] = formName*/
function submitForm(){
    var args = submitForm.arguments;
    $('error_message').style.display = "block";
    if( ($('error_message').innerHTML) && ($('error_message').innerHTML=='success') ) {
        $('error_message').innerHTML = "<div class='dataConfirmationExplanation' id='dataConfirmationExplanation'>Data added successfully!</p></div>";
        //window.setTimeout('document.forms["'+args[0]+'"].submit();', 2500);
        window.setTimeout("new Effect.toggle( 'modal_dialog', 'slide');overlayToggle('none');", 2500);
    }else return false;
}

function submitEmergencyContact(){
    var args = submitForm.arguments;
//    $('error_message').style.display = "block";
//    new Effect.toggle('error_message','appear'); 
    new  Effect.Appear('error_message');
    if( ($('error_message').innerHTML) && ($('error_message').innerHTML=='success') ) {
        $('error_message').innerHTML = "<div class='dataConfirmationExplanation' id='dataConfirmationExplanation'>Data added successfully!</p></div>";
          new Effect.Fade('error_message', { delay: 5.0 });
         // $('error_message').style.display = "none";
        //window.setTimeout('document.forms["'+args[0]+'"].submit();', 2500);
        //window.setTimeout("new Effect.toggle( 'modal_dialog', 'slide');overlayToggle('none');", 2500);
    }else {
      //$('error_message').innerHTML = "<div class='dataConfirmationExplanation' id='dataConfirmationExplanation' style='color:red;'>* fields should not be empty</p></div>";
        //new Effect.Fade('dataConfirmationExplanation', { delay: 5.0 });
   }
}

function CloseThisWindow(){
    overlayToggle('none');
    new Effect.Fade( 'modal_dialog', {duration: 0.2 });
}

function submitFormForUser(formName){
    $('error_message').style.display = "block";
    if( ($('error_message').innerHTML) && ($('error_message').innerHTML=='success') ) {
       $('error_message').style.display = "none";
       $('SuccessMessage').style.display = "block";
       //$('error_message').innerHTML = "<div class='dataConfirmationExplanation' id='dataConfirmationExplanation'>Data added successfully!</p></div>";
       return;
    }
}

function add_family_member(){
    var userid = $('user_id[]');
    for(var i=0; i<$(userid).length; i++){
        if ($('userid')[i].checked){
            val = $('userid')[i].value;
        }
    }
    if (confirm('Do you want to add selected user as family member?'))return true;
    else return false;
}

function setLoading(){
    $('error_message').style.display = "block";
//    new Effect.toggle('error_message','appear');
//    alert($('error_message').style.display);
    new  Effect.Appear('error_message');
    $('error_message').innerHTML = "<div class='dataProcessExplanation' id='dataProcessExplanation'>Sending data.. Please wait!</p></div>";
}

function setLoadingMessage(){
    var args = setLoadingMessage.arguments;
    var status = args[0];
    var string_to_display = args[1]
    if($('addressbook_error_message')){
        $('addressbook_error_message').style.display = "block";
    
    if(status.toString().toLowerCase()=="delete"){
       $('addressbook_error_message').innerHTML = "<div class='dataProcessExplanation' id='dataProcessExplanation'>Deleting data.. Please wait!</p></div>";
    }else if(status.toString().toLowerCase()=="save"){
       $('addressbook_error_message').innerHTML = "<div class='mDiv' style=''><table cellspacing='0' cellpadding='0' class='' style='' align='center' ><tbody><tr><td class='' style='background-position: 0px; background-repeat: no-repeat; '/><td class=''/><td class='' style='background-position: -4px 0px; background-repeat: no-repeat; '/></tr><tr><td class='tbltdCls_alert' ><td class='tbltdTxt'>Sending data.. Please wait!</td><td class=''/></tr><tr><td class='' style='background-position: 0px -4px; background-repeat: no-repeat; '/><td class=''/><td class='' style='background-position: -4px; background-repeat: no-repeat; '/></tr></tbody></table></div>";
    } else if(status.toString().toLowerCase()=="delete_success"){
       $('addressbook_error_message').innerHTML = "<div class='dataProcessExplanation' id='dataProcessExplanation'>"+string_to_display+" Deleted Successfully!</p></div>";
    }
    }
}
// <span class='mandatory'>* </span>
function addUserContact()
{
	$('emergency_contact_form').style.display = "block";
	var args = addUserContact.arguments;
	var tbl = $(args[0]);
	if (tbl.rows.length >2)	{
	alert("Maximum limit reached to add emergency contacts ");
	return false;
	}
	else	{
	var newRow = tbl.insertRow(tbl.rows.length);
	var count = newRow.rowIndex-1;
	newRow.setAttribute('id', 'txtRow' + newRow.rowIndex);

	var newCell = "newCell_"+count ;
	newCell = newRow.insertCell(0);
	newCell.innerHTML = 
        "<table cellpadding='1' cellspacing='0' width='100%'  >"+
        "<tr>"+
        "<th align='left'><span class='mandatory'>* </span>First Name </th>"+
        "<th align='left'>Last Name </th>"+
        "</tr>"+
        "<tr>"+
        "<td><input id='first_name[]' onkeypress='return checkName(event)' name='first_name[]' type='text' class='textfield' size='22' maxlength='22'></td>"+
        "<td><input id='last_name[]'  onkeypress='return checkName(event)' name='last_name[]' type='text' class='textfield'  size='22' maxlength='22'></td>"+
        "</tr>"+
        "<tr>"+
        "<th colspan='1'  align='left'> <span class='mandatory'>* </span>Email Address</th>"+
        "<th align='left'>Phone Number</th>"+
        "<th></th>"+
        "</tr>"+
        "<tr>"+
        "<td colspan='1'><input maxlength='33' size='33' id='email_address[]' name='email[]' type='text' class='emailfield' onkeypress = 'return checkEmailId(event)' ></td>"+
        "<td colspan='2'>"+
        "(<input type='text' size='3' onkeypress='return checkNumbers(event)' id='phone_first[]' name='phone_first[]' maxlength='3' class='phone'/>)"+
        "<input type='text' size='3' onkeypress='return checkNumbers(event)' id='phone_middle[]' name='phone_middle[]' maxlength='3' class='phone'/>-"+
        "<input type='text' size='4' onkeypress='return checkNumbers(event)' id='phone_last[]' name='phone_last[]' maxlength='4' class='phone'/>"+
        "</td>"+
        "</tr>"+
        "</table>"+
        "<div style='float:right;position:relative;right:30px;top:-20px;'  onclick='deleteRow(this);' ><img src='/images/delete.gif' alt='Delete this row' /></div>"+
        "<hr class='divider'/>";
    }
   /* var newCell = "newCell_"+count ;
	newCell = newRow.insertCell(1);
	newCell.innerHTML = '<input id="middle_name[]" name="middle_name[]" size="5" value="" type="text">';

	var newCell = "newCell_"+count ;
	newCell = newRow.insertCell(2);
	newCell.innerHTML = '<input id="last_name[]" name="last_name[]" size="15" value="" type="text">';

	var newCell = "newCell_"+count ;
	newCell = newRow.insertCell(3);
	newCell.innerHTML = '<input id="email[]" name="email[]" size="15" value="" type="text">';

	var newCell = "newCell_"+count ;
	newCell = newRow.insertCell(4);
	newCell.innerHTML = '<input id="phone[]" name="phone[]" size="15" value="" type="text">';*/

	//$('hiddenInterfaceName').value = interfaceName;
}

function deleteRow(r)
  {
  var i=r.parentNode.parentNode.rowIndex
  $("emergency_contact").deleteRow(i)
  if ($("emergency_contact").rows.length == 0) $("emergency_contact_form").style.display = "none";
  }
  
function addContactRowByAppend()
{

		var args = addContactRowByAppend.arguments;
		var NoOfSeniors = $(args[1]);
		var tbl = $(args[0]);
		var newRow = tbl.insertRow(tbl.rows.length);
		var count = newRow.rowIndex-1;
		newRow.setAttribute('id', 'txtRow' + newRow.rowIndex);

			var newCell = "newCell_"+count ;
			newCell = newRow.insertCell(0);
			newCell.innerHTML =
		      '<hr/><table cellSpacing="1" cellPadding="1" width="500px" border="0">'+
		        '<tr>'+
		          '<td><span class="mandatory">* </span>First Name </td>'+
		          '<td>M.I.</TD>'+
		          '<td><span class="mandatory">* </span>Last Name </td>'+
		          '</tr>'+
		        '<tr>'+
		          '<td><input style="width: 90%" id="first_name[]" name="first_name[]" type="text" class="required"></td>'+
		          '<td><input style="width: 90%" id="last_name[]" name="last_name[]" type="text" class="required"></td>'+
		        '</tr>'+
		        '<tr>'+
		          '<td colspan="3"><span class="mandatory">* </span>Email Address</td>'+
		          '<td><span class="mandatory">* </span>Phone Number</td></tr>'+
		        '<tr>'+
		          '<td colspan="3"><input style="width: 80%" maxlength="35" size="35" id="email_address[]" name="email_address[]" type="text" class="required"></td>'+
		          '<td><input id="phone_1[]" name="phone_1[]"  size="3"  value="" type="text" maxlength="3" onkeypress ="return checkNumbers(event)" class="required">'+
		              '<input id="phone_2[]" name="phone_2[]"  size="3"  value="" type="text" maxlength="3" onkeypress ="return checkNumbers(event)" class="required">'+
		              '<input id="phone_3[]" name="phone_3[]"  size="4"  value="" type="text" maxlength="4" onkeypress ="return checkNumbers(event)" class="required">'+
		          '</td>'+
		        '</tr>'+
		        '<tr>'+
		          '<td colspan="3">Add Picture </td>'+
		          '<td>&nbsp;</td></tr>'+
		        '<tr>'+
		          '<td colspan="4"><input type="file" size="30" id="picture_name[]" name="picture_name[]"></td>'+
		        '</tr>'+
		    '</table>';

			var newCell = "newCell_"+count ;
			newCell = newRow.insertCell(1);
			newCell.style.width="100px";
			newCell.setAttribute("align","center");
			//newCell.style.vertical-align="top";
			//newCell.style.align="middle";
			newCell.innerHTML = '<input type="checkbox" value="1"  id="invite_tbs_'+(tbl.rows.length-1)+'" name="invite_tbs_'+(tbl.rows.length-1)+'">';


				var newCell = "newCell_"+count ;
				newCell = newRow.insertCell(2);
				newCell.style.width="200px";
				seniorhtml = '<table cellspacing="1" cellPadding="1" width="200px" border=0><tr>';
				for(var i=0; i<NoOfSeniors; i++){
				seniorhtml = seniorhtml + '<td width="66px" align="center"><input type="checkbox" value="1" id="senior_id_'+(tbl.rows.length-1)+'_'+i+'" name="senior_id_'+(tbl.rows.length-1)+'_'+i+'"></td>';
				}
				seniorhtml = seniorhtml + '</tr></table>';
				newCell.innerHTML = seniorhtml;




}

function addListingRowByAppend()
{
	var args = addListingRowByAppend.arguments;
	var tbl = $(args[0]);
	if (tbl.rows.length >=args[2])	{
	alert("Maximum limit reached to add emergency contacts ");
	return false;
	}
	else	{
	var newRow = tbl.insertRow(tbl.rows.length);
	var count = newRow.rowIndex-1;
	newRow.setAttribute('id', 'txtRow' + newRow.rowIndex);

	var newCell = "newCell_"+count ;
	newCell = newRow.insertCell(0);
	newCell.setAttribute('width', '40%');
	newCell.innerHTML = '<input id="listname[]" name="listname[]" size="15" value="" type="text" maxlength="20" onkeypress="return checkSpecialName(event)" class="textfield" >';

	var newCell = "newCell_"+count ;
	newCell = newRow.insertCell(1);
	newCell.innerHTML =  '(&nbsp;<input type="text" size="3" onkeypress="return checkNumbers(event)" id="phone1[]" name="phone1[]" maxlength="3" class="phone"/>)&nbsp;<input type="text" size="3" onkeypress="return checkNumbers(event)" id="phone2[]" name="phone2[]" maxlength="3" class="phone"/>-<input type="text" size="4" onkeypress="return checkNumbers(event)" id="phone3[]" name="phone3[]" maxlength="4" class="phone"/>';

	var newCell = "newCell_"+count ;
	newCell = newRow.insertCell(2);
	newCell.innerHTML =  '<div style="float:right;position:relative;right:50px;"  onclick=deleteListRow(this,"'+args[0]+'","'+args[1]+'"); ><img src="/images/delete.gif" alt="Delete this row" /></div>';
	
	/*
	var newCell = "newCell_"+count ;
	newCell = newRow.insertCell(2);
	newCell.innerHTML = '';

	var newCell = "newCell_"+count ;
	newCell = newRow.insertCell(3);
	newCell.innerHTML = '';*/
    }
}

function deleteListRow(r,tbl,save_div)
{
  var i=r.parentNode.parentNode.rowIndex;
  $(tbl).deleteRow(i);
  if ($(tbl).rows.length == 0) {
  $(save_div).style.display = "none";
  }
}
function addSurveyQuestions()
{
	var args = addSurveyQuestions.arguments;
	var tbl = $(args[0]);
	if (tbl.rows.length > 4)	{
	alert("Maximum limit reached to add new survey please ");
	return false;
	}
	else	{
	var newRow = tbl.insertRow(tbl.rows.length);
	var count = newRow.rowIndex-1;
	newRow.setAttribute('id', 'txtRow' + newRow.rowIndex);

    var newCell = "newCell_"+count ;
	newCell = newRow.insertCell(0);
	newCell.innerHTML = "<span class='mandatory'>* </span>";
    /* <label>Q.<label>"+(newRow.rowIndex+1)+" */
	var newCell = "newCell_"+count ;
	newCell = newRow.insertCell(1);
	newCell.innerHTML = '<textarea id="survey_question[]" name="survey_question[]" cols=50 rows=1 />';

	var newCell = "newCell_"+count ;
	newCell = newRow.insertCell(2);
	newCell.innerHTML = '<select name="survey_format[]" id="survey_format[]" >'+
	                    '<option value="Free Text">Free Text</option>'+
                        '<option value="Yes/ No">Yes/ No</option>'+
                        '<option value="1 to 5 Ranking">1 to 5 Ranking</option>'+
                        '<option value="Agree/ Disagree">Agree/ Disagree</option>'+
                        '</select>';
    var newCell = "newCell_"+count ;
	newCell = newRow.insertCell(3);
	newCell.innerHTML = '<img src="/images/delete.gif" onclick="deletesurveyRow(this);"; border="0" /> ';
}
   /* var newCell = "newCell_"+count ;
	newCell = newRow.insertCell(3);
	newCell.innerHTML = '';*/
 }
 function deletesurveyRow(r)
  {
  var i=r.parentNode.parentNode.rowIndex
  $("survey_questions").deleteRow(i)
  if ($("survey_questions").rows.length == 0) {
  $("survey_questions").style.display = "none";
  }
  }

function removeRowFromTable()
{
  var args = removeRowFromTable.arguments;
  $(args[0]).deleteRow(args[1]);
}


var senior_table_listener = function(){
    // change the style of text field element on focus
    var focus = function(event){
                       // Internet Explorer
            	       if (event.srcElement) element_id = event.srcElement.getAttribute("id");
            	       // W3C DOM
            	       if (event.currentTarget) element_id =event.currentTarget.getAttribute("id");
            	       $(element_id).style.background="#C5E3EC";
                    };
    var refocus = function(event){
                    // Internet Explorer
            	       if (event.srcElement) element_id = event.srcElement.getAttribute("id");
            	       // W3C DOM
            	       if (event.currentTarget) element_id =event.currentTarget.getAttribute("id");
            	       $(element_id).style.background="#FFFFFF";
                    };
    //set bgcolor for input text filed
    var inputElem = document.getElementsByTagName("input");
    
	 for (var i=0; i<inputElem.length; i++){
                 if(inputElem[i].type == "text"){
		   //inputElem[i].className = "textfield";
		   addEvent(inputElem[i], "focus", focus, false);
		   addEvent(inputElem[i], "blur", refocus, false);
		}else if (inputElem[i].type == "password"){
		  //inputElem[i].className = "textfield";
                   addEvent(inputElem[i], "focus", focus, false);
		   addEvent(inputElem[i], "blur", refocus, false);
		}else if(inputElem[i].type == "submit" || inputElem[i].type == "button"  || inputElem[i].type == "reset" ){
		  //inputElem[i].className = "textfield";
		}
	 }
     //set bgcolor for input textarea
     var textareaElem = document.getElementsByTagName('textarea'); 
      if(textareaElem){
        for (var i=0; i<textareaElem.length; i++){
                addEvent(textareaElem[i], "focus", focus, false);
		addEvent(textareaElem[i], "blur", refocus, false);
	 }
       }
    //set bgcolor for select
      var selectElem = document.getElementsByTagName('select'); 
      if(selectElem){
      for (var i=0; i<textareaElem.length; i++){
                addEvent(selectElem[i], "focus", focus, false);
		addEvent(selectElem[i], "blur", refocus, false);
	 }
       }
}	 

var data_table_listener = function(){
    // change the style of text field element on focus
    var focus = function(event){
                       // Internet Explorer
            	       if (event.srcElement) element_id = event.srcElement.getAttribute("id");
            	       // W3C DOM
            	       if (event.currentTarget) element_id =event.currentTarget.getAttribute("id");
            	       $(element_id).style.color="#1B1B1B";
                    };
    var refocus = function(event){
                    // Internet Explorer
            	       if (event.srcElement) element_id = event.srcElement.getAttribute("id");
            	       // W3C DOM
            	       if (event.currentTarget) element_id =event.currentTarget.getAttribute("id");
            	       $(element_id).style.color="#000000";
                    };
    //set bgcolor for input text filed
    var inputElem = document.getElementsByTagName("input");
	 for (var i=0; i<inputElem.length; i++){
		if(inputElem[i].type == "text"){
		   //inputElem[i].className = "textfield";
		   addEvent(inputElem[i], "focus", focus, false);
		   addEvent(inputElem[i], "blur", refocus, false);
		}else if (inputElem[i].type == "password"){
		  //inputElem[i].className = "textfield";
		}else if(inputElem[i].type == "submit" || inputElem[i].type == "button"  || inputElem[i].type == "reset" ){
		  //inputElem[i].className = "textfield";
		}
	 }

	//set bgcolor for textarea
	inputElem = document.getElementsByTagName("textarea");
	 for (var i=0; i<inputElem.length; i++){
		  // inputElem[i].className = "textfield";
		   addEvent(inputElem[i], "focus", focus, false);
		   addEvent(inputElem[i], "blur", refocus, false);
	 }

	 //set bgcolor for select
	 inputElem = document.getElementsByTagName("select");
	 for (var i=0; i<inputElem.length; i++){
		  //inputElem[i].className = "textfield";
		   addEvent(inputElem[i], "focus", focus, false);
		   addEvent(inputElem[i], "blur", refocus, false);
	 }
}

/* addEvent()
*  Description: adds event to an Element (label, span, input) dynamically
*  Parameters: obj, eventType, afunction, isCapture=false
*/
function addEvent(obj, eventType, afunction, isCapture) {
  // W3C DOM
  if (obj && obj.addEventListener) {
   obj.addEventListener(eventType, afunction, isCapture);
   return true;
  }
  // Internet Explorer
  else if (obj && obj.attachEvent) {
   return obj.attachEvent("on"+eventType, afunction);
  }
  else return false;
 }


/* formCallback()
*  description: call back function for
*               validation.js
*/
function formCallback(result, form) {
	//if(result)
	//document.getElementById("error_message").innerHTML = "";
}

function formReset(){
    //clear server side error message if any
    if($("error_message"))
        {
            $("error_message").innerHTML = "";
            $("error_message").style.display = "none";
        }

    // clear text field values if any
    if($('data_table')){
         var inputList = $('data_table').getElementsByTagName('input');
            if(inputList){
            for(var i=0; i<inputList.length-1; i++)
                if(inputList[i].type=="text")inputList[i].value = "";
                if(inputList[i].type=="password")inputList[i].value = "";
             }

            inputList = $('data_table').getElementsByTagName('textarea');
            if(inputList){
            for(var i=0; i<inputList.length; i++)
                inputList[i].value = "";
             }

    }

}

/** args[0] - element to show
*   args[1].args[2].... - element to hide
**/
function toggle_element(){
    var args = toggle_element.arguments;
    new Effect.Appear(args[0], {duration: 0.3 });
    if(args[1]!=null){
        elements_to_hide = args[1];
        for(var i=0; i<=elements_to_hide.length-1; i++)
            {
                if ($(elements_to_hide[i]))
                    new Effect.Fade( elements_to_hide[i], {duration: 0.0 });
            }
    }
}

function checkNumbers(evt){
    var keynum;
    var keychar;
    var numcheck;

    if (window.event){
        keynum = evt.keyCode;
    }else if (evt.which){
        keynum = evt.which;
    }
    keychar = String.fromCharCode(keynum);
    //numcheck = /[a-zA-Z_\~\s\!\@\#\$\%\^\&\*\(\)\+]/;
   numcheck = (/[\s`~!@#\$\^%*&\_\-\|\"\:\;\{\}\[\]\<\>\?\/\.\,'\(\)\+\\=a-zA-Z]/);
    return !numcheck.test(keychar);
}

function checkName(evt){
    var keynum;
    var keychar;
    var numcheck;

    if (window.event){
        keynum = evt.keyCode;
    }else if (evt.which){
        keynum = evt.which;
    }
    keychar = String.fromCharCode(keynum);
    numcheck = (/[\s`~!@#\$\^%*&\_\-\|\"\:\;\{\}\[\]\<\>\?\/\.\,'\(\)\+\\=0-9]/);
    return !numcheck.test(keychar);
}
/* This validation for city, facility name and edit phone book name and hobbies 
   Allows \s '  and & */
function checkSpecialName(evt){
    var keynum;
    var keychar;
    var numcheck;

    if (window.event){
        keynum = evt.keyCode;
    }else if (evt.which){
        keynum = evt.which;
    }
    keychar = String.fromCharCode(keynum);
    numcheck = (/[`~!@#\$\^%*\_\-\|\"\:\;\{\}\[\]\<\>\?\/\.\,\(\)\+\\=0-9]/);
    return !numcheck.test(keychar);
}

/* This validation for albumname with space and aplha numeric
   Allows A-Z, 0-9
   */
   function checkAlphaNumericZip(evt){
    var keynum;
    var keychar;
    var numcheck;

    if (window.event){
        keynum = evt.keyCode;
    }else if (evt.which){
        keynum = evt.which;
    }
    keychar = String.fromCharCode(keynum);
    numcheck = (/[\s\'\&\`~!@#\$\^%*\_\-\/\|\"\:\;\{\}\[\]\<\>\?\.\(\)\+\\=]/);
    return !numcheck.test(keychar);
}

/* This validation for albumname with space and aplha numeric
   Allows \s,',&,a-z,0-9
   */
   function checkAlphaNumeric(evt){
    var keynum;
    var keychar;
    var numcheck;

    if (window.event){
        keynum = evt.keyCode;
    }else if (evt.which){
        keynum = evt.which;
    }
    keychar = String.fromCharCode(keynum);
    numcheck = (/[`~!@#\$\^%*\_\-\/\|\"\:\;\{\}\[\]\<\>\?\.\(\)\+\\=]/);
    return !numcheck.test(keychar);
}


/* This validation for city, facility name and edit phone book name and hobbies 
   Allows \s, ',/,-,,  and & */
function checkSpecialChar(evt){
    var keynum;
    var keychar;
    var numcheck;

    if (window.event){
        keynum = evt.keyCode;
    }else if (evt.which){
        keynum = evt.which;
    }
    keychar = String.fromCharCode(keynum);
    numcheck = (/[`~!@#\$\^%*\_\-\/\|\"\:\;\{\}\[\]\<\>\?\.\(\)\+\\=0-9]/);
    return !numcheck.test(keychar);
}

/* This validation for user name, It Allows alpha -numeric char . - _*/
function checkUserName(evt){
    var keynum;
    var keychar;
    var numcheck;

    if (window.event){
        keynum = evt.keyCode;
    }else if (evt.which){
        keynum = evt.which;
    }
    keychar = String.fromCharCode(keynum);
    numcheck = (/[\s`~!@#\$\^%*&\|\"\:\;\{\}\[\]\<\>\?\/\,'\(\)\+\\=]/);
    return !numcheck.test(keychar);
}
function checkEmailId(evt){
    var keynum;
    var keychar;
    var numcheck;

    if (window.event){
        keynum = evt.keyCode;
    }else if (evt.which){
        keynum = evt.which;
    }
    keychar = String.fromCharCode(keynum);
    numcheck = (/[\s`~!#\$\^%*&\|\"\:\;\{\}\[\]\<\>\?\/\,'\(\)\+\\=]/);
    return !numcheck.test(keychar);
}
function updateimage(go_id){
    div_id = go_id
    image_id = "img_"+go_id
    if ($(div_id).innerHTML == "check")
        $(image_id).src = "/images/checked.gif";
    else if ($(div_id).innerHTML == "uncheck")
        $(image_id).src = "/images/unchecked.gif";

}

/*
function addUserContact()
{
	var args = addUserContact.arguments;
	var tbl = $(args[0]);
	var newRow = tbl.insertRow(tbl.rows.length);
	var count = newRow.rowIndex-1;
	newRow.setAttribute('id', 'txtRow' + newRow.rowIndex);

	var newCell = "newCell_"+count ;
	newCell = newRow.insertCell(0);
	newCell.innerHTML = 
        "<table cellpadding='1' cellspacing='0' width='100%'  >"+
        "<tr>"+
        "<th>First Name </th>"+
        "<th>M.I.</th>"+
        "<th>Last Name </th>"+
        "</tr>"+
        "<tr>"+
        "<td><input id='first_name[]' name='first_name[]' type='text' class='textfield' size='22' maxlength='22'></td>"+
        "<td><input id='last_name[]' name='last_name[]' type='text' class='textfield'  size='22' maxlength='22'></td>"+
        "</tr>"+
        "<tr>"+
        "<th colspan='2'>Email Address</th>"+
        "<th>Phone Number</th>"+
        "<th></th>"+
        "</tr>"+
        "<tr>"+
        "<td colspan='2'><input maxlength='33' size='33' id='email_address[]' name='email[]' type='text' class='emailfield' ></td>"+
        "<td colspan='2'>"+
        "(<input type='text' size='3' onkeypress='return checkNumbers(event)' id='phone_first[]' name='phone_first[]' maxlength='3' class='phone'/>)"+
        "<input type='text' size='3' onkeypress='return checkNumbers(event)' id='phone_middle[]' name='phone_middle[]' maxlength='3' class='phone'/>-"+
        "<input type='text' size='4' onkeypress='return checkNumbers(event)' id='phone_last[]' name='phone_last[]' maxlength='4' class='phone'/>"+
        "</td>"+
        "</tr>"+
        "</table>"+
        "<div style='float:right;position:relative;right:150px;top:-20px;'  onclick=$('"+args[0]+"').deleteRow(this.parentNode.parentNode.rowIndex); ><img src='/images/delete.gif' alt='Delete this row' /></div>"+
        "<hr class='divider'/>";


}*/

/******************* family and friend ************/
    function chkbox(formObj, obj){
	   field = formObj.senior_id
	   if(typeof(field.length)== "undefined")
        {
    	     if(formObj.senior_id.checked == true )
    	       {
                    //$("invite_tbs").disabled = false; 
            	    $("save").disabled = false;
            	    $("save").className = "survey_button";
               }
             else
              {
            	   //$("invite_tbs").disabled = true; 
        	       $("save").disabled = true;
        	       $("save").className = "survey_button_disabled";
              }
    	  }
	  else {
    	   field_loop:
    	   for (i = 0; i < field.length; i++){
            	if(field[i].checked == true ){
                   // $("invite_tbs").disabled = false; 
            	    $("save").disabled = false;
            	    $("save").className = "survey_button";
            	    break field_loop;
            	 }else {
            	  // $("invite_tbs").disabled = true; 
        	       $("save").disabled = true;
        	       $("save").className = "survey_button_disabled";
            	 }
            }
        }
	}
	
	function showaddform()
	{	
		if( $("add_new_contacts") && $("add_new_contacts").style.display=="none")
			{
			$("add_new_contacts").style.display="block";
			$("add_contact").style.display = "none";
			window.scrollBy(0,2000)
			}
		else if( $("add_new_contacts") && $("add_new_contacts").style.display=="block")
		{
			$("add_new_contacts").style.display = "none"
			$("add_contact").style.display = "block";
		}
	}
	
	
function showSendEmail(){
    txt = '<div style="margin-left:25px;"><div style="display:inline">Sending Email..</div>'+
         '<div style="display:inline"><img src="/images/ajax-loader-email.gif" border=0 /></div></div>';
     $('statusbar').innerHTML= txt;
}

function resetModalDialog(){
    $('modal_dialog').style.top = '45%';
    $('modal_dialog').style.left = '50%';
}

function displaypopupblock(){
    $('modeloverlay').style.display = 'block';
}

function check_radio(obj, count_value )
{
        formobj = obj.form;
        radioObj = formobj.getElementsByTagName("button")
	for(var i=0; i<radioObj.length; i++){
		if(radioObj[i]==obj) { radioObj[i].className = "checked";}
		else if(radioObj[i].name==obj.name) radioObj[i].className = "unchecked";
	}	
	$("hidden_answer_"+count_value).value = obj.value;
}
function toggle_image(family_ref,senior_ref){
    if ($("hidden_answer_1").value == "family") {
        $(family_ref).src ="/images/daughter_green_ds.png"
        $(senior_ref).src ="/images/signup_sr_icon_off.png"
    }else {
        $(family_ref).src ="/images/daughter_ds.png"
        $(senior_ref).src ="/images/signup_sr_icon.png"
    }
}
/*function clear_all_checkbox(){
    id_list = $("collect_all_checked_id").innerHTML;
    if(id_list.split(",").length>0){
        id_list = id_list.split(","); 
        for(var i=0; i<id_list.length; i++) {
           if( $("img_"+id_list[i]))  $("img_"+id_list[i]).src = "/images/unchecked.gif";
        }
    }
}*/
function clear_all_checkbox(){
    $("display_favourites").getElementsByTagName("img")
    var img = $("display_favourites").getElementsByTagName("img") //document.getElementsByTagName("img")
    for(var i=0; i<img.length; i++){
      var nimg  = img[i].src.toString()
      uncheckImage = new RegExp(/unchecked.gif/); 
      checkImage = new RegExp(/checked.gif/);
      if(uncheckImage.test(nimg) || checkImage.test(nimg))
      {
        if(!uncheckImage.test(nimg))img[i].src = "/images/unchecked.gif";
      }
   }

}

function set_focus(){   
    $("user_contact_contact_first_name").focus();
}

function clearSelection() {
   var sel ;
   if(document.selection && document.selection.empty){
     document.selection.empty() ;
   } else if(window.getSelection) {
     sel=window.getSelection();
     if(sel && sel.removeAllRanges)
         sel.removeAllRanges() ;
   }
} 

function read_this_message(folder,messageid,page){
    	window.location="../webmail/read_message?folder_name="+folder+"&msg_id="+messageid+"&page="+page
}

function getEmailCount()
{
	var oXmlHttpClientServer = new XMLHttpRequest();
	if (oXmlHttpClientServer.readyState == 4 || oXmlHttpClientServer.readyState == 0)
			{
			  oXmlHttpClientServer.open("POST", "/webmail/getemailcount", true);			
			  oXmlHttpClientServer.onreadystatechange = function()
				{
				  if (oXmlHttpClientServer.readyState == 4)
				  {
				   // only if HTTP status is "OK"
				   
				   if (oXmlHttpClientServer.status == 200)
				   {
				     var response = oXmlHttpClientServer.responseText;
					     if(response != -1)
					     	$("emailcount").innerHTML = response;
				     window.setTimeout(getEmailCount,300000);
				   }
				    //else 
				    //alert("URL doesn't exist!\n\n" + oXmlHttpClientServer.status); 
				    //if (oXmlHttpClientServer.status==404) 
				  }	
			        }
              dummyparameter = 0;
			  oXmlHttpClientServer.send(dummyparameter);
			}
}

/*
ex: , :onkeypress => "return disableEnterKey(event, 'subject_field');"
    , :onkeypress => "return disableEnterKey(event, 'to_field');"
function disableEnterKey(e, objname)
{
     var key;
     if(window.event)
          key = window.event.keyCode;     //IE
     else
          key = e.which;     //firefox
     if(key == 13){
           switch (objname) {
            case "to_field": document.forms[0].mail_subject.focus(); break;
            case "subject_field": document.forms[0].bodytextarea.focus(); break;
            }
           return false;
     }
     else
          return true;
}*/


/***
** Below method to satisfy 3 conditions
** Drop CR for sending email - Unless User clicks "Send" button, form will not be submitted
** Prevent partial names show up in "TO" field - Fixed
** User can press the CR to naviagte between fields 
**/
function disable_enterKey_to_field(e)
{
      var key;
         if(window.event)
              key = window.event.keyCode;     //IE
         else
              key = e.which;     //firefox
              
     if( ($("mail_to_auto_complete")) && ($("mail_to_auto_complete").style.display!="none") )
     {
         if(key == 13) return false;
         else return true;
     } else if( ($("mail_to_auto_complete")) && ($("mail_to_auto_complete").style.display=="none") ){
        if(key == 13) {
            document.forms[0].mail_subject.focus();
            return false;
        }
         else return true;
     } else {
        return true;
     }
}

function disable_enterKey_subject_field(e){
    var key;
         if(window.event)
              key = window.event.keyCode;     //IE
         else
              key = e.which;     //firefox
         if(key == 13) {
            document.forms[0].bodytextarea.focus();
            return false;
        }
         else return true;
}

//This function is written for compose page make data persistent 
//User enter some thing if they click on others then show a popup prompt message to discard message
 function check_for_data(){
       //We are not calling this function unneccessarily if user not in the write mail scope
        if(typeof($("mail_to"))!= "undefined"){
         var args = check_for_data.arguments;
                controller_name = args[0];
                action_name = args[1];
                if(args[2])folder_name = args[2]; else folder_name ="";
                //Check for white spaces where nothing is entered just white spaces only.                
                reWhiteSpace = new RegExp(/^\s+$/);
            if( (!(reWhiteSpace.test($("mail_to").value)) && $("mail_to").value!="") || 
                (!(reWhiteSpace.test($("mail_subject").value)) && $("mail_subject").value!="")  || 
                (!(reWhiteSpace.test($("bodytextarea").value)) && $("bodytextarea").value != ""))
                {    // get the controller and action name from where it is called
                    // open ajax pop
                    new Ajax.Updater('modal_dialog', '/webmail/confirm_dialog?message=confirm_dialog_discard&controller_name='+controller_name+'&action_name='+action_name+'&folder_name='+folder_name,
                   {
                    asynchronous:true,
                    evalScripts:true,
                    onSuccess:function(request){
                         overlayToggle('block');
                         new Effect.BlindDown( 'modal_dialog', {duration: 0.0 });
                     } } );
            
                return false;
            }
       }else 
            return true;

 }
 

function check_upload_image_type()
	{       var valid =false;
	        var imagePath = $("user_file_data").value;
	        reWhiteSpace = new RegExp(/^\s+$/);
	       // image_validate= new RegExp(/.(gif|jpg|png|bmp|GIF|JPG|PNG|BMP)$/); 
                image_validate = new Array("gif","jpg","png","bmp","jpeg","GIF","JPG","PNG","BMP","JPEG")
	        if( !(reWhiteSpace.test($("user_file_data").value)) &&( $("user_file_data").value!='') )
			{ 
                          image_format =($("user_file_data").value).split(".").last()
			if (image_validate.grep(image_format) != '') valid = true;
		   }
		   if (valid == false )	{
		   	$('upload_image').style.display = 'block';
                        imagePath = $("user_file_data").value = "";
		   	return false;
		   }  
		   else {
		   return true;
		   }
		   
	}  
function setMaxLength() {
	var x = document.getElementsByTagName('textarea');
	var counter = document.createElement('div');
	counter.className = 'counter';
	for (var i=0;i<x.length;i++) {
		if (x[i].getAttribute('maxlength')) {
			var counterClone = counter.cloneNode(true);
			counterClone.relatedElement = x[i];
			counterClone.innerHTML = '<span>0</span>/'+x[i].getAttribute('maxlength');
			x[i].parentNode.insertBefore(counterClone,x[i].nextSibling);
			x[i].relatedElement = counterClone.getElementsByTagName('span')[0];

			x[i].onkeyup = x[i].onchange = checkMaxLength;
			x[i].onkeyup();
		}
	}
}

function checkMaxLength() {
	var maxLength = this.getAttribute('maxlength');
	var currentLength = this.value.length;
	if (currentLength > maxLength)
		this.relatedElement.className = 'toomuch';
	else
		this.relatedElement.className = '';
	this.relatedElement.firstChild.nodeValue = currentLength;
	// not innerHTML
}

 function cursor_focus_on_attachment_window(){
     if ($('title').value=='') $('title').focus();
     if ($('title').value!='') $('description').focus();
   }
   
function setcurrentfocus()
    {
            overlayToggle('block');
    $('ajax-loader').style.display='block';
    }

 function check_valid_file_format(form){
     
    var file = new Array();
    typeName = "file" 
    var inputs = form.getElementsByTagName("input")
    
     for (var i = 0; i < inputs.length; i++) {
      var input = inputs[i];
      if (input.type == typeName){
           file.push(input) 
      }
      
      
    }
    
    
    //file = $('file_field').getElementsByClassName('file_field');
    //image_validate= new RegExp(/.(gif|jpg|png|bmp|GIF|JPG|PNG|BMP)$/);
    image_validate = new Array("gif","jpg","png","bmp","jpeg","GIF","JPG","PNG","BMP","JPEG")
    emptyList = new Array() ;
    imgList = new Array();
    non_imageList = new Array();
    for(var i=0; i<file.length; i++){
            if(file[i].value.toString()==""){
                emptyList.push(i)
            }else if  (file[i].value.toString()!="") {
                 image_format =(file[i].value).split(".").last()
            if (image_validate.grep(image_format) != '')  {
                imgList.push(file[i].value) 
            }else{
               non_imageList.push(file[i].value)  
               var item = i+1
                alert("Item ---->"+item+ "       "+file[i].value.split("\\").last()+" file is invalid image format."); 
                return false;
            }
       }   
       }
//   alert(file.length +"\n" +emptyList.length +"\n" +imgList.length +"\n" +non_imageList.length )
   if(emptyList.length == file.length){
        alert("Please upload proper image format."); 
        return false;
   }
   
   if((imgList.length!=0) && (non_imageList.length==0)){
        setcurrentfocus();
        return true;
   }else {
     alert("Please upload proper image format."); 
     return false;
   }
 }
 
 function check_valid_file_format_senior(form){
     
    var file = new Array();
    typeName = "file" 
    var inputs = form.getElementsByTagName("input")
    
     for (var i = 0; i < inputs.length; i++) {
      var input = inputs[i];
      if (input.type == typeName){
           file.push(input) 
      }
    }
    //file = $('file_field').getElementsByClassName('file_field');
    //image_validate= new RegExp(/.(gif|jpg|png|bmp|GIF|JPG|PNG|BMP)$/);
    image_validate = new Array("gif","jpg","png","bmp","jpeg","GIF","JPG","PNG","BMP","JPEG")
    emptyList = new Array() ;
    imgList = new Array();
    non_imageList = new Array();
    for(var i=0; i<file.length; i++){
            if(file[i].value.toString()==""){
                emptyList.push(i)
            }else if  (file[i].value.toString()!="") {
                 image_format =(file[i].value).split(".").last()
            if (image_validate.grep(image_format) != '')  {
                imgList.push(file[i].value) 
            }else{
               non_imageList.push(file[i].value)  
               var item = i+1
//                alert("Item ---->"+item+ "       "+file[i].value+" file is invalid \n"+"Please upload proper image format."); 
//                return false;
                $("divUploadImage_text").innerHTML = "Upload Photo "+item+ "       "+file[i].value.split("\\").last()+"  is invalid image format."
                return sendEvent("divUploadImage", "displayPopup");
            }
       }   
       }
//   alert(file.length +"\n" +emptyList.length +"\n" +imgList.length +"\n" +non_imageList.length )
   if(emptyList.length == file.length){
       // alert("Please upload proper image format."); 
       // return false;
       $("divUploadImage_text").innerHTML = "Please upload proper image format."
        return sendEvent("divUploadImage", "displayPopup");
   }
   
   if((imgList.length!=0) && (non_imageList.length==0)){
        setcurrentfocus();
        return true;
   }else {
    $("divUploadImage_text").innerHTML = "Please upload proper image format."
    return sendEvent("divUploadImage", "displayPopup");
   }
 }
 
 function toggle_link_title(cur_div,obj) {
        if( $(cur_div) && $(cur_div).style.display=="block"){
			$(cur_div).style.display = "none"
			obj.innerHTML='Show latest'
		}	
		else
		{
			$(cur_div).style.display = "block"
    		obj.innerHTML='Hide'
		}
}

function validate_image_file_format(form, fileid){
    image_validate = new Array("gif","jpg","png","bmp","jpeg","GIF","JPG","PNG","BMP","JPEG")
    imgfile = $(fileid).value.replace(/^\s*|\s*$/g,'');
//    alert(imgfile +"\n "+image_validate.test(imgfile));
    if (imgfile!="") {
       
       image_format =($(fileid).value).split(".").last()
        if (image_validate.grep(image_format) == '')  {
        alert("Please upload proper image format."); 
        return false;
    }
    }else return true;
}

function check_for_relation(form, relation){
    if ($(relation).value =="") {
       alert("Please select the relation."); 
        return false; 
    }else return true;
}

/*function strip(str){
    return str.replace(/^\s*|\s*$/g,'');
}*/
function strip(str)
{
    if(!str || typeof str != 'string')
        return null;

    return str.replace(/^[\s]+/,'').replace(/[\s]+$/,'').replace(/[\s]{2,}/,' ');
}

/****
* below methods are written for  V2.5
*/
function dispatch_event_to(id){
   var clickevent=document.createEvent("MouseEvents")
    clickevent.initEvent("click", true, true)
    $(id).dispatchEvent(clickevent) 
}
function send_message(){dispatch_event_to("send_message")  }
function cancel_message(){dispatch_event_to("cancel_message") }
function check_new_message(){ overlayToggle('block');$('ajax-loader').style.display='block';}
function empty_trash(){dispatch_event_to("empty_trash") }
function add_new_address(){dispatch_event_to("add_new_address")}
function slideshow(){dispatch_event_to("slideshow_button") }
function homepage_album(){dispatch_event_to("homepage_album") }
function contexthelp(){dispatch_event_to("contexthelp") }

/* album prev next */
function page_previous(){dispatch_event_to("page_previous") }
function page_next(){dispatch_event_to("page_next") }

/* close bookmark dialog */
function bookmark(){dispatch_event_to("bookmark") }
function add_album(){dispatch_event_to("add_album") }

function taf_return(){dispatch_event_to("TAFReturn")}

function forward_to(frm, fromwhere){
    if ($("compose_status").innerHTML == "success") {
        $("compose_status").innerHTML = "";
        $("mail_to").value='';
        $("mail_subject").value='';
        $("bodytextarea").value='';
        if(fromwhere=="taf") {sendEvent("divEvent", "TAFReturn") ; }//window.location.href = "/senior/index";
        else if(fromwhere!="write_mail") window.location.href = "/webmail/inbox?folder_name=INBOX";
    }
}

function check_valid_relation(form){
    var invaild_selection = false; 
    var file = new Array();
    typeName = "checkbox" 
    var inputs = form.getElementsByTagName("input")
    
    for (var i = 0; i < inputs.length; i++) {
        var input = inputs[i];
        if (input.type == typeName && input.checked ){
            file.push(input) 
        }
    }
    if(file.length==0)
        {
            alert("Please select any one of the checkbox");
            invaild_selection = true;
        }
        else
            {
                for (var i = 0; i < file.length; i++) {
                    var input = file[i];
                    selected = $("relation_relation_id_"+input.value).value
                    if (selected == 0) {
                        alert("Please select relation");
                        invaild_selection = true;
                        break;
                    }
                }
            }
            if (!invaild_selection){
                if (confirm('Do you want to add selected user as family member?'))return true;
                else return false;
            }
            else return false;
        }
        
 
function invite_accept_reject(senior_id){
    selectBox = "relation_relation_id_"+senior_id
    anchorTag = "span_relation_id_"+senior_id
    if(!$(selectBox).disabled){
       $(selectBox).disabled=true
       $(anchorTag).innerHTML="Accept Invite"
    }else{
        $(selectBox).disabled=false
        $(anchorTag).innerHTML="Reject Invite"  
    }

    new Effect.Shake( selectBox, {duration: 0.1 });
    return false
}

    
/* hack for stying file upload button */
function fillFileField(thisObj, visField){$(visField).value= thisObj.value;}

/* hack to display non-image from rss feed */
function checkImage(obj,url) 
  { 
  var img = new Image; 
  img.onerror = img_onError(obj); 
  img.src = url; 
  } 

  function img_onError(obj)
  {
    obj.alt = "Image not available" 
  }
  
   function set_form_display(type, state){  
        if(type=="primary_user"){
          $('div_primary_user').style.display="block";
          $('div_primary_family').style.display="none";
          $('div_senior').style.display="none";
          $('div_family').style.display="none";
        }
        if(type=="primary_family"){
           $('div_primary_user').style.display="none";
          $('div_primary_family').style.display="block";
          $('div_senior').style.display="none";
          $('div_family').style.display="none";
        }
        if(type=="senior"){
           $('div_primary_user').style.display="none";
          $('div_primary_family').style.display="none";
          $('div_senior').style.display="block";
          $('div_family').style.display="none";
        }
        if(type=="family"){
           $('div_primary_user').style.display="none";
          $('div_primary_family').style.display="none";
          $('div_senior').style.display="none";
          $('div_family').style.display="block";
        }  
    }//fun end

    function checkPrimaryUser(value){
      if($('new_user_primary_user_type').value=="senior"){
        checkUser = new RegExp(/FamilyAndFriend/);
        if(checkUser.test(value)){
            $('relation_with_user').style.display = "block";
          }
          else {
            $('relation_with_user').style.display = "none";
          }
        }
      }


      function showSeniorList(obj){
        if($('new_user_primary_user_type').value=="family"){
          checkFamily = new RegExp(/FamilyAndFriend/);
          checkUser = new RegExp(/Senior/);
          if(checkFamily.test(obj.options[obj.selectedIndex].text)) {
            var subscriptionId =obj.options[obj.selectedIndex].value
            $('relation_with_user').style.display = "block";
            new Ajax.Updater('', '/facility/list_of_seniors?subscriptionId='+subscriptionId,{ asynchronous:true,evalScripts:true} );
          }  
          if(checkUser.test(obj.options[obj.selectedIndex].text)){ 
            $('show_senior_list').hide();
            }
          
          }
        }

function set_compose_form(){
      var args = set_compose_form.arguments;
      if(args[0]!=null && args[0]=="start"){
          mail_senior_id = args[1]
          mail_to = args[2]
          mail_to_name = args[3]
          mail_from = args[4]
         $('mail_from').value = mail_from;
         $('mail_to').value = mail_to;
         $('mail_senior_id').value = mail_senior_id;
         $('to_name').innerHTML = mail_to_name;
         $('mail_subject').value = "";
         new Effect.Appear('compose_modal_dialog', {duration: 0.0 });
         overlayToggle('block');
      }else {
         $('mail_body').value = "";
         $('error_message').style.display = 'none';
         new Effect.Fade('compose_modal_dialog', {duration: 0.0 });
         overlayToggle('none');
        // $('status_message').style.display = 'none';
      }
     
}

function set_column_height_for_ff(){
    if($("right_column").offsetHeight<=620){
    $("right_column").style.height = 0;
    $("right_column").style.height = 640+"px"; }
  }
  
// Prepare the UI for admin when he wants to create a Free Trial signup
function createFreeTrial(e) {
    eventSource = Event.findElement(e, 'input');
    if (eventSource.checked) {
        var reference = $('signup_url_reference');
        reference.value = "";
        reference.disabled = true;
        $('signup_url_reference_label').setStyle({color:'#cccccc'});
        var pageTitle = $('signup_url_page_title');
        pageTitle.value = "Sign up for a free 30-day trial account.";
    }else{
        var reference = $('signup_url_reference').disabled = false;
        $('signup_url_reference_label').setStyle({color:'#333333'});
        var pageTitle = $('signup_url_page_title').value = "";
    }
}

function toTop(){window.scrollTo(0, 0)}

function getUserReportsFor(critieria, controller) {
//    Element.show('report_status');
    $("report_data").innerHTML = "<div class='dataProcessExplanation' id='dataProcessExplanation' style='margin:10px 0px 0px 100px;' >Getting data... Please wait!</p></div>"
    new Ajax.Updater("report_data", "/" + controller + "/new_users_report_delta/"+critieria)
}

/* bookmark js*/
function checkFormFields(){
    name = strip($("bookmark_name").value);
    url = strip($("bookmark_url").value);
    description = strip($("bookmark_description").value);
    if(url==null || url =="" || name==null || name==""){
         $("bookmark").innerHTML = "Please enter all mandatory fields."
          return sendEvent("div_bookmark_status", "displayPopup");//false;
     } else if($("bookmark_description").value.length>255){
          $("bookmark").innerHTML = '<b>"Description"</b> should not exceed 255 characters.'
          return sendEvent("div_bookmark_status", "displayPopup");
    } else return true;
 }
 
 
function checkStatus(){
    if(document.getElementById('bookmark_status').innerHTML == "success"){
       document.getElementById('bookmark_status').style.display = "block";
       document.getElementById('bookmark_status').innerHTML = '<div style="position: relative; top: 10px; width: auto; height: 23px; padding-top: 2px;"><img style="margin-top: -13px;" src="/images/done.png?1199858720" class="status-image" alt="Done"/><div class="divStatus"> <span class="helptext">Bookmark updated successfully.</span></div></div>';
       new Effect.Fade( 'modal_dialog', {duration: 0.0 });
       overlayToggle('none');
       return true;
    } else{ 
      document.getElementById('bookmark_status').style.display = "block";
      $('bookmark_status').innerHTML = '<div style="position: relative; top: 10px; width: auto; height: 30px; padding-top: 2px;"><img style="margin-top: -7px;" src="/images/alert_brick.png?1199858721" class="status-image" alt="Alert_brick"/><div class="divStatus"> <span class="helptext"><b>"Name"</b> field should not be empty.</span></div></div>';
      return false;
    }
}
function edit_bookmark(){
    if(document.getElementById('bookmark_status').innerHTML == "success"){
                 window.setTimeout("new Effect.toggle( 'enlarge_modal_dialog', 'slide');overlayToggle('none');", 2500);
                 $("update").innerHTML = "Bookmark updated successfully."
                 return sendEvent("divUpdate", "displayPopup");//false;
            } else{
              document.getElementById('bookmark_status').style.visibility = "visible";
              $('bookmark_status').innerHTML = '<div style="position: relative; top: 10px; width: auto; height: 30px; padding-top: 2px;"><img style="margin-top: -7px;" src="/images/alert_brick.png?1199858721" class="status-image" alt="Alert_brick"/><div class="divStatus"> <span class="helptext">"Name" field should not be empty.</span></div></div>';
              return false;
            }
        }
        
function edit_ff_bookmark(){
    if(document.getElementById('bookmark_status').innerHTML == "success"){
                 window.setTimeout("new Effect.toggle( 'enlarge_modal_dialog', 'slide');overlayToggle('none');", 2500);
                 $("update").innerHTML = "Bookmark copied successfully."
                 return sendEvent("divUpdate", "displayPopup");//false;
            } else{
              document.getElementById('bookmark_status').style.visibility = "visible";
              $('bookmark_status').innerHTML = '<div style="position: relative; top: 10px; width: auto; height: 30px; padding-top: 2px;"><img style="margin-top: -7px;" src="/images/alert_brick.png?1199858721" class="status-image" alt="Alert_brick"/><div class="divStatus"> <span class="helptext">"Name" field should not be empty.</span></div></div>';
              return false;
            }
        }        

function clientCallback(html)
{
	document.getElementById("statusPane").innerHTML = html;
}

function sendEvent(eleNm, evtNm)
{
	var e = document.getElementById(eleNm);
	if (e && ("createEvent" in document))
	{
	  e.setAttribute("oncommand", evtNm);
	  var evt = document.createEvent("Events");
	  evt.initEvent("BigScreenEvent", true, false);
	  e.dispatchEvent(evt);
	}
	
	return false;
}

function changeVariables(e) {
    var target = sourceElement(e);
    document.getElementsByClassName('target_user_types').each(function(s){
        s.hide();
    });
    $(target).show();
}

function toggleMsgFormatting() {
    var link = $('format_msg_link');
    var targetUserType = $("target_user").value;
    link.blur();
    if (targetUserType == "" || targetUserType == undefined) {
        alert("Please select the target user type.");
        new Effect.Highlight('target_user', {duration: 2});
        return;
    }
    var txt = link.innerHTML;
    var rawMsgContainer = $('message_text');
    var rawMsg = $("message_message");
    
    if (txt == "Show formatted message") {
        
        $('rawMsgMarkup').update(rawMsgContainer.innerHTML);
        $('rawMsg').update(rawMsg.value);
        
        new Ajax.Updater('message_text', '/messages/formatted', {
            method: "post",
            parameters: Form.serialize('new_message_form')
        });
        
        if ($('msgFormSubmitButton')) {
            link.update("Resume editing");
            $('msgFormSubmitButton').disabled = 'true';
        } else {
            link.update("Back to unformatted message");
        }
    } else {
        link.update("Show formatted message");
        rawMsgContainer.update($('rawMsgMarkup').innerHTML);
        $("message_message").value = $('rawMsg').innerHTML;
        if ($('msgFormSubmitButton')) $('msgFormSubmitButton').disabled = '';
    }
}

// Toggles the visibility of subject text box in "New/Edit Message" dialog
function toggleSubject(e) {
    var subject = $('message_subject');
    if ($('inline_message').checked) {
        subject.value = "";
        subject.readOnly = true
    } else {
        subject.readOnly = false;
    }
}

function getMessageTriggersFor(planType) {
    $("message_triggers_list").innerHTML = "<div class='dataProcessExplanation' id='dataProcessExplanation' style='margin:10px 0px 0px 100px;' >Getting data... Please wait!</p></div>"
    new Ajax.Updater("message_triggers_list", "/message_triggers/delta/" + planType, {method: 'get'})
}

function getMessageTriggersForPlan() {
    $("triggerList").innerHTML = "<div class='dataProcessExplanation' id='dataProcessExplanation' style='margin:10px 0px 0px 0px;' >Getting data... Please wait!</div>"
    new Ajax.Updater("triggerList", "/message_triggers/trigger_list_for_plan/" + $('message_trigger_plan_id').value, {method: 'get'})
}

function viewMessage() {
    new Ajax.Updater("modal_dialog1", 
    "/messages/" + $('message_trigger_message_id').value, 
    {method: 'get', onSuccess: function(transport){
        overlayToggle('block');
        new Effect.Appear('modal_dialog1', {duration: 0.0} );
    }})
}

// Provides a way to switch to a page that is not associated with the first tab
// of a function/category. In other words, ability to go from the Home page to 
// the Tools My Account page with the proper top tab selected. 
// To do this, you need to send a "BigScreenEvent" event to the client with 
// "oncommand" attribute set to "selectCatAndTopTab", the "cat" attribute set 
// to the function/category (either 'Mail', 'Photos', 'Health', 'Web', 'Shop', 
// 'Tools' or 'Games') and the "url" attribute set to the relative URL 
// of the page. The following code illustrates how this is done given 
// a hidden HTML DIV with the id “evtEle”.

function selectCatAndTopTab(cat, url) {
    var e = document.getElementById("evtEle");
    if (e && ("createEvent" in document)) {
        e.setAttribute("oncommand", "selectCatAndTopTab");   
        e.setAttribute("cat", cat);
        e.setAttribute("url", url);
        var evt = document.createEvent("Events");
        evt.initEvent("BigScreenEvent", true, false);
        e.dispatchEvent(evt);
    }
}

function prohibit_p_h2()//to prohibit unwanted messages during error display
{
    if($("errorExplanation") && $("errorExplanation").getElementsByTagName("p") && $("errorExplanation").getElementsByTagName("p")[0])$("errorExplanation").getElementsByTagName("p")[0].style.display = "none";
    if($("errorExplanation") && $("errorExplanation").getElementsByTagName("h2") && $("errorExplanation").getElementsByTagName("h2")[0])$("errorExplanation").getElementsByTagName("h2")[0].style.display = "none";
}

// Used in admin Manage Subscriptions
function chk_plan_details(){
    if($('hidden_answer_1').value==''){
      $('error_message').innerHTML='<div class="error" style="padding:10px;">Please select a plan to continue!</div>'; 
      return false;
      }
    else 
      return true;    
  }

function iprint(ptarget)
  {
    ptarget.focus();
    ptarget.print();
  }
  var emailDeletePressed = false;
  function check_doubleclick(){
      if (emailDeletePressed) return true;
      else {
          emailDeletePressed = true;
      return false
      }
}