

var SmartAssist = function(){
	var CHECK_AGE_SVC = "http://datastore.arsecom.com/kmart/smart_assist/age.php";
	var EMAIL_CHECK = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
	var ZIP_CHECK = /^\d{5}(-\d{4})?$/;
	
	var formValidated = false;
	
	var $errorMsgs,
		$unavailableErr,
		$dobYear,
		$dobDay,
		$dobMonth,
		$form,
		$formDiv,
		$state,
		$submitButton,
		$email,
		$zipCode,
		$notQualifiedErr;
		
		
	/* cookies */
	var Cookies = {
		create: function(name,value,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 = name+"="+value+expires+"; path=/";
		},

		read: function(name) {
			var nameEQ = name + "=";
			var ca = document.cookie.split(';');
			for(var i=0;i < ca.length;i++) {
				var c = ca[i];
				while (c.charAt(0)==' ') c = c.substring(1,c.length);
				if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
			}
			return null;
		},

		erase: function(name) {
			this.create(name,"",-1);
		}
	};
	

	/* populate month, day for DOB */
	function populateDobFields() {
		// days
		var opt_text = "";
		for (var d=1;d<=31;d++) {
			if (d<=9) d = '0' + d;
			opt_text += "<option value=\"" + d + "\">" + d + "</option>\n";
		}
		$dobDay.append(opt_text);
		
		// years
		opt_text = "";
		for (var d=1995;d>=1900;d--) {
			opt_text += "<option value=\"" + d + "\">" + d + "</option>\n";
		}
		$dobYear.append(opt_text);
	};


	function hookJqueryObjects() {
		
		// display form when a state is selected
		$state.change(function() {
			var sel_val = $(this).children('option:selected').val();
	
			if (sel_val == "0") {
				$formDiv.hide();
				$unavailableErr.hide();
			} else {
				$formDiv.show();
				$unavailableErr.hide();
			}
		});

		// cancel anything that will trigger a form submit - needs to run through $submitButton
		$form.submit(function() {
			return formValidated;
		});

		$submitButton.click(function() {
			validateFormPart1();	// form validation is split up into 2 fn's : second function is handler for json age check.
		});
	}
	
	function validateFormPart1() {
		var submit_form = true;
		
		$errorMsgs.css('visibility', 'hidden');
										
		// check required inputs (input.sm_req)
		$("input.sm_req").each(function() {
			if ($(this).val() == "") {
				$(this).parent().children('span').css('visibility', 'visible');
				submit_form = false;
			}
		});
		
		// check required selects (select.sm_req)
		$("select.sm_req").each(function() {
			var sel_val = $(this).children('option:selected').val();
			if (sel_val == "0") {
				$(this).parent().children('span').css('visibility', 'visible');
				submit_form = false;
			}
		});	
		
		// custom validation: zipcode
		if (isNaN($zipCode.val()) || $zipCode.val().length != 5) {
			$zipCode.parent().children('span').css('visibility', 'visible');
			submit_form = false;
		}
		
		// email
		if (!EMAIL_CHECK.test($email.val())) {
			$email.parent().children('span').css('visibility', 'visible');
			submit_form = false;
		}
		
		// initial error checking complete, issue DOB check
		if (submit_form) {
			
			// build URL:
			var request_url = CHECK_AGE_SVC +
							  "?dob=" +
							  $dobYear.children('option:selected').val() + "-" +
							  $dobMonth.children('option:selected').val() + "-" +
							  $dobDay.children('option:selected').val() +
							  "&years=18&callback=SmartAssist.validateFormPart2";
							  
			var obj=new JSONscriptRequest(request_url);     
			obj.buildScriptTag(); // Build the script tag     
			obj.addScriptTag(); // Execute (add) the script tag		
			
			//alert('request sent');
			
		} 
	

		return false;
	};
	

	function validateFormPart2(age_is_ok) {
		if (age_is_ok) {
			//set cookie for coupon
			var p_name = $("#txt_fname").val() + ' '  + $("#txt_mi").val() + ' ' + $("#txt_lname").val();
			Cookies.create("smart_assist_name",p_name,30);
			
			configResponsysFormValues();
			
			formValidated = true;
			$form.submit();

		} else {
			$notQualifiedErr.css('visibility', 'visible');
		}
	};
	
	
	
	/* set & configure hidden form fields for responses */
	function configResponsysFormValues() {
		var rand1 = Math.floor(Math.random()*999999);
		var rand2 = Math.floor(Math.random()*999999);
		var now = new Date();			
		var PREF_ID = rand1 + now.format("yyyyMMddHHmmssS") + rand2;
		var OPT_STATUS_CHANGE = now.format("yyyy-MM-dd HH:mm:ss");
		
		//set month
		var the_month = now.getMonth()+1;
		$("input#MONTH").val(the_month);		
			
		var BIRTHDATE = $("select#sel_year option:selected").val() + "-" + $("select#sel_month option:selected").val() + "-" + $("select#sel_day option:selected").val() + " 00:00:00";
	
		$("#PREF_ID").val(PREF_ID);
		$("#OPT_STATUS_CHANGE").val(OPT_STATUS_CHANGE);
		$("#BIRTHDATE").val(BIRTHDATE);

	}
	
	
	function initJqueryObjects() {
		$errorMsgs = $(".sm_err");
		$dobYear = $("#sel_year");
		$dobDay = $("#sel_day");
		$dobMonth = $("#sel_month");
		$formDiv = $("div.sa_form");
		$form = $("form#sm_form");
		$state = $("#sel_state");
		$unavailableErr = $(".sa_unavail");
		$submitButton = $("#sm_submit");
		$email = $("#txt_email");
		$zipCode = $("#txt_zipcode"),
		$notQualifiedErr = $("#sm_not_qualified");
		
	};

	function init(){
		initJqueryObjects();
		hookJqueryObjects();

		// hide form, error messages, and state not available error message
		$formDiv.hide();
		$unavailableErr.css('visibility', 'hidden');
		$errorMsgs.css('visibility', 'hidden');
		
		populateDobFields();

						
		
	};
	
	// public
	return {
		init: init,
		Cookies: Cookies,
		validateFormPart2: validateFormPart2
	}
	
}();


