// ######################################### //
// validation, UTMZ scrape, GEO IP functionality
// for use on ibis.com, advanceddistributionsoftware.com, dynamicscare.com
// Version 1.1 - Feb 26, 2011
// ######################################### //

// function to search inside arrays
Array.prototype.find = function(searchStr) {
  var returnArray = false;
  for (i=0; i<this.length; i++) {
    if (typeof(searchStr) == 'function') {
      if (searchStr.test(this[i])) {
        if (!returnArray) { returnArray = [] }
        returnArray.push(i);
      }
    } else {
      if (this[i]===searchStr) {
        if (!returnArray) { returnArray = [] }
        returnArray.push(i);
      }
    }
  }
  return returnArray;
}

// Jquery
$(document).ready(function () {

        // setup countries where form is NOT blocked
        // for IBIS and DC = USA, england, australia, new zealand, ireland and canada 
        // for ADS = no blocking (for now ADS uses the same as IBIS and DC)
        // country code list http://countrycode.org/
        var validcountries = [ 'US','GB','AU','NZ','IE','CA' ];
        var restrictMsg = "We're sorry this content is not available in your geographic location.";
        
        // setup variables used
        var sw = jQuery.noConflict();
        var hasloc = false;
        var city = '';
        var state = '';
        var country = '';
        var countrycode = '';
        var location = '';
        var region = "";
        var zip = "";
        
        // Which GEOIP database to use
        var bGoogle = false;       
        var bMaxMind =true;

        // query GEOIP provider
        if (bGoogle)
         {
          if (google.loader.ClientLocation != null) {
              hasloc = true;
              city = google.loader.ClientLocation.address.city;
              region = google.loader.ClientLocation.address.region;
              location = google.loader.ClientLocation.latitude + ' ' + google.loader.ClientLocation.longitude;
          }
        }
        else
        {
            // maxmind
            // http://www.maxmind.com/app/javascript_city
            countrycode = geoip_country_code();
            country = geoip_country_name();
            city = geoip_city();
            state = geoip_region_name();
            region = geoip_region();
            location = geoip_latitude() + ' ' + geoip_longitude();
            zip = geoip_postal_code();
        }
      // Debug GEOIP
      // debugMsg = countrycode + ',' + country + ',' + city + ',' + state + ',' + region + ',' + location + ',' + zip;
      // alert(debugMsg);
      
      // Populate Form
      fillFormValue(sw, 'swcity', city);
      fillFormValue(sw, 'swcountry', country);
      fillFormValue(sw, 'swstate', state);
      fillFormValue(sw, 'swregion', region);
      fillFormValue(sw, 'swlocation', location);
      fillFormValue(sw, 'swzip', zip);
      
      fillFormValue(sw, 'swsource', source);
      fillFormValue(sw, 'swmedium', medium);
      fillFormValue(sw, 'swterm', term);
      fillFormValue(sw, 'swcontent', content);
      fillFormValue(sw, 'swcampaign', campaign);
      fillFormValue(sw, 'swcsegment', csegment);
      

      // Restrict Form Access to specific valid countrycodes
      // if a div with the id "swrestricted" exists on the page, then check for valid countries
      if (sw('#swrestricted').length > 0)
      {
        if(!validcountries.find(countrycode))
        {
            // hide content region
            // sw('.swvalidate').hide();
            // hide entire form
            sw('form').hide();
            // show custom restricted messsage
            // sw('#swrestricted').show();
            // // show default restriced message
            sw('#swrestricted').after("<span class=error>" + restrictMsg + "</span>");
        }
      }
  

      // On Form Submit
      sw('.swvalidate').submit(function (e) {
			
              //hide errors
            sw(".error").hide();
            retval = true;
            
            //required fields
            sw(".swrequired").each(function () {
            
                  var def = sw(this).attr("default");
                  
                  if (sw(this).attr("type") == "radio")
                  { 
                      if (!sw(this).attr("checked"))
                      {
                        //validateEmpty(sw(this).context);
                        ret = "Please select one";
                      }
                  }
                  else {
                  
                  
                  if (def)
                  {
                      ret = validateEmpty(sw(this).context, def);
                   }
                  else
                  {
                      ret = validateEmpty(sw(this).context);
                  }
                  }
                  if (ret != '')
                  {
                        sw(this).after("<span class=error>" + ret + "</span>");
                        retval = false;
                  } 
            }); // END required fields
	
            //email no free emails
            sw(".swemailnofree").each(function () {
              ret = validateFreeEmail(sw(this).context);
              if (ret != '')
              {
                    sw(this).after("<span class=error>" + ret + "</span>");

                    retval = false;
              } 
            });
            
            //email free emails allowed
            sw(".swemail").each(function () {
              ret = validateEmail(sw(this).context);
              if (ret != '')
              {
                    sw(this).after("<span class=error>" + ret + "</span>");

                    retval = false;
              } 
            });
            
            
            //phone
            sw(".swphone").each(function () {
              ret = validatePhone(sw(this).context);
              if (ret != '')
              {
                    sw(this).after("<span class=error>" + ret + "</span>");

                    retval = false;
              } 
            });

            // If errors found, prevent submission of form
            if (!retval)
            {
               e.preventDefault();
            }
            else
            {
              //alert('ok submitting form');
            }
            return retval;
        });

jQuery.noConflict();

});


