// Matchpoint JS Lib

/* prevent search box from submitting an empty field */
function validateEmpty(mytext) {
  var re = /^\s{1,}$/g; //match any white space including space, tab, form-feed, etc. 
  if ((mytext.value.length==0) || (mytext.value==null) || ((mytext.value.search(re)) > -1)) {
    alert('Please enter a category.');
    return false;
  }
}

/* popup window with provided url */
function popUrl(url, width, height) {
    var localWindowLeft = screen.width/2;
	window.open(url,null,"height=" + height + ",left=" + localWindowLeft + ",top=300,width=" + width + ",scrollbars=yes,resizable=yes,status=no,toolbar=no,menubar=no,location=no");
}

/* scale cpc images width, please pass a very specific jQuery selector */
function mpJQueryScaleMaxWidth(max_width, selector) {
 $(document).ready(function() {		 
  $(selector).each(function(){
    var width = $(this).width();
    if (width > max_width) {
      var new_width = max_width;
      $(this).width(new_width + 'px');
    } 
  });
 });
}

/* jquery form validation */
function mpJQueryFormValidation(elementId) {

 /* jQuery */
 $(document).ready(function() {
  // validate signup form on keyup and submit
  var validator = $("#" + elementId).validate({
    rules: { 
      subject: { required: true },
	  briefDescTextArea: { required: true },	
      firstName: { required: true, minlength: 2 },
      lastName: { required: true, minlength: 2 },
      email: { required: true, email: true },
      zipcode: { required: true, minlength: 5 },		
      phoneAreaCode: { required: true, digits: true, minlength: 3 },
      phonePrefix: { required: true, digits: true, minlength: 3 },
      phoneSuffix: { required: true, digits: true, minlength: 4 }
    },
    messages: {
	  subject: { required: "Please choose a subject" },
      briefDescTextArea: { required: "Please enter content" },	
      firstName: { required: "Enter a first name", minlength: jQuery.format("Enter more letters") },
      lastName: { required: "Enter a last name", minlength: jQuery.format("Enter more letters") },
      email: { required: "Enter a valid email address", minlength: "Please enter a valid email address"},
      zipcode: { required: "Enter a valid zip code", minlength: "Please enter 5 or more digits" },		
      phoneAreaCode: { required: "Enter a valid area code", digits: "Area code must be numbers only", minlength: "Area code must have 3 digits" },
      phonePrefix: { required: "Enter a valid prefix", digits: "Prefix must be numbers only", minlength: "Prefix must have 3 digits" },
      phoneSuffix: { required: "Enter a valid suffix", digits: "Suffix must be numbers only", minlength: "Suffix must has have 4 digits" }
   },
   // the errorPlacement has to take the table layout into account
   errorPlacement: function(error, element) {
    if ( element.is(":radio") )
     error.appendTo( element.parent().next().next() );
    else if ( element.is(":checkbox") )
     error.appendTo ( element.next() );
    else
     error.appendTo( element.parent().next() );
   },
   // set this class to error-labels to indicate valid fields
   success: function(label) {
    // set   as text for IE
    label.html(" ").addClass("checked");
   }
  }); //validate 
 }); //document.ready
}

