// 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 

/* jQuery Lightbox to ask a business a question whether logged in or not. launchIdSelector is a unique id from the button that launches this lightbox */
/* useful for leadforms with multiple businesses such as on the serp compare page */
function mpJQueryLightboxMultiLeadForm(pSearchTerm, pLeadId, userStatus, launchIdSelector, lboxHeight) {

$(document).ready(function() {

  $('#mpDirectedInclusion').dialog({
    width:340,
    height:lboxHeight,
    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"); } }			
  });
				
  $('#' + launchIdSelector).click(function(){
    $('#mpDirectedInclusion').dialog('open');
	$('.ui-dialog').height(lboxHeight);
	$('#bn').val( $(this).attr('rev') );
	$('#bp').val( $(this).attr('rel') );
    $('#mpDirectedInclusion').css({ display:"block" });
    $('.ui-dialog-buttonpane').hide();
	$('.mpMessageResponse').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"

      var mpEmailFormSubmitObject = {};
	  
      if(userStatus == "loggedIn") {
	  	if(!pBusinessPhone) {
	  	  mpEmailFormSubmitObject = {
            descYourNeeds: $('#descYourNeeds').val(),
            searchTerm: pSearchTerm,
            mp_pt_json: "true",
            lead_id: pLeadId,
            sendToOtherBusinesses: checkBoxValue
          };
		} else {
	  	  mpEmailFormSubmitObject = {
            descYourNeeds: $('#descYourNeeds').val(),
            searchTerm: pSearchTerm,
            mp_pt_json: "true",
            lead_id: pLeadId,
            bn: $('#bn').val(),
            bp: $('#bp').val(),
            sendToOtherBusinesses: checkBoxValue
          };			
		}
	  } else {
	  	mpEmailFormSubmitObject = {
          descYourNeeds: $('#descYourNeeds').val(),
          firstName: $('#firstName').val(),
          lastName: $('#lastName').val(),
          email: $('#email').val(),	  
          searchTerm: pSearchTerm,
          mp_pt_json: "true",
          lead_id: pLeadId,
          bn: $('#bn').val(),
          bp: $('#bp').val(),
          zipcode: $('#zipcode').val(),
          sendToOtherBusinesses: checkBoxValue
        };	  	
	  }
 		 
      jQuery.post('/mpEmailFormSubmit.htm',
        mpEmailFormSubmitObject,
        function(jsonData) {			 
          $('.diLoader').remove();

          switch(jsonData.pageType) {			 
            case "confirm page new user" :
              $('.ui-dialog-buttonpane').show();
              // append dyn html to #mpDirectedInclusion
              $("#mpDirectedInclusion").append("<div class=\"mpMessageResponse\"></div>");			 			 			
              $(".mpMessageResponse").append("<div class='confirmResponse'><h3>You must confirm your e-mail address before your message can be sent.</h3><div class='mpMessageResponseMid'><img src='http://sites-01.matchpoint.net/mp_email_stamp_92x83.jpg'><p><strong>Check your E-mail</strong> for a confirmation message.<span>We sent it to:</span><em>" + email + "</em></p><div class='clear'></div></div></div>");
              $(".ui-dialog").height(500);
			break;				

            default :	
			  if (jsonData.userStatus == "notLoggedIn") {
			  	$("#personProfileForm").show();
			  	var leadFormLoginLink = $("#leadFormLoginLink").attr("href");
				if($(".mpMessageAlert").size() == 0)
                  $(".submitContainer").prepend("<div class=\"mpMessageAlert\"><strong>Alert!</strong> You must <a href=\"" + leadFormLoginLink + "\">login to send.</a></div>");
			    $(".ui-dialog").height(600);			  				    
			  }	else {
                $('.ui-dialog-buttonpane').show();
                // append dyn html to #mpDirectedInclusion
                $("#mpDirectedInclusion").append("<div class=\"mpMessageResponse\"></div>");			 			 			  	
                $(".mpMessageResponse").append("<img src='http://sites-01.matchpoint.net/mp_email_env_blu_cm_91x74.png'><h3>Your message has been sent.</h3>");
			    $(".ui-dialog").height(350);			  	
			  }	
            } //switch					 
          },
        "json"); //jQuery.post
      } //submitHandler  
    }); //validate 
  }); //document.ready
} //mpJQueryLightboxLeadForm