function fillFormValue(sw, classid, value)
      {
        if (sw('select.' + classid + ' option[value="' + value  + '"]').length > 0 )
        {
          sw('select.' + classid + ' option[value="' + value  + '"]').attr('selected','selected');
        }
        else
        {
            // city wasn't in th select list so lets add it.      
            sw('select.' + classid ).append(sw("<option></option>").attr("value", value).text(value).attr("selected","selected"));
        }
      
        if(sw('input.' + classid).length > 0 )
        {
            sw('input.' + classid).val(value);
        }
}



/*


revised Nov 16 by Ryan F
Cannot be Empty:
.formtextinput

Must be valid email:
.formemailinput
.formemailinputnofree

Must not be "Select One"
.formselectinput 

Phone 10+ digit, no alpha, symbols/punc ok
.formphoneinput

*/
function validateFormOnSubmit(theForm) {
var reason = "";
  reason += validateName(theForm.name);
  reason += validatePhone(theForm.phone);
  reason += validateEmail(theForm.email);
  if (reason != "") {
    alert("Some fields need correction:\n\n" + reason );
    return false;
  }
  return true;
}

function validateEmpty(fld) {
    var error = "";
    if (fld.value.length == 0) {
        fld.style.background = '#ffc9bb'; 
        error = "Required field.\n"
    } else {
        fld.style.background = 'White';
    }
    return error;  
}

function validateEmpty(fld, def) {
    var error = "";
    if ((fld.value.length == 0) || (fld.value == def) ){
        fld.style.background = '#ffc9bb'; 
        error = "Required field.\n"
    } else {
        fld.style.background = 'White';
    }
    return error;  
}


function validateName(fld) {
    var error = "";
    if (fld.value == "" || fld.value == "Your Name") {
        fld.style.background = '#ffc9bb'; 
        error = "Please enter your first and last name.\n\n";
	} else if (fld.value.length < 2) {
        fld.style.background = '#ffc9bb';
        error = "Please enter your first and last name.\n\n";
    } else {
        fld.style.background = 'White';
    }
    return error;
}

function validatePhone(fld) {
    var error = "";
    if (fld.value == "" || fld.value == "Your Phone Number") {
        fld.style.background = '#ffc9bb'; 
        error = "Please enter your phone number.\n\n";
	} else if (fld.value.length < 9) {
        fld.style.background = '#ffc9bb';
        error = "Please enter your 10 digit phone number.\n\n";
    } else {
        fld.style.background = 'White';
    }
    return error;
}

function trim(s)
{
  return s.replace(/^\s+|\s+$/, '');
}

