// ######################################### //
// 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, 'swmedium', medium, '.');
      
      fillFormValue(sw, 'swsource', source,'.');
      fillFormValue(sw, 'swterm', term,'.');
      fillFormValue(sw, 'swcontent', content,'.');
      fillFormValue(sw, 'swcampaign', campaign,'.');
      fillFormValue(sw, 'swcsegment', csegment,'.');
	  
	  formData = readCookie('_formData');
	  if (formData !== false) {
		  formData = formData.split('_formData=');
		  formData = formData[1];
		  formData = formData.split(';');
		  formData = formData[0];
		  formData = formData.split(',');
		  for (var i = 0; i < formData.length; i++) {
			  formDataSplit = formData[i].split(':');
			  formFieldName = formDataSplit[0];
			  formFieldValue = formDataSplit[1];
			  fillFormValue(sw, formFieldName, formFieldValue,'#');
		  }
	  }
      

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


	// Function to change other answers which are contigent on a primary question
	// Author: Vitaliy Isikov <visikov@gmail.com>
	//  So essentially, if user selects None in A (contingentPrimary) then the values for B and C (contingentSecondary) automatically switch to None (instantly) and the class â€œgreyedOutâ€ is added to B and C (contingentSecondary) 
	//  A will be â€œcontingentPrimaryâ€
	//  B and C will be â€œContingentSecondaryâ€
	// EAM
	jQuery('select[name="EAM"]').change( function() {
		var val = jQuery(this).val();
		if (val.toLowerCase() == 'none') {
			if (jQuery('select[name="EAMStatus"] option[value="none"]').length > 0 ) {
				jQuery('select[name="EAMStatus"] option[value="none"]').attr('selected', true);
			}
			else {
				jQuery('select[name="EAMStatus"]').append(jQuery("<option></option>").attr("value", "none").text("None").attr("selected", true));
			}
			if (jQuery('select[name="EAMSat"] option[value="none"]').length > 0 ) {
				jQuery('select[name="EAMSat"] option[value="none"]').attr('selected', true);
			}
			else {
				jQuery('select[name="EAMSat"]').append(jQuery("<option></option>").attr("value", "none").text("None").attr("selected", true));
			}
			
			jQuery('select[name="EAMStatus"]').addClass('greyedOut').attr('disabled', true);
			jQuery('select[name="EAMSat"]').addClass('greyedOut').attr('disabled', true);
		}
		else {
			jQuery('select[name="EAMStatus"]').removeClass('greyedOut').removeAttr('disabled');
			jQuery('select[name="EAMSat"]').removeClass('greyedOut').removeAttr('disabled');
		}	
	});
	
	// CRM
	jQuery('select[name="CRM"]').change( function() {
		var val = jQuery(this).val();
		if (val.toLowerCase() == 'none') {
			if (jQuery('select[name="CRMStatus"] option[value="none"]').length > 0 ) {
				jQuery('select[name="CRMStatus"] option[value="none"]').attr('selected', true);
			}
			else {
				jQuery('select[name="CRMStatus"]').append(jQuery("<option></option>").attr("value", "none").text("None").attr("selected", true));
			}
			if (jQuery('select[name="CRMSat"] option[value="none"]').length > 0 ) {
				jQuery('select[name="CRMSat"] option[value="none"]').attr('selected', true);
			}
			else {
				jQuery('select[name="CRMSat"]').append(jQuery("<option></option>").attr("value", "none").text("None").attr("selected", true));
			}
			jQuery('select[name="CRMStatus"]').addClass('greyedOut').attr('disabled', true);
			jQuery('select[name="CRMSat"]').addClass('greyedOut').attr('disabled', true);
		}
		else {
			jQuery('select[name="CRMStatus"]').addClass('greyedOut').removeAttr('disabled');
			jQuery('select[name="CRMSat"]').addClass('greyedOut').removeAttr('disabled');
		}	
	});	
	// PLM
	jQuery('select[name="PLM"]').change( function() {
		var val = jQuery(this).val();
		if (val.toLowerCase() == 'none') {
			if (jQuery('select[name="PLMStatus"] option[value="none"]').length > 0 ) {
				jQuery('select[name="PLMStatus"] option[value="none"]').attr('selected', true);
			}
			else {
				jQuery('select[name="PLMStatus"]').append(jQuery("<option></option>").attr("value", "none").text("None").attr("selected", true));
			}
			if (jQuery('select[name="PLMSat"] option[value="none"]').length > 0 ) {
				jQuery('select[name="PLMSat"] option[value="none"]').attr('selected', true);
			}
			else {
				jQuery('select[name="PLMSat"]').append(jQuery("<option></option>").attr("value", "none").text("None").attr("selected", true));
			}
			jQuery('select[name="PLMStatus"]').addClass('greyedOut').attr('disabled', true);
			jQuery('select[name="PLMSat"]').addClass('greyedOut').attr('disabled', true);
		}
		else {
			jQuery('select[name="PLMStatus"]').addClass('greyedOut').removeAttr('disabled');
			jQuery('select[name="PLMSat"]').addClass('greyedOut').removeAttr('disabled');
		}	
	});		  
	// SCP
	jQuery('select[name="SCP"]').change( function() {
		var val = jQuery(this).val();
		if (val.toLowerCase() == 'none') {
			if (jQuery('select[name="SCPStatus"] option[value="none"]').length > 0 ) {
				jQuery('select[name="SCPStatus"] option[value="none"]').attr('selected', true);
			}
			else {
				jQuery('select[name="SCPStatus"]').append(jQuery("<option></option>").attr("value", "none").text("None").attr("selected", true));
			}
			if (jQuery('select[name="SCPSat"] option[value="none"]').length > 0 ) {
				jQuery('select[name="SCPSat"] option[value="none"]').attr('selected', true);
			}
			else {
				jQuery('select[name="SCPSat"]').append(jQuery("<option></option>").attr("value", "none").text("None").attr("selected", true));
			}
			jQuery('select[name="SCPStatus"]').addClass('greyedOut').attr('disabled', true);
			jQuery('select[name="SCPSat"]').addClass('greyedOut').attr('disabled', true);
		}
		else {
			jQuery('select[name="SCPStatus"]').addClass('greyedOut').removeAttr('disabled');
			jQuery('select[name="SCPSat"]').addClass('greyedOut').removeAttr('disabled');
		}	
	});
	
      // On Form Submit
      sw('form').submit(function (e) {
			
              //hide errors
            sw(".error").hide();
            retval = true;

            //required fields
            sw(".swrequired").each(function () {
                  var def = sw(this).attr("default");
				  var ret;
                  if (sw(this).attr("type") == "radio")
                  { 
                      if (!sw(this).attr("checked"))
                      {
                        //validateEmpty(sw(this).context);
                        ret = "Please select one";
                      }
                  }
				  else if (sw(this).attr("type") == "select-one") {
					  /*
						// check for additional "default" values on select boxes
						I fixed the select none issue and there is now validation for pages 2 and 3. The validation checks to see if it's a select field first, then if it is checks the value of it. Since there is no value stored for <option>Please Select</option> it returns "Please Select". If the script sees that, it know the field wasn't filled in.

						That's on line 254 of the script, it can be changed to anything you need for future use. You can also append it using the or `||` operator like this:

							   if (sw(this).val() == "Please Select" || sw(this).val() == "Another Defualt Value Possibility" ) 

						That will check to see if either is true, if any 1 is true, then mark the field with error and don't submit form.
					  
					  */
					  if (sw(this).val() == "Please Select") {
						  sw(this).css({
							  'background' : '#ffc9bb'
						  });
						  ret = 'Required field.\n';
					  }
					  else {
						  sw(this).css({
							  'background' : '#ffffff'
						  });
						  ret = '';
					  }
				  }
                  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
            {
				// if <input type="hidden" name="dontCookieThis" value="true" />  is located on the form, don't write the cookie
				if (sw("input[name='dontCookieThis']").val() != "true") {
					var data = sw("input[name='FirstName'], input[name='LastName'], input[name='Email'], input[name='Company'], input[name='Phone'], select[name='Product'], select[name='BuyingHorizon'], select[name='Industry'], select[name='EmployeeSize'], select[name='AnnualRevenue'], select[name='JobFunction'], select[name='JobRole'], input[name='Website'], input[name='Address1']").serialize();
					data = data.replace(/=/g, ':');
					data = data.replace(/&/g, ',');
					data = '_formData=' + data;
					createCookie(data, 270);
				}
            }

            return retval;
        });

jQuery.noConflict();
});