/* jQuery Lightbox to ask a business a question whether logged in or not. launchIdSelector is a unique id from the button that launches this lightbox */
/* this one is useful for the biz profile page -products tab- where the business name and business phone does not change, unlike the previous function above */
function mpJQueryLightboxLeadForm(pSearchTerm, pLeadId, pBusinessName, pBusinessPhone, userStatus, launchIdSelector, lboxHeight) {

$(document).ready(function() {

  var email = $('#email').val();
  $('#mpDirectedInclusion').dialog({
    width:340,
    height:lboxHeight,
    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"); } }			
  });
				
  $('#' + launchIdSelector).click(function(){
    $('#mpDirectedInclusion').dialog('open');
	$('.ui-dialog').height(lboxHeight);
    $('#mpDirectedInclusion').css({ display:"block" });
    $('.ui-dialog-buttonpane').hide();	
	$('.mpMessageResponse').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"

      if(userStatus == "loggedIn") {
	  	if(!pBusinessPhone) {
	  	  var mpEmailFormSubmitObject = {
            descYourNeeds: $('#descYourNeeds').val(),
            searchTerm: pSearchTerm,
            mp_pt_json: "true",
            lead_id: pLeadId,
            sendToOtherBusinesses: checkBoxValue
          };
		} else {
	  	  var mpEmailFormSubmitObject = {
            descYourNeeds: $('#descYourNeeds').val(),
            searchTerm: pSearchTerm,
            mp_pt_json: "true",
            lead_id: pLeadId,
            bn: pBusinessName,
            bp: pBusinessPhone,
            sendToOtherBusinesses: checkBoxValue
          };			
		}
	  } else {
	  	var mpEmailFormSubmitObject = {
          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
        };	  	
	  }
	  		 
      jQuery.post('/mpEmailFormSubmit.htm',
        mpEmailFormSubmitObject,
        function(jsonData) {			 
          $('.diLoader').remove();

          switch(jsonData.pageType) {			 
            case "confirm page new user" :
              $('.ui-dialog-buttonpane').show();
              // append dyn html to #mpDirectedInclusion
              $("#mpDirectedInclusion").append("<div class=\"mpMessageResponse\"></div>");			 			 			
              $(".mpMessageResponse").append("<div class='confirmResponse'><h3>You must confirm your e-mail address before your message can be sent.</h3><div class='mpMessageResponseMid'><img src='http://sites-01.matchpoint.net/mp_email_stamp_92x83.jpg'><p><strong>Check your E-mail</strong> for a confirmation message.<span>We sent it to:</span><em>" + email + "</em></p><div class='clear'></div></div></div>");
              $(".ui-dialog").height(500);
			break;				

            default :	
			  if (jsonData.userStatus == "notLoggedIn") {
			  	$("#personProfileForm").show();
			  	var leadFormLoginLink = $("#leadFormLoginLink").attr("href");
				if($(".mpMessageAlert").size() == 0)
                  $(".submitContainer").prepend("<div class=\"mpMessageAlert\"><strong>Alert!</strong> You must <a href=\"" + leadFormLoginLink + "\">login to send.</a></div>");
			    $(".ui-dialog").height(600);			  				    
			  }	else {
                $('.ui-dialog-buttonpane').show();
                // append dyn html to #mpDirectedInclusion
                $("#mpDirectedInclusion").append("<div class=\"mpMessageResponse\"></div>");			 			 			  	
                $(".mpMessageResponse").append("<img src='http://sites-01.matchpoint.net/mp_email_env_blu_cm_91x74.png'><h3>Your message has been sent.</h3>");
			    $(".ui-dialog").height(350);			  	
			  }	
            } //switch					 
          },
        "json"); //jQuery.post
      } //submitHandler  
    }); //validate 
  }); //document.ready
} //mpJQueryLightboxLeadForm


