var myCaptKey = 1000;
var theUrl = "";
var extServ = "/externalStoreFrontServices";
/*!
Math.uuid.js (v1.4)
http://www.broofa.com
mailto:robert@broofa.com

Copyright (c) 2009 Robert Kieffer
Dual licensed under the MIT and GPL licenses.
*/

/*
 * Generate a random uuid.
 *
 * USAGE: Math.uuid(length, radix)
 *   length - the desired number of characters
 *   radix  - the number of allowable values for each character.
 *
 * EXAMPLES:
 *   // No arguments  - returns RFC4122, version 4 ID
 *   >>> Math.uuid()
 *   "92329D39-6F5C-4520-ABFC-AAB64544E172"
 * 
 *   // One argument - returns ID of the specified length
 *   >>> Math.uuid(15)     // 15 character ID (default base=62)
 *   "VcydxgltxrVZSTV"
 *
 *   // Two arguments - returns ID of the specified length, and radix. (Radix must be <= 62)
 *   >>> Math.uuid(8, 2)  // 8 character ID (base=2)
 *   "01001010"
 *   >>> Math.uuid(8, 10) // 8 character ID (base=10)
 *   "47473046"
 *   >>> Math.uuid(8, 16) // 8 character ID (base=16)
 *   "098F4D35"
 */
Math.uuid = (function() {
  // Private array of chars to use
  var CHARS = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split(''); 

  return function (len, radix) {
    var chars = CHARS, uuid = [];
    radix = radix || chars.length;

    if (len) {
      // Compact form
      for (var i = 0; i < len; i++) uuid[i] = chars[0 | Math.random()*radix];
    } else {
      // rfc4122, version 4 form
      var r;

      // rfc4122 requires these characters
      uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-';
      uuid[14] = '4';

      // Fill in random data.  At i==19 set the high bits of clock sequence as
      // per rfc4122, sec. 4.1.5
      for (var i = 0; i < 36; i++) {
        if (!uuid[i]) {
          r = 0 | Math.random()*16;
          uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];
        }
      }
    }

    return uuid.join('');
  };
})();