/* type ahead function used in matchpoint suggest feature for search */
function mpJQueryTypeAhead(mpFindDestId) {

  $(document).ready(function(){

    //prevent users from searching for nothing
    $("#mpSearchForm").submit(function(){
      if( ($("#q").val() == "Product & Service Providers") || ($("#q").val() == "") ) {
        alert("Please enter a search term");
        return false;
      }
    });
  
    //category type ahead	  
    $("#q").autocomplete("/dest", {
      extraParams: {
        id: mpFindDestId,
        jump: "type ahead",
        q: function(){ return $("#q").val(); },
        mp_pt_json: "true"		
      },
      minChars: 3,
      max: 10,
      scroll: false
    });

    //geo type ahead	
    $("#g").autocomplete("/dest", {
      extraParams: {
        id: mpFindDestId,
        jump: "type ahead",	  
        q: function(){ return ""; }, //force q to be blank because autocomplete always sends a "q"
        g: function(){ return $("#g").val(); },
        mp_pt_json: "true"		
      },
      minChars: 3,
      max: 10,
      scroll: false	  
    });

    //geo type ahead local search	
    $("#mpGeoSearchForm_g").autocomplete("/dest", {
      extraParams: {
        id: mpFindDestId,
        jump: "type ahead",	  
        q: function(){ return ""; }, //force q to be blank because autocomplete always sends a "q"
        g: function(){ return $("#mpGeoSearchForm_g").val(); },
        mp_pt_json: "true"		
      },
      minChars: 3,
      max: 10,
      scroll: false	  
    });

    //insert Suggestions header on ajaxSuccess event
    $("#q").ajaxSuccess(function(event){
      $(".ac_results li:first-child").before("<li class=\"ac_header\">Suggestions</li>");
    });
		
  }); 
}

/* ajax yahoo results */
function mpJQueryYahooResults(p_zipcode, p_vel_vw_pid, p_keywordsConcatenated_st, p_mp_xmlAd_BiddedResults, p_vel_vw_q, p_vel_vw_site_partnerId, p_vel_vw_dest, p_vel_vw_flowexp, p_sem_string, p_lead_id) {
  $(document).ready(function(){
    jQuery.ajax({  
      type: "GET",
      url: "/mpExtFeed.htm",
      data: "mppname=yahoo&zipcode=" + p_zipcode + "&pid=" + p_vel_vw_pid + "&keywords=" + escape(p_keywordsConcatenated_st) + "&biddedResults=" + p_mp_xmlAd_BiddedResults,        	 	 
      error: function(event, request, settings){$("#mpXmlAdContainer").css("display","none");},
      beforeSend: function(){ $("#ajaxindicator").show(); },
      success: function(xmlData){
        $("#ajaxindicator").hide();
        if($(xmlData).find('result').length > 0) {			
          $(xmlData).find('result').each(function() {
            var mpNodeHeading = $(this).find('heading').text();
            var mpNodeDescription = $(this).find('description').text();
            var mpClickUrl = $(this).find('clickurl').text();
            var mpDisplayUrl = $(this).find('displayurl').text();					
            var mpOdest_Index = mpClickUrl.indexOf("r=http"); 
            var mpOdest = mpClickUrl.substring(mpOdest_Index + 2); //start at http, not at r=, because 'r' is already encoded.
            var mp_Y_ClickUrl_Params = "q=" + p_vel_vw_q + "&pid=" + p_vel_vw_pid + "&partnerId=" + p_vel_vw_site_partnerId + "&dest=" + p_vel_vw_dest + "&flowexp=" + p_vel_vw_flowexp + "&" + p_sem_string + "&";	
            var mp_Y_ClickUrl = "/mpExtClick.htm?" + mp_Y_ClickUrl_Params + "displayurl=" + escape(mpDisplayUrl) + "&redirectUrl=" + mpOdest + "&lead_id=" + p_lead_id;				
            var mpDisplayAdUnit = $('<div></div>').addClass("mpSponsoredResult");								
            var mpHeadingLink = $('<a></a>').attr({
              href : mp_Y_ClickUrl,
              target : "_blank"
            });					
            mpHeadingLink.addClass("mpSponsoredResultHeader");				
            mpHeadingLink.html(mpNodeHeading).appendTo(mpDisplayAdUnit);									
            $('<div class="mpSponsoredResultDescription"></div>').html(mpNodeDescription).appendTo(mpDisplayAdUnit);
            var mpDisplayLink = $('<a></a>').attr({
              href : mp_Y_ClickUrl,
              target : "_blank"
            });			
            mpDisplayLink.addClass("mpSponsoredResultDisplayLink");
            mpDisplayLink.html(mpDisplayUrl).appendTo(mpDisplayAdUnit);		
            $('<div style="clear:both;padding:0;"></div>').appendTo(mpDisplayAdUnit);
            mpDisplayAdUnit.appendTo('#mpXmlAd');				
          });	
        } else {
          $("#mpXmlAdContainer").css("display","none");
        }
      }
    });
  });
}