/* 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      
    });  
  });
}

/* mpGMapsObj */

function mpGMapsObj() {
	
  var map, elementMapId;

  this.loadGMap = function(address, city, state, businessName, elementMapId, zoomLevel) {
    var longAddress = address + ", " + city + ", " + state;
    var fallBackAddress = city + ", " + state;
    if (GBrowserIsCompatible()) {
      var geocoder = new GClientGeocoder();
      geocoder.getLatLng(
        longAddress,
        function(point) {
          if (!point) {
            var geocoderFallBack = new GClientGeocoder();
            geocoderFallBack.getLatLng(fallBackAddress, function(point){renderGMap(point, businessName, elementMapId, zoomLevel);});
          } else {
            renderGMap(point, businessName, elementMapId, zoomLevel);
          }
        }
      );
    }
  }

  function renderGMap(point, businessName, elementMapId, zoomLevel) {		
    map = new GMap2(document.getElementById(elementMapId));
    map.addControl(new GSmallMapControl())							 
    map.addControl(new GMapTypeControl());							 
    map.setCenter(point, zoomLevel);
    marker = new GMarker(point);
    to_html = businessName + '<br>Directions: <b>To here</b> - <a href="javascript:fromhere()">From here</a>' + '<br>Start address:<form action="http://maps.google.com/maps" method="get" target="_blank">' + '<input type="text" size=40 maxlength=48 name="saddr" id="saddr" value=""><br>' + '<input value="Get Directions" type="submit">' + '<input type="hidden" name="daddr" value="' + point.lat() + ',' + point.lng() + '">';
    from_html = businessName + '<br>Directions: <a href="javascript:tohere()">To here</a> - <b>From here</b>' + '<br>End address:<form action="http://maps.google.com/maps" method="get"  target="_blank">' + '<input type="text" size="40" maxlength="48" name="daddr" id="daddr" value=""><br>' + '<input value="Get Directions" type="submit">' + '<input type="hidden"  name="saddr" value="' + point.lat() + ',' + point.lng() + '">';
    direction_html = businessName + '<br>Directions: <a href="javascript:tohere()">To here</a> - <a href="javascript:fromhere()">From here</a>';
    GEvent.addListener(marker, "click", function() {
      marker.openInfoWindowHtml(direction_html);
    });
    map.addOverlay(marker);		
  }

}

var marker, to_html, from_html;
function tohere() {
  marker.openInfoWindowHtml(to_html);
}
function fromhere() {
  marker.openInfoWindowHtml(from_html);
}

function mapsLoaded() {
  var mpMaps = new mpGMapsObj();
  mpMaps.loadGMap(g_bizStreetAddr, g_bizCity, g_bizState, g_businessName, elementMapId, g_zoomLevel);
}

function loadMaps() {
  google.load("maps", "2", {"callback" : mapsLoaded});	
}		

function mpDynamicGMap(targetMapId, mp_key_google_maps) {
  elementMapId = targetMapId;
  var script = document.createElement("script");
  script.src = "http://www.google.com/jsapi?key=" + mp_key_google_maps + "&callback=loadMaps";
  script.type = "text/javascript";
  document.getElementsByTagName("head")[0].appendChild(script);
}  


function mpLoadMapsEmbed(mp_key_google_maps) {
  $(document).ready(function(){										 
    mpDynamicGMap("mpMapEmbed", mp_key_google_maps);
  });
}

function mpInitMapsLightbox(mp_key_google_maps) {
  $(document).ready(function(){
    $('#mpMap').dialog({
      width:494,
      height:430,
      autoOpen:false,
      modal:true,
      resizable:false,
      overlay: {opacity: 0.5, background: "black"},
      buttons: { "Close": function(){$(this).dialog("close");} }								
    });
		
    $('#mpMapClose').click(function(){$('#mpMap').dialog('close');});
		
    $('#launch_mpMap').click(function(){
      $('#mpMap').dialog('open');
      $('.ui-dialog-buttonpane button').mouseover(function(){
      $(this).css({ cursor:"pointer" });
    });	
	
    mpDynamicGMap("mpMapLightbox", mp_key_google_maps);
    $('.ui-dialog-buttonpane').show();
    $('#mpMap').css({ display:"block" });
    });
  });
}