/* ---------------------------------------------------------------
-   function submitForm
-
-   purpose - validates inputs, and sends request for catalog to
-             a specific email account.
-            
-
-   created date  2/26/2009
-   written by  Mike Kucharski  & Jef Scott 
-----------------------------------------------------------------*/
function submitForm()
{
   var valid = "Y";

   // --------------------- captcha -------------------
   var captcha = $("#captchaResponse").val();
   captcha = captcha.replace(/ /g,"$!20");
   if (captcha == "")
   {
      valid = "N";
      $('#captchaResponse').focus();
      $('#errcaptchaResponse').html('<span id="captcha.errors" class="formError">CAPTCHA response invalid.</span>');
   }
   else
   {
      $('#errcaptchaResponse').html("");
   }

   var storeId = $("#storeId").val();
   var invalidchars = "can not contain the following: / % ; \ ? { } < > ( ) & + : # \" \'  ";
   


// --------------------- style number  -------------------
	if ($('#style').length)
	{
		var style = $("#style").val();
		
		if (isDataDirty(style))
		{
			$('#style').focus();
			$('#errstyle').html('<span id="style.errors" class="formError">Style ' +invalidchars+ '.</span>');
			valid = "N";
		}
		else
		{
			$('#errstyle').html("");
		}
	}

// --------------------- Subject -------------------
	if ($('#subject').length)
	{
		var subject = $("#subject").val();
		subject = subject.replace(/ /g,"$!20");
		if (subject == "")
		{
			valid = "N";
			$('#subject').focus();
			$('#errsubject').html('<span id="subject.errors" class="formError">Subject is required.</span>');
		}
		else
		{
			$('#errsubject').html("");
		}
		
		if (isDataDirty(subject))
		{
			$('#subject').focus();
			$('#errsubject').html('<span id="subject.errors" class="formError">Subject ' +invalidchars+ '.</span>');
			valid = "N";
		}
	}

// ------------------------ email --------------------
	if ($('#email').length)
	{
		var email = $("#email").val();
		$('#erremail').html("");
		if (email == "")
		{
			$('#email').focus();
			$('#erremail').html('<span id="email.errors" class="formError">E-Mail is required.</span>');
			valid = 'N';
		}
		if (email.indexOf("@") <= 0)
		{
			$('#email').focus();
			$('#erremail').html('<span id="email.errors" class="formError">Valid E-Mail is required.</span>');
			valid = 'N';
		}
		else
		{
			if (email.indexOf(".") <= 0)
			{
				$('#email').focus();
				$('#erremail').html('<span id="email.errors" class="formError">Valid E-Mail is required.</span>');
				valid = 'N';
			}
		}
		
		if (isDataDirty(email))
		{
			$('#email').focus();
			$('#erremail').html('<span id="email.errors" class="formError">Email ' +invalidchars+ '</span>');
			valid = "N";
		}
	}

// --------------------- zip  -------------------
	if ($('#zip').length)
	{
		var zipCode = $("#zip").val();
		if (zipCode == "")
		{
			//$('#zip').focus();
			//$('#errzip').html('<span id="zip.errors" class="formError">Zip Code is required.</span>');
			//valid = "N";
		}
		else
		{
			$('#errzip').html("");
		}
		
		if (isDataDirty(zipCode))
		{
			$('#zip').focus();
			$('#errzip').html('<span id="zip.errors" class="formError">Zip Code ' +invalidchars+ '</span>');
			valid = "N";
		}
	}

// --------------------- state  -------------------
	if ($('#state').length)
	{
		var state = $("#state").val();
		if (state == "")
		{
			//$('#state').focus();
			//$('#errstate').html('<span id="state.errors" class="formError">State/Province is required.</span>');
			//valid = "N";
		}
		else
		{
			$('#errstate').html("");
		}
	}

// --------------------- city  -------------------
	if ($('#city').length)
	{
		var city = $("#city").val();
		city = city.replace(/ /g,"$!20");
		if (city == "")
		{
			//$('#city').focus();
			//$('#errcity').html('<span id="city.errors" class="formError">City is required.</span>');
			//valid = "N";
			
			city = "$!20";
		}
		else
		{
			$('#errcity').html("");
		}
		
		if (isDataDirty(city))
		{
			$('#city').focus();
			$('#errcity').html('<span id="city.errors" class="formError">City ' +invalidchars+ '</span>');
			valid = "N";
		}
	}

// --------------------- street address2  -------------------
	if ($('#addr2').length)
	{
		var addr2 = $("#addr2").val();
		addr2 = addr2.replace(/ /g,"$!20");
		if (addr2 == "")
		{
			addr2 = "$!20";
		}
		if (isDataDirty(addr2))
		{
			$('#addr2').focus();
			$('#erraddr2').html('<span id="addr2.errors" class="formError">Address line 2 ' +invalidchars+ '</span>');
			valid = "N";
		}
		else
		{
			$('#erraddr2').html("");
		}
	}

// --------------------- street address  -------------------
	if ($('#addr1').length)
	{
		var addr1 = $("#addr1").val();
		addr1 = addr1.replace(/ /g,"$!20");
		if (addr1 == "")
		{
			//$('#addr1').focus();
			//$('#erraddr1').html('<span id="addr1.errors" class="formError">Street Address 1 is required.</span>');
			//valid = "N";
			
			addr1 = "$!20";
		}
		else
		{
			$('#erraddr1').html("");
		}
		
		if (isDataDirty(addr1))
		{
			$('#addr1').focus();
			$('#erraddr1').html('<span id="addr1.errors" class="formError">Address line 1 ' +invalidchars+ '.</span>');
			valid = "N";
		}
	}

// --------------------- last name -------------------
	if ($('#lastName').length)
	{
		var lname = $("#lastName").val();
		lname = lname.replace(/ /g,"$!20");
		if (lname == "")
		{
			$('#lastName').focus();
			$('#errlastName').html('<span id="lastName.errors" class="formError">Last Name is required.</span>');
			valid = "N";
		}
		else
		{
			$('#errlastName').html("");
		}
		
		if (isDataDirty(lname))
		{
			$('#lastName').focus();
			$('#errlastName').html('<span id="lastName.errors" class="formError">Last Name ' +invalidchars+ '.</span>');
			valid = "N";
		}
	}

// --------------------- first name -------------------
	if ($('#firstName').length)
	{
		var fname = $("#firstName").val();
		fname = fname.replace(/ /g,"$!20");
		if (fname == "")
		{
			valid = "N";
			$('#firstName').focus();
			$('#errfirstName').html('<span id="firstName.errors" class="formError">First Name is required.</span>');
		}
		else if (fname == "aniTest")
	   {
			$('#confirmation').html("<h3>Your request has been submitted. Thank you!&nbsp;</h3>");
			$('#mybuttons').hide(1000);
			$('#captcha').hide(1000);
			$('#welcome').hide(1000);
			$('#formElements').hide(1000);
			$('#confirmation').fadeIn(1000);
			
			//$('html, body').animate({scrollTop:0}, 'slow');
			//return false;
		}
		else
		{
			$('#errfirstName').html("");
		}
		
		if (isDataDirty(fname))
		{
			$('#firstName').focus();
			$('#errfirstName').html('<span id="firstName.errors" class="formError">First Name ' +invalidchars+ '.</span>');
			valid = "N";
		}
	}

// --------------------- SPORT 1.  -------------------
	if ($('#sport1').length)
	{
		var sport1 = $("#sport1").val();
		if (sport1 == "")
		{
			valid = "N";
			$("#errsport1").html('<span id="sport1.errors" class="formError">Sport is required.</span>');
		}
		else
		{
			$("#errsport1").html("");
		}
	}

// --------------------- FAX NO.  -------------------
	if ($('#fax').length)
	{
		var faxNumber = $("#fax").val();
		if (faxNumber == "")
		{
			faxNumber = "$!20";
		}  
		
		if (isDataDirty(faxNumber))
		{
			$('#fax').focus();
			$('#errfax').html('<span id="fax.errors" class="formError">Fax ' +invalidchars+ '.</span>');
			valid = "N";
		}
		else
		{
			$('#errfax').html("");
		}
	}

// --------------------- PHONE  -------------------
	if ($('#phone').length)
	{
		var phone = $("#phone").val();
		if (phone == "")
		{
			phone = "$!20";
		}  

		if (isDataDirty(phone))
		{
			$('#phone').focus();
			$('#errphone').html('<span id="phone.errors" class="formError">Phone ' +invalidchars+ '.</span>');
			valid = "N";
		}
		else
		{
			$('#errphone').html("");
		}
	}

// --------------------- MESSAGE FIELD  -------------------
	if ($('#messageBox').length)
	{   
		var messageBox = $("#messageBox").val();
		
		if ((messageBox.indexOf(">") >= 0) || 
			(messageBox.indexOf("<") >= 0) || 
			(messageBox.indexOf("&") >= 0) )
		{
			$('#messageBox').focus();
			$('#errmessageBox').html('<span id="messageBox.errors" class="formError">Message can not contain <, >, or & symbols</span>');
			valid = "N";
		}
		else
		{
			$('#errmessageBox').html("");
		}
	}

// -------------------- if valid send request -----------------------
	if (valid == "Y")
	{
		var cResponse = $('#captchaResponse').val();
		theUrl = extServ + "/rest/v1/logEmailEvent/" + storeId;
	
		var sUrl = extServ + "/rest/v1/validateCaptcha/" + myCaptKey +"/" + cResponse;
		$.get(sUrl, function(data) { validateCaptcha(data); });     
	}
	else
	{
		setCaptcha();
	}

	//return false to disable default anchor action
	return false;
} // end of submitForm function

   //common function to look for invalid chars