/* jQuery Lightbox to ask a business a question on SERP */
function mpJQueryLightbox(pSearchTerm, pLeadId, pBusinessName, pBusinessPhone) {

$(document).ready(function() {

  $('#mpDirectedInclusion').dialog({
    width:494,
    height:450,
    autoOpen:false,
    modal:true,
    resizable:false,
    overlay: {
      opacity: 0.5, 
      background: "black"			  
    },
    close: function() {
      $('#personProfileForm').show();
      $('#mpDirectedInclusion .directedInclusionMessage').remove();		
      $("#descYourNeedsSubject").get(0).selectedIndex = 0;
      $("#descYourNeeds").val("");
      $(".ui-dialog-buttonpane button > *").remove();
    },
    buttons: { "Close": function() { $(this).dialog("close"); } }			
  });
				
  $('#launch_mpDirectedInclusion').click(function(){
    $('#mpDirectedInclusion').dialog('open');
    $('#mpDirectedInclusion').css({ display:"block" });
    $('.ui-dialog-buttonpane').hide();			
  });
  
  $('#launch_mpDirectedInclusion2').click(function(){
    $('#mpDirectedInclusion').dialog('open');
    $('#mpDirectedInclusion').css({ display:"block" });
    $('.ui-dialog-buttonpane').hide();			
  });  
		
  $('#mpDiClose').click(function(){
    $('#mpDirectedInclusion').dialog('close');
  });

  $("#signupsubmit").val("");
  $(".ui-dialog-buttonpane button").empty();
  $("#signupsubmit").mouseover(function(){
    $(this).css("cursor","pointer");
  });
  $(".ui-dialog-buttonpane button").mouseover(function(){
    $(this).css("cursor","pointer");
  });
	 
  // validate form on keyup and submit
  var validator = $("#personProfileForm").validate({
    rules: {
      descYourNeedsSubject: { required: true },
      firstName: { required: true, minlength: 2 },
      lastName: { required: true, minlength: 2 },
      email: { required: true, email: true },
      zipcode: { required: true, minlength: 5 },		
      phoneAreaCode: { required: true, digits: true, minlength: 3 },
      phonePrefix: { required: true, digits: true, minlength: 3 },
      phoneSuffix: { required: true, digits: true, minlength: 4 }
    },
    messages: {
      descYourNeedsSubject: { required: "Please choose a subject" },
      firstName: { required: "Enter a first name", minlength: jQuery.format("Enter more letters") },
      lastName: { required: "Enter a last name", minlength: jQuery.format("Enter more letters") },
      email: { required: "Enter a valid email address", minlength: "Please enter a valid email address" },
      zipcode: { required: "Enter a valid zip code", minlength: "Please enter 5 or more digits" },		
      phoneAreaCode: { required: "Enter a valid area code", digits: "Area code must be numbers only", minlength: "Area code must have 3 digits" },
      phonePrefix: { required: "Enter a valid prefix", digits: "Prefix must be numbers only", minlength: "Prefix must have 3 digits" },
      phoneSuffix: { required: "Enter a valid suffix", digits: "Suffix must be numbers only", minlength: "Suffix must has have 4 digits" }
    },

    // the errorPlacement has to take the table layout into account
    errorPlacement: function(error, element) {
      if ( element.is(":radio") )
        error.appendTo( element.parent().next().next() );
      else if ( element.is(":checkbox") )
        error.appendTo ( element.next() );
      else
        error.appendTo( element.parent().next() );
    },
	
    // set this class to error-labels to indicate valid fields
    success: function(label) {
      // set   as text for IE
      label.html(" ").addClass("checked");
    },

    submitHandler: function(form) {
      $("#descYourNeeds").val($("#descYourNeedsSubject").val() + " - " + $("#descYourNeeds").val());
      //form.submit(); //just when testing without ajax		  
      $("#personProfileForm").hide();
      $("#mpDirectedInclusion").append("<img class=\"diLoader\" src=\"http://sites-01.matchpoint.net/mp_roller.gif\">");
      var checkBoxValueJQuery = $('input#sendToOtherBusinesses:checked').val();
      var checkBoxValue;
      if (checkBoxValueJQuery == undefined)
        checkBoxValue = "off";
      else
        checkBoxValue = checkBoxValueJQuery;
      //otherwise, jQuery returns the string "on"
		 
      jQuery.post('/mpEmailFormSubmit.htm',
	    {
          descYourNeeds: $('#descYourNeeds').val(),
          firstName: $('#firstName').val(),
          lastName: $('#lastName').val(),
          email: $('#email').val(),	  
          searchTerm: pSearchTerm,
          mp_pt_json: "true",
          lead_id: pLeadId,
          bn: pBusinessName,
          bp: pBusinessPhone,
          zipcode: $('#zipcode').val(),
          sendToOtherBusinesses: checkBoxValue
        },
        function(jsonData) {			 
          $('.diLoader').remove();
          $('.ui-dialog-buttonpane').show();
          // append dyn html to #mpDirectedInclusion
          $("#mpDirectedInclusion").append("<div class=\"directedInclusionMessage\"></div>");			 			 

          switch(jsonData.pageType) {			 
            case "confirm page new user" :
              $(".directedInclusionMessage").append("<h3 class=\"noBg\">We Need to Confirm Your E-mail Address.</h3><h4>Check for our confirmation e-mail so we can send your message.</h3><img src='http://sites-01.matchpoint.net/mp_conf_edu_image.jpg'/>");
            break;				

            default :				
              $(".directedInclusionMessage").append("<h3>Your message has been sent to:</h3>");
              if(jsonData.includedBusiness != null) {				   
                if(jsonData.includedBusiness.businessName == "")
                  var bizName = jsonData.includedBusiness.contactName;
                else
                  var bizName = jsonData.includedBusiness.businessName;				 					 	
                var includedBizHtml = $("<div class=\"resultRow\"><a href=" + jsonData.includedBusiness.friendlyUrl + ">" + bizName + "</a><br><em>" + jsonData.includedBusiness.streetAddr + ", " + jsonData.includedBusiness.city + ", " + jsonData.includedBusiness.state + " " + jsonData.includedBusiness.zip + "</em></div>");
                $(".directedInclusionMessage").append(includedBizHtml);
              }				 			
              if(jsonData.searchResultList)					 
                var searchResultList = jsonData.searchResultList;
              else				 	 
                var searchResultList = null;

              if(searchResultList) {
                //case where searchResultList has only one result.
                if(searchResultList.length == 1) {
                  //if the business is not directed inclusion, its a competitive business as a single result.
                  if(searchResultList[0].isIncludedBusiness != true) {			 
                    if(searchResultList[0].businessName == "")
                      var bizName = searchResultList[0].contactName;
                    else
                      var bizName = searchResultList[0].businessName;						 
                    var resultHtml = $("<div class=\"resultRow\"><a href=" + searchResultList[0].friendlyUrl + ">" + bizName + "</a><br><em>" + searchResultList[0].streetAddr + ", " + searchResultList[0].city + ", " + searchResultList[0].state + " " + searchResultList[0].zip + "</em></div>");
                    $(".directedInclusionMessage").append(resultHtml);
                  } else { //this is the includedBusiness! Do not display included business twice! just display the illustration as in the mockup
                    $(".directedInclusionMessage").append("<h4>Check your e-mail for responses from this business.</h4><div class='mp_dlg_illus'><img src='http://sites-01.matchpoint.net/mp_dlg_illus.jpg'/></div>");   
                  }				 				   
                } else if(searchResultList.length > 1) {				 				 
                  //$(".directedInclusionMessage").append("<h4>We also sent your message to these competitive businesses:</h4>");
                  for (var i in searchResultList) {	
                    if(searchResultList[i].isIncludedBusiness != true) {			 
                      if(searchResultList[i].businessName == "")
                        var bizName = searchResultList[i].contactName;
                      else
                        var bizName = searchResultList[i].businessName;						 
                      var resultHtml = $("<div class=\"resultRow\"><a href=" + searchResultList[i].friendlyUrl + ">" + bizName + "</a><br><em>" + searchResultList[i].streetAddr + ", " + searchResultList[i].city + ", " + searchResultList[i].state + " " + searchResultList[i].zip + "</em></div>");
                      $(".directedInclusionMessage").append(resultHtml);
                    }
                  }
				  $(".directedInclusionMessage").append("<p class=\"cl\">Check your e-mail for responses from these businesses.</p>");
                } //if searchResultList.length
              } else { //searchResultList
                $(".directedInclusionMessage").append("<div class=\"resultRow\"><strong style=\"color:#f00\">ERROR: searchResultList is null, page type is " + jsonData.pageType + "</strong></div>");
              }
            } //switch					 
          },
        "json"); //jQuery.post
      } //submitHandler  
    }); //validate 
  }); //document.ready
} //mpJQueryLightbox 
 