$(function(){
	SmartAssist.init();
});





/*
 * Date Format 1.2.2
 * (c) 2007-2008 Steven Levithan <stevenlevithan.com>
 * MIT license
 * Includes enhancements by Scott Trenda <scott.trenda.net> and Kris Kowal <cixar.com/~kris.kowal/>
 *
 * Accepts a date, a mask, or a date and a mask.
 * Returns a formatted version of the given date.
 * The date defaults to the current date/time.
 * The mask defaults to dateFormat.masks.default.
 */
var dateFormat = function () {
	var	token = /d{1,4}|m{1,4}|yy(?:yy)?|([HhMsTt])\1?|[LloSZ]|"[^"]*"|'[^']*'/g,
		timezone = /\b(?:[PMCEA][SDP]T|(?:Pacific|Mountain|Central|Eastern|Atlantic) (?:Standard|Daylight|Prevailing) Time|(?:GMT|UTC)(?:[-+]\d{4})?)\b/g,
		timezoneClip = /[^-+\dA-Z]/g,
		pad = function (val, len) {
			val = String(val);
			len = len || 2;
			while (val.length < len) val = "0" + val;
			return val;
		};

	// Regexes and supporting functions are cached through closure
	return function (date, mask, utc) {
		var dF = dateFormat;

		// You can't provide utc if you skip other args (use the "UTC:" mask prefix)
		if (arguments.length == 1 && (typeof date == "string" || date instanceof String) && !/\d/.test(date)) {
			mask = date;
			date = undefined;
		}

		// Passing date through Date applies Date.parse, if necessary
		date = date ? new Date(date) : new Date();
		if (isNaN(date)) throw new SyntaxError("invalid date");

		mask = String(dF.masks[mask] || mask || dF.masks["default"]);

		// Allow setting the utc argument via the mask
		if (mask.slice(0, 4) == "UTC:") {
			mask = mask.slice(4);
			utc = true;
		}

		var	_ = utc ? "getUTC" : "get",
			d = date[_ + "Date"](),
			D = date[_ + "Day"](),
			m = date[_ + "Month"](),
			y = date[_ + "FullYear"](),
			H = date[_ + "Hours"](),
			M = date[_ + "Minutes"](),
			s = date[_ + "Seconds"](),
			L = date[_ + "Milliseconds"](),
			o = utc ? 0 : date.getTimezoneOffset(),
			flags = {
				d:    d,
				dd:   pad(d),
				ddd:  dF.i18n.dayNames[D],
				dddd: dF.i18n.dayNames[D + 7],
				m:    m + 1,
				mm:   pad(m + 1),
				mmm:  dF.i18n.monthNames[m],
				mmmm: dF.i18n.monthNames[m + 12],
				yy:   String(y).slice(2),
				yyyy: y,
				h:    H % 12 || 12,
				hh:   pad(H % 12 || 12),
				H:    H,
				HH:   pad(H),
				M:    M,
				MM:   pad(M),
				s:    s,
				ss:   pad(s),
				l:    pad(L, 3),
				L:    pad(L > 99 ? Math.round(L / 10) : L),
				t:    H < 12 ? "a"  : "p",
				tt:   H < 12 ? "am" : "pm",
				T:    H < 12 ? "A"  : "P",
				TT:   H < 12 ? "AM" : "PM",
				Z:    utc ? "UTC" : (String(date).match(timezone) || [""]).pop().replace(timezoneClip, ""),
				o:    (o > 0 ? "-" : "+") + pad(Math.floor(Math.abs(o) / 60) * 100 + Math.abs(o) % 60, 4),
				S:    ["th", "st", "nd", "rd"][d % 10 > 3 ? 0 : (d % 100 - d % 10 != 10) * d % 10]
			};

		return mask.replace(token, function ($0) {
			return $0 in flags ? flags[$0] : $0.slice(1, $0.length - 1);
		});
	};
}();