function isDataDirty(data)
{
	if ( data == undefined ) {return false;}

	if 	(
		(data.indexOf("/") >= 0) || 
		(data.indexOf("%") >= 0) || 
		(data.indexOf(";") >= 0) || 
		(data.indexOf("\\") >= 0) || 
		(data.indexOf("?") >= 0) ||
		(data.indexOf("{") >= 0) ||
		(data.indexOf("}") >= 0) ||
		(data.indexOf("<") >= 0) ||
		(data.indexOf(">") >= 0) ||
		(data.indexOf(")") >= 0) ||
		(data.indexOf("(") >= 0) ||
		(data.indexOf("&") >= 0) ||
		(data.indexOf("+") >= 0) ||
		(data.indexOf(":") >= 0) ||
		(data.indexOf("#") >= 0) ||
		(data.indexOf("'") >= 0) ||
		(data.indexOf('"') >= 0) 
	)
		{return true;}
}

function checkCaptcha()
{
    var cResponse = $('#captchaResponse').val();
    var sUrl = extServ + "/rest/v1/validateCaptcha/" + myCaptKey +"/" + cResponse;
    $.get(sUrl, function(data) { validateCaptcha(data); });     
}


function validateCaptcha(data)
{
   if ($(data).find("boolean").text() == "true")
   {
      $.post(theUrl, $("#contactUsForm").serialize(), function(data) { finishRequest(data); });
   }
   else
   {
      setCaptcha();
      $('#captchaResponse').focus();
      $('#errcaptchaResponse').html('<span id="captcha.errors" class="formError">CAPTCHA response invalid</span>');
   }
}

function setCaptcha()
{
     
     myCaptKey = Math.uuid();
     $("#captchaImg").attr("src", extServ + "/CaptchaService?captchaGuid="+ myCaptKey);    
}

function finishRequest(data)
{
   var mystats = $(data).text();
   if (mystats.indexOf("Failed") >= 0)
   {
     alert('Sorry, your request was not submitted.  Please try again.');
   }
   else
   {
	$('#confirmation').html("<h3>Your request has been submitted. Thank you!&nbsp;</h3>");
	$('#mybuttons').hide(1000);
	$('#captcha').hide(1000);
	$('#welcome').hide(1000);
	$('#formElements').hide(1000);
	$('#confirmation').fadeIn(1000);
   }
}

