


// This is needed so that submit is clicked that all services, towns, and counties are selected
function selectOptions(list_id)
{
  var list = document.getElementById(list_id);

  for(var i = 0; i < list.options.length; ++i)
  {
    list.options[i].selected = true;
  }
}

function selectOptionsIfNotSelected( list_id )
{
  var is_any_selected = false;
  var list = document.getElementById(list_id);

  for(var i = 0; i < list.options.length; ++i)
  {
    if( list.options[i].selected )
      is_any_selected = true;
  }

  if( !is_any_selected )
    selectOptions( list_id );
}

function selectAllOptions()
{
  selectOptions( 'town_selected_id' );
  selectOptions( 'state_selected_id' );
  selectOptions( 'county_selected_id' );
}

// Declaring required variables
var digits = "0123456789";
// non-digit characters which are allowed in phone numbers
var phoneNumberDelimiters = "()- ";
// characters which are allowed in international phone numbers
// (a leading + is OK)
var validWorldPhoneChars = phoneNumberDelimiters + "+";
// Minimum no of digits in an international phone no.
var minDigitsInIPhoneNumber = 10;

function isInteger(s)
{   var i;
    for (i = 0; i < s.length; i++)
    {
        // Check that current character is number.
        var c = s.charAt(i);
        if (((c < "0") || (c > "9"))) return false;
    }
    // All characters are numbers.
    return true;
}
function trim(s)
{   var i;
    var returnString = "";
    // Search through string's characters one by one.
    // If character is not a whitespace, append to returnString.
    for (i = 0; i < s.length; i++)
    {
        // Check that current character isn't whitespace.
        var c = s.charAt(i);
        if (c != " ") returnString += c;
    }
    return returnString;
}
function stripCharsInBag(s, bag)
{   var i;
    var returnString = "";
    // Search through string's characters one by one.
    // If character is not in bag, append to returnString.
    for (i = 0; i < s.length; i++)
    {
        // Check that current character isn't whitespace.
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }
    return returnString;
}

function checkInternationalPhone(strPhone)
{
  var bracket=3
  strPhone=trim(strPhone)
  if(strPhone.indexOf("+")>1) return false
  if(strPhone.indexOf("-")!=-1)bracket=bracket+1
  if(strPhone.indexOf("(")!=-1 && strPhone.indexOf("(")>bracket)return false
  var brchr=strPhone.indexOf("(")
  if(strPhone.indexOf("(")!=-1 && strPhone.charAt(brchr+2)!=")")return false
  if(strPhone.indexOf("(")==-1 && strPhone.indexOf(")")!=-1)return false
  s=stripCharsInBag(strPhone,validWorldPhoneChars);
  return (isInteger(s) && s.length >= minDigitsInIPhoneNumber);
}

function isUrl(s) {
 	var regexp = /http:\/\/[A-Za-z0-9\.-]{3,}\.[A-Za-z]{3}/;
 	return regexp.test(s);
}