/* mp function */
function concatenatePhone(areacode, prefix, suffix) {
  var acString = areacode.value + '';
  var pfxString = prefix.value + '';
  var sfxString = suffix.value + ''; 
  document.getElementById("phoneNumber").setAttribute('value', acString + pfxString + sfxString);
} 
 
/* pass in a parent id of a ul tag and hide ul tags > 3 */
function mpUL_Shift_Init(ul_id_parent_selector) {
  /* reserved global vars */
  var mp_g_SerpSize; //size of results for the case Did You Mean
  var mp_g_FlagString; //string of 0's and 1's used to determine which column to hide with lightbox pagination

  $(document).ready(function() { 
    //initialize global flag string of 0's and 1's used to determine which column to hide with lightbox pagination
    mp_g_FlagString = "";
    $(ul_id_parent_selector + ' ul').each(function(i){
      if(i>2) {
        $(this).hide();
		mp_g_FlagString += "0";
	  } else {
	    mp_g_FlagString += "1";
      }	    
    });
	mp_g_SerpSize = $(ul_id_parent_selector + ' a').size();
	//45 links per page, 15 links per column
	//var mpTotalPages = Math.ceil(mp_g_SerpSize / 45);
	var mpTotalNumColumns = Math.ceil(mp_g_SerpSize / 15);
    $("#mpGetNextList").click(function(){
	  mpPaginateRight();
	});
    $("#mpGetBackList").click(function(){
	  mpPaginateLeft();
	});
    function mpPaginateRight() {
      if(mp_g_FlagString.charAt(mp_g_FlagString.length-1) != "1") {		
        var mp_g_FlagString_ShiftRight = flag_shift_r(mp_g_FlagString);
        var mp_g_FlagString_ShiftRight_Split = mp_g_FlagString_ShiftRight.split("");
        $(ul_id_parent_selector + ' ul').each(function(i){
          if(mp_g_FlagString_ShiftRight_Split[i] == "0")
            $(this).hide();
          else
            $(this).show();
        });
        $("#mpGetNextList").addClass("mpButtonSmallO").removeClass("mpButtonSmallG");
		$("#mpGetBackList").addClass("mpButtonSmallO").removeClass("mpButtonSmallG");
        mp_g_FlagString = mp_g_FlagString_ShiftRight;
      } else {
        $("#mpGetNextList").addClass("mpButtonSmallG").removeClass("mpButtonSmallO"); 
	  }
    }
    function mpPaginateLeft() {
      if(mp_g_FlagString.charAt(0) != "1") {	
        var mp_g_FlagString_ShiftLeft = flag_shift_l(mp_g_FlagString);
        var mp_g_FlagString_ShiftLeft_Split = mp_g_FlagString_ShiftLeft.split("");
        $(ul_id_parent_selector + ' ul').each(function(i){
          if(mp_g_FlagString_ShiftLeft_Split[i] == "0")
            $(this).hide();
          else
            $(this).show();
        });
        $("#mpGetBackList").addClass("mpButtonSmallO").removeClass("mpButtonSmallG");
		$("#mpGetNextList").addClass("mpButtonSmallO").removeClass("mpButtonSmallG");
        mp_g_FlagString = mp_g_FlagString_ShiftLeft;		
      } else {
        $("#mpGetBackList").addClass("mpButtonSmallG").removeClass("mpButtonSmallO"); 
	  }
    }  
	
  });   
}