function validateEmail(fld) {
    var error="";
    var tfld = trim(fld.value);                        // value of field with whitespace trimmed off
    var emailFilter = /^[^@]+@[^@.]+\.[^@]*\w\w$/ ;  //old
	//var emailFilter = /^([a-zA-Z0-9_.-\+])+@(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,4})+$/;
	
    var illegalChars = /[\(\)\<\>\,\;\:\\\"\[\]]/ ;
    if (fld.value == "" || fld.value == "Your Email") {
        fld.style.background = '#ffc9bb';
        error = "Please enter your email address.\n\n";
    } else if (!emailFilter.test(tfld)) {              //test email for illegal characters
        fld.style.background = '#ffc9bb';
        error = "The email address you entered is not valid.\n\n";
    } else if (fld.value.match(illegalChars)) {
        fld.style.background = '#ffc9bb';
        error = "Your email address contains illegal characters.\n\n";
    } else {
        fld.style.background = 'White';
    }
    return error;
}



function validateFreeEmail(fld) {

    var error="";

    var tfld = trim(fld.value);                        // value of field with whitespace trimmed off

    var emailFilter = /^[^@]+@[^@.]+\.[^@]*\w\w$/ ;
	//var emailFilter = /^([a-zA-Z0-9_.-\+])+@(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,4})+$/;
	
    var illegalChars = /[\(\)\<\>\,\;\:\\\"\[\]]/ ;

    var telusEmail = /@telus\.com/i;

    var hotmailEmail = /@hotmail\.com/i;

    var liveEmail = /@live\.com/i;

    var gmailEmail = /@gmail\.com/i;

    var yahooEmail = /@yahoo\.com/i;

    var yahoocaEmail = /@yahoo\.ca/i;

    var msnEmail = /@msn\.com/i;

    var attEmail = /@att\.com/i;

    var roadrunnerEmail = /@roadrunner\.com/i;

    var comcastEmail = /@comcast\.net/i;

    var rogersEmail = /@rogers\.com/i;
    
    var sympaticoEmail = /@sympatico\.ca/i;

   var defaultError = "Please use your office (business) email address.";

    if (fld.value == "" || fld.value == "Your Email") {

        fld.style.background = '#ffc9bb';

        error = "Please enter your office (business) email address.\n\n";

    } else if (!emailFilter.test(tfld)) {              //test email for illegal characters

        fld.style.background = '#ffc9bb';

        error = "The email address you entered is not valid.\n\n";

    } else if (fld.value.match(illegalChars)) {

        fld.style.background = '#ffc9bb';

        error = "Your email address contains illegal characters.\n\n";

    } else if (fld.value.match(telusEmail)) {

        fld.style.background = '#ffc9bb';

        error = defaultError;

    } else if (fld.value.match(hotmailEmail)) {

        fld.style.background = '#ffc9bb';

      error = defaultError;

    } else if (fld.value.match(liveEmail)) {

        fld.style.background = '#ffc9bb';

       error = defaultError;

    } else if (fld.value.match(gmailEmail)) {

        fld.style.background = '#ffc9bb';

        error = defaultError;

    } else if (fld.value.match(yahooEmail)) {

        fld.style.background = '#ffc9bb';

        error = defaultError;

    } else if (fld.value.match(yahoocaEmail)) {

        fld.style.background = '#ffc9bb';

        error = defaultError;

    } else if (fld.value.match(msnEmail)) {

        fld.style.background = '#ffc9bb';

        error = defaultError;

    } else if (fld.value.match(attEmail)) {

        fld.style.background = '#ffc9bb';

        error = defaultError;

    } else if (fld.value.match(roadrunnerEmail)) {

        fld.style.background = '#ffc9bb';

        error = defaultError;

    } else if (fld.value.match(comcastEmail)) {

        fld.style.background = '#ffc9bb';

        error = defaultError;

    } else if (fld.value.match(sympaticoEmail)) {

        fld.style.background = '#ffc9bb';

        error = defaultError;

    } else if (fld.value.match(rogersEmail)) {

        fld.style.background = '#ffc9bb';

        error = defaultError;

    } else {

        fld.style.background = 'White';

    }

    return error;

}

				