// Some common format strings
dateFormat.masks = {
	"default":      "ddd mmm dd yyyy HH:MM:ss",
	shortDate:      "m/d/yy",
	mediumDate:     "mmm d, yyyy",
	longDate:       "mmmm d, yyyy",
	fullDate:       "dddd, mmmm d, yyyy",
	shortTime:      "h:MM TT",
	mediumTime:     "h:MM:ss TT",
	longTime:       "h:MM:ss TT Z",
	isoDate:        "yyyy-mm-dd",
	isoTime:        "HH:MM:ss",
	isoDateTime:    "yyyy-mm-dd'T'HH:MM:ss",
	isoUtcDateTime: "UTC:yyyy-mm-dd'T'HH:MM:ss'Z'"
};

// Internationalization strings
dateFormat.i18n = {
	dayNames: [
		"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat",
		"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"
	],
	monthNames: [
		"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
		"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"
	]
};

// For convenience...
Date.prototype.format = function (mask, utc) {
	return dateFormat(this, mask, utc);
};






// JSONscriptRequest -- a simple class for accessing Yahoo! Web Services
// using dynamically generated script tags and JSON
//
// Author: Jason Levitt
// Date: December 7th, 2005
//
// A SECURITY WARNING FROM DOUGLAS CROCKFORD:
// "The dynamic <script> tag hack suffers from a problem. It allows a page 
// to access data from any server in the web, which is really useful. 
// Unfortunately, the data is returned in the form of a script. That script 
// can deliver the data, but it runs with the same authority as scripts on 
// the base page, so it is able to steal cookies or misuse the authorization 
// of the user with the server. A rogue script can do destructive things to 
// the relationship between the user and the base server."
//
// So, be extremely cautious in your use of this script.
//

// Constructor -- pass a REST request URL to the constructor
//
function JSONscriptRequest(fullUrl) {
    // REST request path
    this.fullUrl = fullUrl; 
    // Keep IE from caching requests
    this.noCacheIE = '&noCacheIE=' + (new Date()).getTime();
    // Get the DOM location to put the script tag
    this.headLoc = document.getElementsByTagName("head").item(0);
    // Generate a unique script tag id
    this.scriptId = 'YJscriptId' + JSONscriptRequest.scriptCounter++;
}

// Static script ID counter
JSONscriptRequest.scriptCounter = 1;

// buildScriptTag method
//
JSONscriptRequest.prototype.buildScriptTag = function () {

    // Create the script tag
    this.scriptObj = document.createElement("script");
    
    // Add script object attributes
    this.scriptObj.setAttribute("type", "text/javascript");
    this.scriptObj.setAttribute("src", this.fullUrl + this.noCacheIE);
    this.scriptObj.setAttribute("id", this.scriptId);
}
 
// removeScriptTag method
// 
JSONscriptRequest.prototype.removeScriptTag = function () {
    // Destroy the script tag
    this.headLoc.removeChild(this.scriptObj);  
}

// addScriptTag method
//
JSONscriptRequest.prototype.addScriptTag = function () {
    // Create the script tag
    this.headLoc.appendChild(this.scriptObj);
}