/* pass in a flag string like 100011 and shift left */
function flag_shift_l(flagStr) {
  flagArray = flagStr.split("");
  var firstElement = flagArray[0];
  flagArray.shift();
  flagArray.push(firstElement);
  return flagArray.join("");
}

/* pass in a flag string like 100011 and shift right */
function flag_shift_r(flagStr) {
  flagArray = flagStr.split("");   var lastIndex = (flagArray.length)-1;
  var lastElement = flagArray[lastIndex];
  flagArray.pop();
  flagArray.unshift(lastElement);
  return flagArray.join("");
}

/* jQuery Lightbox to ask a business a question on SERP */
function mpJQueryLightboxGeneric(p_lightBoxElementId, p_width, p_height, p_lightBoxOpenerId, p_lightBoxCloserId) {
  $(document).ready(function() {  
    /* setup the lightbox*/
    $('#' + p_lightBoxElementId).dialog({
      width: p_width,
      height: p_height,
      autoOpen: false,
      modal: true,
      resizable: false,
      overlay: {
        opacity: 0.5, 
        background: "black"			  
      }
    });
    /* style the lightbox */
    $('.ui-resizable-handle').css({ 'display':'none' });
    $('.ui-dialog-container').css({ 'background':'#ffeccc', '-moz-border-radius':'5px', '-webkit-border-radius':'5px' });
    /* assign the opener to an -a- tag with an id */
    $('#' + p_lightBoxOpenerId).click(function(){
      $('#' + p_lightBoxElementId).dialog('open');
    });
    $('#' + p_lightBoxCloserId).click(function(){
      $('#' + p_lightBoxElementId).dialog('close');
    });  
    /* initialize by hiding extra columns */
    mpUL_Shift_Init("#mpCategoryListContent");	    
  });
}