/* pop coupon */
function couponPopWin(url) {
  var localWindowLeft = screen.width/4;
  var couponWin = window.open(url,"couponPop","top=200,left="+localWindowLeft+",width=982,height=750,location=no,menubar=no,status=no,toolbar=no,scrollbars=yes");
  jQuery.get("/mpActTrack.htm", { action: "coupon_print", from: "b" } );	
}

/* tracking user actions from top */
function mpTrackUserActions() {
  $(document).ready(function(){  
    $("#mpLinkSocialNetworkFaceBook").click(function() { jQuery.get("/mpActTrack.htm", { action: "facebook_add", from: "b" } ); }); 
    $("#mpLinkSocialNetworkLinkedIn").click(function() { jQuery.get("/mpActTrack.htm", { action: "linkedin_add", from: "b" } ); }); 
    $("#mpAddressBook").click(function() { jQuery.get("/mpActTrack.htm", { action: "addrbook_save", from: "b" } ); }); 
    $("#launch_mpMap").click(function() { jQuery.get("/mpActTrack.htm", { action: "map_view", from: "b" } ); }); 
    $("#mpPrinter").click(function() { jQuery.get("/mpActTrack.htm", { action: "page_print", from: "b" } ); }); 
    $("#mpEmailCoupon").click(function() { jQuery.get("/mpActTrack.htm", { action: "coupon_email", from: "b" } ); });   
  });
}

/* overview - service area */
function mpInitServiceAreaExpand() {
  $(document).ready(function(){
    $("#mpServiceAreaMore").hide();										 
    $("#mpServiceAreaMorePopDown").click(function(){ 
      $("#mpServiceAreaMore").show(); 
      $("#mpServiceAreaMorePopDown").hide();
    });
  });
}
 
function mpInitAdminToolBar() {
$(document).ready(function(){
  $("#adminHandle").mouseover(function(){
    $(this).css("cursor","pointer");
  });
  $("#adminHandle").click(function(){
    var currentWidth = 	$("#adminToolBar").css("width");
		if(currentWidth == "10px") {
      $("#adminToolBar").css("width","auto");
			$("#adminToolBar a.dialogBoxOpener").css("display","inline");
			$("#adminToolBar .mp_admin_sprite").css("display","inline-block");
			$(".container").css("margin-top","0px");
		} else {
		  $("#adminToolBar").css("width","10px");
			$("#adminToolBar a.dialogBoxOpener").css("display","none");
			$("#adminToolBar .mp_admin_sprite").css("display","none");
			$(".container").css("margin-top","-30px");			
		}
  });
});
}

/* replaces non-alphanumeric characters with dash - character for friendly urls */
function friendlyString(str){
  return(str.replace(/[^0-9A-Za-z]+/g, "-"));
}

/* articleSearchInit */
function articleSearchInit() {
  $(document).ready(function(){
    $("#articleSearchTermSubmit").click(function(){
      var mySearchString = $("#articleSearchTerm").val();
      var myActionUrl = "/article-search/" + friendlyString(mySearchString);
		  $("#articleSearchForm").attr("action", myActionUrl);
    });  												 
  });
}