function createCookie(data,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = data+expires+"; path=/";
}

function readCookie(name) {
	var ca = document.cookie;
	if (ca.search(name) !== -1) {
		return ca;
	}
	else {
		return false;
	}
}

function eraseCookie(name) {
	createCookie(name + "=",-1);
}

function fillFormValue(sw, classid, value, type) {
	value = unescape(value);
	value = value.replace(/\+/g, ' ');
	if (classid == 'swmedium') {
		var valueArray = new Array('', '-', '(none)', 'Cpc', 'organic', 'Banner', 'Email', 'referral', 'dm');
		for (var i = 0; i < valueArray.length; i++) {
			var checkValue = valueArray[i].toLowerCase();
			var sentValue = value.toString().toLowerCase();
			// pass as integer 
			/* if (sentValue == checkValue) {
				if (i != 0) {
					value = i - 1;
				}
				else {
					value = i;
				}
			}*/ 
			// pass as eloqua GUID
			if (sentValue == '') {
				value = '20F2589F-A014-DD11-A161-005056B21571';
			}
			if (sentValue == '-') {
				value = '20F2589F-A014-DD11-A161-005056B21571';
			}
			if (sentValue == '(none)') {
				value = '20F2589F-A014-DD11-A161-005056B21571';
			}
			if (sentValue == 'cpc') {
				value = 'A92F67F4-E4F4-E011-86ED-005056B23E4A';
			}
			if (sentValue == 'organic') {
				value = '1C1C96B5-A014-DD11-A161-005056B21571';
			}
			if (sentValue == 'banner') {
				value = '754E7425-61F6-E011-86ED-005056B23E4A';
			}
			if (sentValue == 'email') {
				value = '691FE085-747A-E011-9E98-005056B23E4A';
			}
			if (sentValue == 'referral') {
				value = '6AAE062E-61F6-E011-86ED-005056B23E4A';
			}
			if (sentValue == 'dm') {
				value = 'DD269F37-61F6-E011-86ED-005056B23E4A';
			}
			
		}
	}
	
	if (sw('select' + type + classid + ' option[value="' + value  + '"]').length > 0 ) {
		sw('select' + type + classid + ' option[value="' + value  + '"]').attr('selected','selected');
	}
	else {
		// city wasn't in th select list so lets add it.      
		sw('select' + type + classid ).append(sw("<option></option>").attr("value", value).text(value).attr("selected", true));
	}
  
	if(sw('input' + type + classid).length > 0 ) {
		sw('input' + type + 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;

}