function mpJQueryClearInput(p_selector, clearOutValue) {
  $(document).ready(function(){
  
    if($(p_selector).val() == clearOutValue)
      $(p_selector).css({'color':'#aaa','font-style':'italic'});
        
    $(p_selector).focus(function() {
	  if($(this).val() == clearOutValue) {
        $(this).val("");
        $(this).css({'color':'#000','font-style':'normal'});
      }  
    });
  });
}

function mpJQueryClearInputOnSubmit(p_selector_input, p_selector_form_id) {
  $(document).ready(function(){
    $(p_selector_form_id).submit(function() {
	  if($(p_selector_input).val() == "City, State or Zip") {
        $(p_selector_input).val("");
      }  
    });
  });
}

/* home page tabs */
function mpInitHomeTabs() {
$(document).ready(function() {
  //init
  $("#mpTabViewPromoteYourBiz").hide();
  $("#mpTabViewWebPublishers").hide();
  $("#mpTabClickPromoteYourBiz").parent().removeClass("selected").removeClass("mpNoRightBorder").addClass("mpNoLeftBorder");
  $("#mpTabClickWebPublishers").parent().removeClass("selected").removeClass("mpNoRightBorder").addClass("mpNoLeftBorder");		
  //clicks
  $("#mpTabClickFreeTools").click(function(){
    $("#mpTabViewFreeTools").show();
    $("#mpTabViewPromoteYourBiz").hide();
    $("#mpTabViewWebPublishers").hide();
	$(this).parent().addClass("selected").removeClass("mpNoRightBorder").removeClass("mpNoLeftBorder");
    $("#mpTabClickPromoteYourBiz").parent().removeClass("selected").removeClass("mpNoRightBorder").addClass("mpNoLeftBorder");
    $("#mpTabClickWebPublishers").parent().removeClass("selected").removeClass("mpNoRightBorder").addClass("mpNoLeftBorder");		
  });
  $("#mpTabClickPromoteYourBiz").click(function(){
    $("#mpTabViewFreeTools").hide();
    $("#mpTabViewPromoteYourBiz").show();
    $("#mpTabViewWebPublishers").hide();
	$(this).parent().addClass("selected").removeClass("mpNoRightBorder").removeClass("mpNoLeftBorder");
    $("#mpTabClickFreeTools").parent().removeClass("selected").removeClass("mpNoLeftBorder").addClass("mpNoRightBorder");	
    $("#mpTabClickWebPublishers").parent().removeClass("selected").removeClass("mpNoRightBorder").addClass("mpNoLeftBorder");	
  });
  $("#mpTabClickWebPublishers").click(function(){
    $("#mpTabViewFreeTools").hide();
    $("#mpTabViewPromoteYourBiz").hide();
    $("#mpTabViewWebPublishers").show();
	$(this).parent().addClass("selected").removeClass("mpNoRightBorder").removeClass("mpNoLeftBorder");
    $("#mpTabClickFreeTools").parent().removeClass("selected").removeClass("mpNoLeftBorder").addClass("mpNoRightBorder");
    $("#mpTabClickPromoteYourBiz").parent().removeClass("selected").removeClass("mpNoLeftBorder").addClass("mpNoRightBorder");	
  });
});
}