/* home page init dynamic tabs */
function mpInitDynTabs(tab1, tab2, tab3, tabClick1, tabClick2, tabClick3) {
$(document).ready(function() {
  //init
  $("#" + tab2).hide();
  $("#" + tab3).hide();
  $("#" + tabClick2).parent().removeClass("selected").removeClass("mpNoRightBorder").addClass("mpNoLeftBorder");
  $("#" + tabClick3).parent().removeClass("selected").removeClass("mpNoRightBorder").addClass("mpNoLeftBorder");		
  //clicks
  $("#" + tabClick1).click(function(){
    $("#" + tab1).show();
    $("#" + tab2).hide();
    $("#" + tab3).hide();
	$(this).parent().addClass("selected").removeClass("mpNoRightBorder").removeClass("mpNoLeftBorder");
    $("#" + tabClick2).parent().removeClass("selected").removeClass("mpNoRightBorder").addClass("mpNoLeftBorder");
    $("#" + tabClick3).parent().removeClass("selected").removeClass("mpNoRightBorder").addClass("mpNoLeftBorder");		
  });
  $("#" + tabClick2).click(function(){
    $("#" + tab1).hide();
    $("#" + tab2).show();
    $("#" + tab3).hide();
	$(this).parent().addClass("selected").removeClass("mpNoRightBorder").removeClass("mpNoLeftBorder");
    $("#" + tabClick1).parent().removeClass("selected").removeClass("mpNoLeftBorder").addClass("mpNoRightBorder");	
    $("#" + tabClick3).parent().removeClass("selected").removeClass("mpNoRightBorder").addClass("mpNoLeftBorder");	
  });
  $("#" + tabClick3).click(function(){
    $("#" + tab1).hide();
    $("#" + tab2).hide();
    $("#" + tab3).show();
	$(this).parent().addClass("selected").removeClass("mpNoRightBorder").removeClass("mpNoLeftBorder");
    $("#" + tabClick1).parent().removeClass("selected").removeClass("mpNoLeftBorder").addClass("mpNoRightBorder");
    $("#" + tabClick2).parent().removeClass("selected").removeClass("mpNoLeftBorder").addClass("mpNoRightBorder");	
  });
});
}

function mpJQueryCheckInputTextOnSubmit(p_selector_form_id, p_selector_input, input_value_text) {
  $(document).ready(function(){ 	
    $(p_selector_form_id).submit(function() {	  
     if( ($(p_selector_input).val() == input_value_text) || ($(p_selector_input).val() == "") ) {
        alert("Please enter a search term");
        return false;
      }  	  
    });
  });
}


function mpInitMatchHeights(numOfRows){
    $(window).ready(function(){
        $(".r1 img").width(105);
        //match heights
        for (i = 1; i < numOfRows + 1; i++) {
            var tallestHeight = $("#mpProductGrid li.r" + i + ":first-child").height();
            $("#mpProductGrid li.r" + i).each(function(){
                if ($(this).height() > tallestHeight) 
                    tallestHeight = $(this).height();
            });
            $("#mpProductGrid li.r" + i).each(function(){
                $(this).height(tallestHeight);
            });
        }
        //hide columns greater than 5
        $("#mpProductGrid ul.column:gt(5)").hide();
        $(".mpControlStub").height($("li.r1").height());
    });
}

function mpGroupHandler(event){
    $(".group" + event.data.mpGroupIndex).toggle();
    if ($("#mpGroup" + event.data.mpGroupIndex + " img").attr("src") == "http://sites-01.matchpoint.net/mp_arrow_down_fde8c2.gif") 
        $("#mpGroup" + event.data.mpGroupIndex + " img").attr("src", "http://sites-01.matchpoint.net/mp_arrow_right_fde8c2.gif");
    else 
        $("#mpGroup" + event.data.mpGroupIndex + " img").attr("src", "http://sites-01.matchpoint.net/mp_arrow_down_fde8c2.gif")
}

function mpInitGroupControl(numOfGroups){
    $(document).ready(function(){
        for (i = 1; i < numOfGroups + 1; i++) {
            //do not use the jQuery's .click even directly. you must user jQuery bind because index won't be available with jQuery click	
            $("#mpGroup" + i).bind("click", {
                mpGroupIndex: i
            }, mpGroupHandler);
        }
    });
}