function is_valid_url(url)
{
     return url.match(/^[a-z0-9-\.]+\.[a-z]{2,4}\/?([^\s<>\#%"\,\{\}\\|\\\^\[\]`]+)?$/) || isUrl(url);
}

function is_alpha(str)
{
  return str.match(/^[a-zA-Z]/);
}



// Note: this function is not working in form_validation.js. TODO figure out why.
function checkEmail( email_address )
{
  var str = email_address;
  var is_success = false;
  var filter=/^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;

  if (filter.test(str))
    is_success = true;

  return is_success;
}

function isInteger(s)
{   var i;
  for (i = 0; i < s.length; i++)
  {
      // Check that current character is number.
      var c = s.charAt(i);
      if (((c < "0") || (c > "9"))) return false;
  }
  // All characters are numbers.
  return true;
}

function copytolist(obj_from, obj_to)
{
	var flag		= false; // To check whether value is selected..
	var remove_flag = false; // To check whether value is selected..

	for (i=0;i<obj_from.options.length;i++)
	{
		var curr_option = obj_from.options[i];

		if(curr_option.selected)
		{
			// To display 'Doesn't Matter' if not added anything..
			if(obj_from == document.frm_main.elements['communityarray[]']
			|| obj_from == document.frm_main.elements['mothertonguearray[]']
			|| obj_from == document.frm_main.elements['castearray[]']
			|| obj_from == document.frm_main.elements['occupationarray[]']
			|| obj_from == document.frm_main.elements['residencystatusarray[]']
			|| obj_from == document.frm_main.elements['education_level_array[]']
			|| obj_from == document.frm_main.elements['education_area_array[]']
			|| obj_from == document.frm_main.elements['countryofresidencearray[]']
			|| obj_from == document.frm_main.elements['stateofresidencearray[]'])
			{
				remove_flag = true;
			}

			flag = true;

			var new_option	   = curr_option.text;
			var new_option_val = curr_option.value;

			//Need to put select mothertongue n caste condition bcoz we hv static option files
			//for occupation n residency status.. which doesnt hv value attribute in option tag.
			//so we hv checked text of the option..
			if(new_option != ""
			&& new_option != "----Select Mother Tongue----"
			&& new_option != "---------Select Caste---------"
			&& new_option_val != "")
			{
				// when user selects anything frm left when doesnt matter at right side, overwriting the doesnt matter value.
				// countryofresidence condition is added bcoz.. we can have "" value as 0th option in countryofresidencearray.. so it resets the whole list..
				if(obj_to.options[0] && (obj_to.options[0].text == "Doesn't Matter" || obj_to.options[0].text == "") && obj_from != document.frm_main.elements['countryofresidencearray[]'] )
				{
					obj_to.options.length = 0;

					//If user selected default mothertongues &
					//then when he adds community to nullify preselected mothertongues..
					if(obj_to == document.frm_main.elements['communityarray[]'])
					{
						document.frm_main.elements['mothertonguearray[]'].length = 0;
					}
				}

				if(new_option != "Doesn't Matter")
				{
					obj_to.options[obj_to.length] = new Option(new_option, new_option_val);
				}

				//Removing the option frm the source list n
				//decrementing bcoz now we need to loop thr the new list count
				//if(remove_flag){ // Uncomment if u dont want to remove the val frm left list.
				obj_from.options[i] = null;	//we can use obj_from.remove(i);
				i--; // Used for multiple selection..
				//}
			}

		} // EO if(curr_option.selected)

	} // EO for (i=0;i<obj_from.options.length;i++)

	if(obj_from.options.length == 0 && remove_flag)
	{
		// This is done bcoz, we need " " value for 'Doesn't Matter' option in case of community block only so that
		// we can display default mothertongue list..
		// For other elements we need "" value..
		if(obj_from == document.frm_main.elements['communityarray[]']
		|| obj_from == document.frm_main.elements['mothertonguearray[]']
		|| obj_from == document.frm_main.elements['castearray[]'])
		{
			var value = " ";
		}
		else
		{
			var value = "";
		}

		obj_from.options[0] = new Option("Doesn't Matter", value);
	}

	// This block is used to remove the blank separator between the options in the LHS box
	if(obj_from.options.length > 0 && obj_from.options.length <= 2)
		{
			if(obj_from.options[0].text == "---------Select Caste---------" && obj_from.options.length == 2)
			{
				if(obj_from.options[1].text =="")
				obj_from.options[1] = null;
			}
			else if(obj_from.options.length == 1 && obj_from.options[0].text == "")
			{
				obj_from.options[0] = null;
		}
	}

	if (!flag)
	{
		alert ('Please select the Options');
		return false;
	}

	return true;

} // EO function copytolist(obj_from,obj_to)

function textCounter(field, countfield, maxlimit)
{
    if (field.value.length > maxlimit) // if too long...trim it!
    field.value = field.value.substring(0, maxlimit);
    // otherwise, update 'characters left' counter
    else
    {
      if( countfield != '' )
        countfield.value = maxlimit - field.value.length;
    }
}

function copyContactInfo()
{
  document.frm_main.AddressB.value = document.frm_main.Address.value;
  document.frm_main.CityB.value = document.frm_main.City.value;
  document.frm_main.CountyB.value = document.frm_main.County.value;
    //document.frm_main.StateB.value = document.frm_main.State.value;
  document.frm_main.ZipB.value = document.frm_main.Zip.value;
  document.frm_main.PhoneB.value = document.frm_main.Phone.value;
  document.frm_main.cPhoneB.value = document.frm_main.cPhone.value;
  document.frm_main.FaxB.value = document.frm_main.Fax.value;
  document.frm_main.mailB.value = document.frm_main.mail.value;
  document.frm_main.URLB.value = document.frm_main.URL.value;
}


function validateForm( is_ignore_password )
{
	var Phone=document.frm_main.Phone;
  var Fax=document.frm_main.Fax;
  var CellPhone=document.frm_main.cPhone;
  var Password=document.frm_main.password;
  var Name = document.frm_main.aolcp_first_name;
  var last_name = document.frm_main.aolcp_last_name;
  var Email = document.frm_main.mail;
  var Website = document.frm_main.URL;
  var Zip = document.frm_main.Zip; // member zip
  var validation_message = "";
  var State = document.frm_main.State;
  var City = document.frm_main.City;
  var County = document.frm_main.County;

  // first make sure required fields are there
  if( Name.value.length ==  0 || last_name.value.length == 0 )
    validation_message = "Name is a required field <br/>";
  if( Password.value.length == 0 && is_ignore_password == '0' )
    validation_message += "Password is a required field <br/>";
  if( Email.value.length == 0 )
    validation_message += "Email is a required field <br/>";

	if (Phone.value.length > 0 && checkInternationalPhone(Phone.value)==false){
    validation_message += "Please enter a valid Phone Number<br/>";
	}

  if (CellPhone.value.length > 0 && checkInternationalPhone(CellPhone.value)==false){
    validation_message += "Please enter a valid Cell Phone Number<br/>";
	}

  if (Fax.value.length > 0 && checkInternationalPhone(Fax.value)==false){
    validation_message += "Please enter a valid Fax Number<br/>";
	}

  if( Website.value.length > 0 && !is_valid_url( Website.value ) )
    validation_message += "Please enter a valid Website URL (http://www.example.com)<br/>";

  if( Zip.value.length > 0 && !isInteger( Zip.value ) )
    validation_message += "Please enter a valid Zip<br/>";
  else if( Zip.value.length > 0 && Zip.value.length < 5 )
    validation_message += "Please enter a valid Zip<br/>";
  else if( Zip.value.length == 0 )
    validation_message += "Please enter a Zip<br/>";

  if( State.value == "0" )
    validation_message += "Please select a AOLCP state<br/>";

  if( trim(City.value) == "" || City.value.length == 0 )
    validation_message += "Please enter a Town<br/>";
  else if( isInteger( trim(City.value) ) )
    validation_message += "Please enter a valid Town<br/>";

  if( trim(County.value) == "" || County.value.length == 0 )
    validation_message += "Please enter a County<br/>";
  else if( isInteger( trim(County.value) ) )
    validation_message += "Please enter a valid County<br/>";

  if( Email.value.length > 0 )
  {
    if( !checkEmail( Email.value ) )
      validation_message += "Please enter a valid Email Address<br/>";
    else
    {
      var is_valid = document.frm_main.is_email_used;

      if( is_valid.value.length  )
      {
        validation_message += "Email address already exists.<br/>";
      }
    }
  }

  // now check the business section
  var business = document.frm_main.txt_business_name;
  if( business.value.length )
  {

      // validate business information
    if( document.frm_main.mailB.value.length == 0 )
      validation_message += "Business Email is a required field <br/>";

    if (document.frm_main.PhoneB.value.length > 0 && checkInternationalPhone(document.frm_main.PhoneB.value)==false){
      validation_message += "Please enter a valid Business Phone Number<br/>";
    }

    if (document.frm_main.cPhoneB.value.length > 0 && checkInternationalPhone(document.frm_main.cPhoneB.value)==false){
      validation_message += "Please enter a valid Business Cell Phone Number<br/>";
    }

    if (document.frm_main.FaxB.value.length > 0 && checkInternationalPhone(document.frm_main.FaxB.value)==false){
      validation_message += "Please enter a valid Business Fax Number<br/>";
    }

    if( document.frm_main.URLB.value.length > 0 && !is_valid_url( trim(document.frm_main.URLB.value) ) )
      validation_message += "Please enter a valid Business Website URL (http://www.example.com)<br/>";

    if( document.frm_main.ZipB.value.length > 0 && !isInteger( document.frm_main.ZipB.value ) )
      validation_message += "Please enter a valid Business Zip<br/>";
    else if( document.frm_main.ZipB.value.length > 0 && document.frm_main.ZipB.value.length < 5  )
      validation_message += "Please enter a valid Business Zip<br/>";



    if( document.frm_main.mailB.value.length > 0 )
    {
      if( !checkEmail( trim(document.frm_main.mailB.value) ) )
        validation_message += "Please enter a valid Business Email Address<br/>";
    }
  }

  if( document.frm_main.zipCode.value.length > 0 )
  {
    if( !isInteger(document.frm_main.zipCode.value))
      validation_message +="Please enter a valid Area Served Zip<br/>";
  }

  if( document.frm_main.radius.value.length > 0 )
  {
    if( !isInteger( document.frm_main.radius.value ))
      validation_message += "Please enter a numeric Area Served Radius<br/>";
    else if( document.frm_main.radius.value == 0 )
      validation_message += "Please enter a numeric Area Served Radius between 1 to 3000<br/>";

    if( document.frm_main.zipCode.value.length == 0 )
    {
      validation_message += "Please enter a Area Served Zip Code<br/>";
    }
  }
  else if( document.frm_main.zipCode.value.length > 0 ) // radius is not set
  {
    validation_message += "Please enter a Area Served Radius between 1 to 3000<br/>";
  }
  /*
  else if( !is_alpha(document.getElementById('state_selected_id').options[0].value) )
  {
    validation_message += "Area Served requires either a Zip/Radius or a State selection<br/>";
  }
  */



  if( validation_message != "" )
  {
    document.getElementById("message_box").innerHTML = "<div class='alert'>" + validation_message + "</div>";
    window.scrollTo(0,0);
    return false;
  }

	return true;
 }

  function validateEditBusinessForm( )
  {
    var validation_message = "";
      // validate business information
    if( document.members.email.value.length == 0 )
      validation_message += "Business Email is a required field <br/>";

    if (document.members.phone.value.length > 0 && checkInternationalPhone(document.members.phone.value)==false){
      validation_message += "Please enter a valid Business Phone Number<br/>";
    }

    if (document.members.cell_phone.value.length > 0 && checkInternationalPhone(document.members.cell_phone.value)==false){
      validation_message += "Please enter a valid Business Cell Phone Number<br/>";
    }

    if (document.members.fax.value.length > 0 && checkInternationalPhone(document.members.fax.value)==false){
      validation_message += "Please enter a valid Business Fax Number<br/>";
    }

    if( document.members.website.value.length > 0 && !is_valid_url( trim(document.members.website.value) ) )
      validation_message += "Please enter a valid Business Website URL (http://www.example.com)<br/>";

    if( document.members.zip.value.length > 0 && !isInteger( document.members.zip.value ) )
      validation_message += "Please enter a valid Business Zip<br/>";
    else if( document.members.zip.value.length > 0 && document.members.zip.value.length < 5 )
      validation_message += "Please enter a valid Business Zip<br/>";



    if( document.members.email.value.length > 0 )
    {
      if( !checkEmail( trim(document.members.email.value) ) )
        validation_message += "Please enter a valid Business Email Address<br/>";
    }

    if( validation_message != "" )
    {
      document.getElementById("message_box").innerHTML = "<div class='alert'>" + validation_message + "</div>";
      return false;
    }

    return true;
  }

  function validateSearchForm()
  {
    var validation_message = "";

    if( document.search_aolcp_form.zip.value.length > 0 && !isInteger(document.search_aolcp_form.zip.value) )
    {
      validation_message += "Please enter a valid zip code<br/>";
    }

    if( validation_message != "" )
    {
      document.getElementById("message_box").innerHTML = "<div class='alert'>" + validation_message + "</div>";
      return false;
    }

    return true;
  }


     // sort function - ascending (case-insensitive)
        function sortFuncAsc(record1, record2) {
            var value1 = record1.optText.toLowerCase();
            var value2 = record2.optText.toLowerCase();
            if (value1 > value2) return(1);
            if (value1 < value2) return(-1);
            return(0);
        }

        // sort function - descending (case-insensitive)
        function sortFuncDesc(record1, record2) {
            var value1 = record1.optText.toLowerCase();
            var value2 = record2.optText.toLowerCase();
            if (value1 > value2) return(-1);
            if (value1 < value2) return(1);
            return(0);
        }

        function sortSelect(selection_id, ascendingOrder)
        {
            var selectToSort = document.getElementById(selection_id)
            if (arguments.length == 1) ascendingOrder = true;    // default to ascending sort

            // TODO: for now we are not handling more than 100
            if( selectToSort.options.length > 2000 )
              return;
            //alert( "SORTING = " + selectToSort.options.length );

            // copy options into an array
            var myOptions = [];
            for (var loop=0; loop<selectToSort.options.length; loop++) {
                myOptions[loop] = { optText:selectToSort.options[loop].text, optValue:selectToSort.options[loop].value };
            }

            // sort array
            if (ascendingOrder) {
                myOptions.sort(sortFuncAsc);
            } else {
                myOptions.sort(sortFuncDesc);
            }

            // copy sorted options from array back to select box
            selectToSort.options.length = 0;
            for (var loop=0; loop<myOptions.length; loop++) {
                var optObj = document.createElement('option');
                optObj.text = myOptions[loop].optText;
                optObj.value = myOptions[loop].optValue;
                selectToSort.options.add(optObj);
            }
        }


function checkRadiusMax( field_radius )
{
  if( field_radius.value > 3000 )
    field_radius.value = 3000;
}