/* legacy validate phone - non-jquery */
function validatePhone(areacode, prefix, suffix, extension) {

	var mpAlertNumbersOnlyMessage = "Please enter digits only.";
	var mpAlertEmptyFormMessage = "One or more of the fields are blank.\r\r * Please enter your phone number.\r\rExtension is optional.";
	var mpAlertAreaCodeLength = "The area code must have 3 digits.";
    var mpAlertPrefixCodeLength = "The prefix must have 3 digits.";
	var mpAlertSuffixCodeLength = "The suffix must have 4 digits";
	var mpAlertExtensionCodeLength = "The extension must have 3 to 4 digits";
	
	var acString = areacode.value + '';
	var pfxString = prefix.value + '';
	var sfxString = suffix.value + '';
	var extString = extension.value + '';	
					
	if ( (areacode.value == "") || (prefix.value == "") || (suffix.value == "") ) {
		alert(mpAlertEmptyFormMessage);
		return false;
	} else if ( ! ( (areacode.value.match(/^\d+$/)) && (prefix.value.match(/^\d+$/)) && (suffix.value.match(/^\d+$/)) && (extension.value.match(/^\d*$/)) ) ) {
		alert(mpAlertNumbersOnlyMessage);
		return false;
	} else if(acString.length != 3) {
		alert(mpAlertAreaCodeLength);
		return false;
	} else if(pfxString.length != 3) {
		alert(mpAlertPrefixCodeLength);
		return false;
	} else if(sfxString.length != 4) {
		alert(mpAlertSuffixCodeLength);
		return false;
	} else if( (extString.length < 3) || (extString.length > 4) ) {
		alert(mpAlertExtensionCodeLength);
		return false;
	}
	
	document.getElementById("phoneNumber").setAttribute('value', acString + pfxString + sfxString);
}

/* used for buttons built from nested html tags, instead of a plain old -a- tag. example, buttons on the right gutter of a serp page */
function mpJQueryButtonInit() {
  $(document).ready(function(){
    $(".mpGutterButtonContainer").mouseover(function(){
      $(this).css({"background":"#C8DCFC","cursor":"pointer"});
      $(this).find("a").css({"text-decoration":"none","color":"#000"});
    });
    $(".mpGutterButtonContainer").mouseout(function(){
      $(this).css({"background":"#fff","cursor":"auto"});
      $(this).find("a").css({"text-decoration":"underline","color":"#36c"});    
    });
    $(".mpGutterButtonContainer").click(function(){      
      if( ! ((($(this).find("a").attr("href").substring(0,1)) == "#") || (($(this).find("a").attr("href")) == "") ) )
        window.location.replace($(this).find("a").attr("href")); //plain old links
      else
        $(this).find("a").trigger('click'); //for lightbox links      
    });  
  });
}