function mpBuildChooserControl(targetSelector, numOfRows){

    $(".r1:gt(0)").each(function(i){
        var mpProductBoxWrapper = $('<span class="mpProductBoxWrapper"></span>');
        var mpProductBox = $('<span class="mpProductBox"></span>');
        var mpProductBoxSourceChildrenSet = $(this).children();
        mpProductBoxSourceChildrenSet.each(function(){
            if (!($(this).hasClass("mp_ornge_28h_bg"))) {
                mpProductBox.append($(this).clone()); //appending  $this removes from this selection,append a 'clone' of $this instead of $this
                mpProductBox.remove('.dialogBoxOpenButton'); //remove inner dialogBoxOpenButton
            }
        });
        var mpProductCheckMarkId = "checkMark" + $(this).parent().attr("id");
        if (i < 5) 
            var mpProductCheckMark = $('<input id="' + mpProductCheckMarkId + '" type="checkbox" checked="checked">');
        else 
            var mpProductCheckMark = $('<input id="' + mpProductCheckMarkId + '" type="checkbox">');
        
        mpProductBoxWrapper.append(mpProductBox);
        mpProductBoxWrapper.append(mpProductCheckMark);
        $('#' + targetSelector).append(mpProductBoxWrapper);
    });
    
    $('#mpExecCompare').click(function(){
        $('#productCompareTarget input').each(function(i){
            colIndex = i + 1;
            if ($(this).attr('checked')) 
                $('#col' + colIndex).show();
            else 
                $('#col' + colIndex).hide();
        });
        $('#dialogBoxProductCompare').hide();
        
        //match heights
        for (i = 1; i < numOfRows + 1; i++) {
            var tallestHeight = $("#mpProductGrid li.r" + i + ":first-child").height();
            $("#mpProductGrid li.r" + i).each(function(){
                if ($(this).height() > tallestHeight) 
                    tallestHeight = $(this).height();
            });
            $("#mpProductGrid li.r" + i).each(function(){
                $(this).height(tallestHeight);
            });
        }
        $("#mpProductGrid ul.column:nth-child(6)").css("border-right", "2px solid #ccc");
    }); 
}

function mpJQueryDialogBoxGenControlInit(dialogBox, dialogBoxOpener, dialogBoxCloser){
    $(document).ready(function(){
        $('#' + dialogBoxOpener).click(function(){
            $('#' + dialogBox).show();
        });
        $('#' + dialogBoxCloser).click(function(){
            //$('#' + targetSelector).children().remove();
            $('#' + dialogBox).hide();
        });
    });
}

function mpJQueryProductBoxHoverInit(){
    $(document).ready(function(){
    
        $('.mpProductBox').mouseover(function(){
            $(this).css('border-color', '#000');
            $(this).css('cursor', 'pointer');
            $(this).find('a').css('color', '#000');
        });
        $('.mpProductBox').mouseout(function(){
            $(this).css('border-color', '#ccc');
            $(this).css('cursor', 'normal');
            $(this).find('a').css('color', '#36c');
        });
        
        $('.mpProductBox').click(function(){
        
            var checkCount = 0;
            $('#productCompareTarget input').each(function(i){
                if ($(this).attr('checked')) 
                    checkCount++;
            });
            if (checkCount == 5) {
                if ($(this).next().attr('checked') == true) {
                    $(this).next().removeAttr('checked');
                }
                else {
                    alert('Please uncheck other products. Choose ONLY up to 5 products!');
                    $(this).next().removeAttr('checked');
                }
            }
            else {
                $(this).find('a').attr('href', '#'); //remove href from name	
                if ($(this).next().attr('checked') == true) {
                    $(this).next().removeAttr('checked');
                    //alert('removed');
                }
                else {
                    $(this).next().attr('checked', 'checked');
                    //alert('added');
                }
            }
        });
        
        $('.mpProductBoxWrapper input').click(function(){       
            var checkCount = 0;
            $('#productCompareTarget input').each(function(i){
                if ($(this).attr('checked')) 
                    checkCount++;
            });
			
            if (checkCount > 5) {
                alert('Please uncheck other products. Choose ONLY up to 5 products!');
                $(this).removeAttr('checked');   
            } else {
                $(this).find('a').attr('href', '#'); //remove href from name	
            }
        });
    });
}

function mpInitToolTipsGridBySelector(mpSelector) {
  $(document).ready(function(){
    $(mpSelector).tooltip({
		showURL: false,
		top: -10,
		right: 10
	});
  });
}

