var SCFitness = function() {	var NO_PRODUCTS_IN_LIST = 'There are no items in your list.';	var SAVE_PID_TIME = 7; 	// days		var SPANISH_URL = 'espanol.searscommercialfitness.com';  var ENGLISH_LANG = { 'search' : 'Search for products in this brand'                     }  var SPANISH_LANG = { 'search' : 'Búsqueda de productos de esta marca'                     }  	var SEARCH_DEFAULT_TEXT = (window.location.host == SPANISH_URL) ? SPANISH_LANG['search'] : ENGLISH_LANG['search'];	var VALID_EMAIL = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;	var CONTACT_URL = BASE_URL + 'index.php/contact';	var REP_FINDER_URL = 'http://finder.scmarketingtools.com/branches_040710.php?zip=%zipcode%&find=am'; // http://finder.staging.arsecom.com/web_force/branches.php?zip=%zipcode%&find=am	var REP_RESULTS;	var DEFAULT_REP_EMAIL = 'jfleming@thinkars.com';	var email_data = {};	//	ref: http://www.quirksmode.org/js/cookies.html	var Cookie = function() {		function get(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;		};		function set(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=/";		};		function del(name) {			set(name, '', -1);		};		return {			get: get,			set: set,			del: del		}	}();	var Lightbox = function() {		var $overlay;		var $lb, $lbcontent;		var startX, startY, lbH, lbW;		function init(html, sX, sY, callback) {			// default parameters			startX = (typeof sX === 'undefined') ? 0 : sX;			startY = (typeof sY === 'undefined') ? 0 : sY;			$overlay = $("#overlay");			// create the overlay to gray out background if not done so already.			$("#lightbox").remove();			if ($overlay.length == 0) {				// create overlay				$('body').prepend('<div id="overlay"></div>');				$overlay = $("#overlay");			}			var body_height = $("body").height();			var body_width = $("body").width();			$overlay.css({				opacity: 0.75,				height: body_height			}).hide().fadeIn(200, function() {				//				// add lightbox to html				//				$('body').prepend(lb_html(html));				$lb = $("#lightbox");				$lbcontent = $("#lbcontent");				newTop = finalPosY();				newLeft = finalPosX();				lbH = $lb.height();				lbW = $lb.width();				$lb.css({				/* init css styles */					width: 0,					height: 0,					opacity: .1,					top: startY,					left: startX,					padding: '0',					display: 'block'				}).hide().animate({ 	/* animate to these css styles */					height: lbH,					width: lbW,					opacity: 1,					padding: '20px',					top: newTop,					left: newLeft				}, {					duration: 500,					easing: 'easeInOutQuad',					complete: function() {										/* fade in lightbox content once lightbox is done animating */						$lbcontent.css({							visibility: 'visible'						}).hide().fadeIn(300);					}				});				//				// reset X & Y position on lightbox to emulate position: fixed				//				$(window).bind('scroll', function() {					newTop = finalPosY();					newLeft = finalPosX();					$lb.css({						top: newTop,						left: newLeft					});				});				// only execute callback if one was passed.				if (typeof callback !== 'undefined')					callback();			}); // end fadeIn();		};		function lb_html(html) {			var new_html = '' +			'<div id="lightbox">' +			'	<div id="lbcontent">' +			html			'	</div>' +			'</div>';			return new_html;		}		function scrollTop() {			// ref: http://www.subodhpatel.co.cc/index.php?option=com_content&view=article&id=57:fix-for-windowscrolly&catid=39:javascript			var iebody = (document.compatMode && document.compatMode != "BackCompat") ? document.documentElement : document.body;			var dsoctop = document.all ? iebody.scrollTop : pageYOffset;			return dsoctop;		};		function finalPosY() {			var lbH = $lb.height();			newTop = ($(window).height() - lbH) / 2;			newTop += scrollTop() - 40;			return newTop;		};		function finalPosX() {			var lbW = $lb.width();			newLeft = ($(window).width() - lbW) /2;			newLeft -= 20;			return newLeft;		}		function destroy() {			$lbcontent.stop().fadeOut(300, function() {				$(this).css('visibility', 'hidden').hide();				$lb.stop().animate({					height: 0,					width: 0,					opacity: 0,					padding: '0',					top: startY,					left: startX				}, {					duration: 500,					easing: 'easeInOutQuad',					complete: function() {						$lb.remove();						$overlay.fadeOut(200);						$(window).unbind('scroll');					}				});			});		};		return {			init: init,			destroy: destroy,			lb_html: lb_html		}	}();	function save_pid(pid, pname) {		//Cookie.del('pids');		var saved_pids = Cookie.get('pids');		// if cookie is not set, do not perform any checks.		// simply create cookie because it's the first product added.		if (saved_pids == null || saved_pids === '') {			var new_p = pid + ',' + pname + '|';			Cookie.set('pids', new_p, SAVE_PID_TIME);		} else {			// check if PID is already in list. if not, add it.			pid_list = saved_pids.split('|');			// loop thru entire list			for (i in pid_list) {				// if last list item, break out because it's blank (trailing pipe)				if (i == pid_list.length-1)					break;				var line_item = pid_list[i].split(',');				var i_pid = line_item[0];				var i_pname = line_item[1];				// if we found the pid, do not add it to the list again.				if (i_pid == pid)					return false;			}			// safely set cookie after pid does not already exist.			var new_p = pid + ',' + pname + '|';			Cookie.set('pids', saved_pids + new_p, SAVE_PID_TIME);		}	};	function remove_pid(pid) {		// loop thru list of pids, if it exists remove it:		var saved_pids = Cookie.get('pids');		pid_list = saved_pids.split('|');		// loop thru entire list		for (i in pid_list) {			// if last list item, break out because it's blank (trailing pipe)			if (i == pid_list.length-1)				break;			var line_item = pid_list[i].split(',');			var i_pid = line_item[0];			var i_pname = line_item[1];			// if we found the pid, remove it & stop searching			if (i_pid == pid) {				var new_pid_list = '';				for (var x = 0; x < pid_list.length-1; x++) {					// add to new list as long as indices don't match.					if (x != i)						new_pid_list += pid_list[x] + '|';				}				if (new_pid_list == '')					Cookie.del('pids');				else					Cookie.set('pids', new_pid_list, SAVE_PID_TIME);				//alert(Cookie.get('pids'));				return false;			}		} // end for		// safely set cookie after pid does not already exist.		var new_p = pid + ',' + pname + '|';		Cookie.set('pids', saved_pids + new_p, SAVE_PID_TIME);	};	function init() {		if ($("body#brand-landing").length > 0) {			listing_init();			refresh_product_list();			//$("#send-rep").hide();			// if there is no text in the search box on load, set it to default text.			if ($("input#search").val() == '')				$("input#search").val(SEARCH_DEFAULT_TEXT + '   ')			// clear text form search box if it contains default value & add active state.			$("input#search")				.focus(function() {					if ($(this).val() == SEARCH_DEFAULT_TEXT + '   ')						$(this).val('');					else {						// highlight the text b/c the user probably wants to clear it out.						this.select();					}					$(this).addClass('active');				})				.blur(function() {					$(this).removeClass('active');					if ($(this).val() == '')						$(this).val(SEARCH_DEFAULT_TEXT + '   ');				});			// my list stuff			$("a#show-items").click(function() {				//alert(Cookie.get('pids'));				refresh_product_list();				return false;			});			$("a#clear-items").click(function() {				Cookie.del('pids');				refresh_product_list();				$("input.add-to-list").removeAttr('checked');				return false;			});			$("#header .my-list a").click(function() {				$(window).scrollTo($($(this).attr('href')), 300);				return false;			});			var cancelFn = function() {				var $sr = $("#send-rep");				var $mlw = $("#ml-wrapper");				var h = $sr.height();				$mlw.css('height', h+100);				$("#product-list-wrapper").slideDown(500);				$("#send-rep").slideUp(500, function() {					$mlw.css( {height: 'auto'} );				}).attr('down', false);				$("#send-rep-status").hide();				$("#send-rep-status").hide();				return false;			};			var findRepFn = function() {			    var $zip = $('input#zipcode');			    if ($zip.val() == '' || $zip.val().length < 5) {					$zip.siblings('span.error').html('Invalid');					return false;				} else					$zip.siblings('span.error').html('');                var svc_URL = REP_FINDER_URL.replace('%zipcode%', $zip.val());				var r = new JSONscriptRequest(svc_URL);				r.buildScriptTag();				r.addScriptTag();				$('#finding-reps').show();				return false;			};			$("#send-rep").hide();			$("#find-rep").click(findRepFn);			$("a#cancel").click(cancelFn);			$("h2#my-list-header").click(function() {				if ($("#send-rep").attr('down') == 'true') {					cancelFn();				} else {					findRepFn();				}			});			$("#send").click(function() {				// perform client-side form validation				var errs = 0;				var $fn = $("#first-name");				var $ln = $("#last-name");				var $e = $("#email");				if ($fn.val() == '') {					$fn.siblings('span.error').html('Required');					errs++;				} else {					$fn.siblings('span.error').html('');				}				if ($ln.val() == '') {					$ln.siblings('span.error').html('Required');					errs++;				} else {					$ln.siblings('span.error').html('');				}				if (!VALID_EMAIL.test($e.val())) {					$e.siblings('span.error').html('Invalid');					errs++;				} else {					$e.siblings('span.error').html('');				}				if (Cookie.get('pids') == null) {					$('p.proderror').show();					errs++;				}				if (errs > 0) {				} else {					var $sr = $("#send-rep");					var $mlw = $("#ml-wrapper");					var h = $sr.height();					$mlw.css('height', h+100);					/*$sr.slideUp(500, function() {					});*/					$("#send-rep-status").html("<img src='" + BASE_URL + "images/ajaxwait.gif' /><br />Sending").slideDown(500);					// do ajax email here.                    var zip = $('input#zipcode').val();					SCFitness.email_data = {						firstname: $fn.val(),						lastname: $ln.val(),						email: $e.val(),						zipcode: zip,						rep: $('input[name=rep]:checked').val(),						phonenumber: $("#phone-number").val(),						additionalinfo: $("#additional-info").val()					};					var rep = SCFitness.REP_RESULTS[1][$('input[name="reps"]:checked').val()];            		var foundrep_error = typeof SCFitness.REP_RESULTS[0][0].error != 'undefined';            		// if there was an error with the zipcode, use default rep email            		if (foundrep_error)            			var send_email = SCFitness.DEFAULT_REP_EMAIL;            		else            			var send_email = rep.email					var pids = SCFitness.Cookie.get('pids');            		var pids_text = '';            		if (pids == null)            			pids_text = 'No products selected.';            		else {            			pids = pids.split('|');            			for (i in pids) {            				var a = pids[i].split(',');            				if (typeof a[0] == 'undefined' || typeof a[1] == 'undefined')            					continue;            				pids_text += a[0] + ' -- ' + a[1] + "<br />";            			}            		}            		$.post(SCFitness.CONTACT_URL, {            			firstname: SCFitness.email_data.firstname,            			lastname: SCFitness.email_data.lastname,            			email: SCFitness.email_data.email,            			zipcode: SCFitness.email_data.zipcode,            			phonenumber: SCFitness.email_data.phonenumber,            			rep: SCFitness.email_data.rep,            			additionalinfo: SCFitness.email_data.additionalinfo,            			assignrep: rep.name,            			repemail: send_email,            			repphone: rep.phone,            			prodlist: pids_text            		}, function(data) {            			$("#send-rep-status").html("Your list and message has been sent to the nearest representative.");            			setTimeout("SCFitness.reset_mylist();", 5000);            		}, 'json');				}				return false;			});		}	};	function reset_mylist() {		//clear_product_list();		//$("#product-list-wrapper").slideDown(500);		// $("#send-rep").slideUp(500).attr('down', false);		//$("#send-rep-status").slideUp(500, function() {		//	$("#ml-wrapper").css('height', 'auto');		//});	};	//	//	listing_init() - to be called after products are loaded on brand-landing page.	//	function listing_init() {		// loop thru all items and make sure they are selected.		$("input.add-to-list").removeAttr('checked');		var saved_pids = Cookie.get('pids');		// check and see if there are PIDs first...		if (saved_pids !== null)			pid_list = saved_pids.split('|');		else			pid_list = Array();		// loop thru entire list		for (i in pid_list) {			// if last list item, break out because it's blank (trailing pipe)			if (i == pid_list.length-1)				break;			var line_item = pid_list[i].split(',');			var i_pid = line_item[0];			var i_pname = line_item[1];			$("input.add-to-list[value='" + i_pid + "']").attr('checked', 'true');		} // end for		$("input.add-to-list").click(function() {			var pid = $(this).val();//pid_from_input_id($(this).attr('id'));			if ($(this).attr('checked')) {				// checked				var pname = $(this).attr('rel');				save_pid(pid, pname);			} else {				// un-checked				remove_pid(pid);			}			// refresh product listing under "My List"			//alert(Cookie.get('pids'));			refresh_product_list();		});		$("a.product-lightbox").click(function(e) {			var $this = $(this);			var pid = $(this).attr('rel');			var pname = $(this).children('strong').html();			var $chk = $("input#prod" + pid);			$this.css('cursor', 'wait');			//var rand = Math.floor(Math.random()*999999)			var url = BASE_URL + "index.php/products/pid/" + $this.attr('rel');			//alert(url);			$.ajax({				type: 'GET',				url: url,				dataType: 'html',				error: function(XMLHttpRequest, textStatus, errorThrown) {					alert('Could not complete your request: ' + textStatus + ' - ' + this.url);					$this.css('cursor', 'default');					return;				},				success: function(html, textStatus) {					Lightbox.init(html, e.pageX, e.pageY, function() {						// restore wait cursor						$this.css('cursor', 'default');						// activate event handlers in Lightbox HTML:						$("#lbclose").click(function() {							Lightbox.destroy();							return false;						});						$("#add-to-my-list a").click(function() {							save_pid(pid, pname);							$chk.attr('checked', 'true');							refresh_product_list();							Lightbox.destroy();							return false;						});												if (window.location.host == SPANISH_URL) { // Puerto-Rican site url              var text = $('#lightbox .description').html();              text = text.replace(/ (?:[\w]*) *= *"(?:(?:(?:(?:(?:\\\W)*\\\W)*[^"]*)\\\W)*[^"]*")/gi, '');                google.language.translate(text, 'en', 'es', function(result) {                  if (result.translation)                      $('#lightbox .description').html(result.translation);              });            }					});				}			});			return false;		});	}	// refresh "My List" items	function refresh_product_list() {		var html = '';		var saved_pids = Cookie.get('pids');		if (saved_pids == null || saved_pids == '') {			// no pids, show message			html = NO_PRODUCTS_IN_LIST;			$('#clear-items').hide(); //added by Brian Ray to hide the clear all link if there are no PIDs in My List		} else {			// there are pids, generate list			pid_list = saved_pids.split('|');			// loop thru entire list			html += "<ul>\n";			for (i in pid_list) {				// if last list item, break out because it's blank (trailing pipe)				if (i == pid_list.length-1)					break;				var line_item = pid_list[i].split(',');				var i_pid = line_item[0];				var i_pname = line_item[1];				html += "\t<li><a href=\"#\" rel=\"" + i_pid + "\" class=\"my-list-del\"><span>Remove Item</span></a> " + i_pname + " </li>\n";			} // end for			html += "</ul>\n";			$('#clear-items').show(); //added by Brian Ray to show the clear all link if there are PIDs in My List		} // end if		var len;		if (saved_pids == null || pid_list == '')			len = 0;		else			len = pid_list.length-1;		switch (len) {			case 0:				$("#my-list-header span").html('');			break;			case 1:				$("#my-list-header span").html('(1 item)');			break;			default:				$("#my-list-header span").html('(' + (pid_list.length-1) + ' items)');			break;		}		$("div#product-list").html(html);		// add event handlers		$("a.my-list-del").unbind('click').click(function() {			var pid = $(this).attr('rel');			remove_pid(pid);			refresh_product_list();			listing_init();			return false;		}).hover(function() {			$(this).parent().addClass('active');		}, function() {			$(this).parent().removeClass('active');		});	};	function clear_product_list() {		Cookie.del('pids');		listing_init();		refresh_product_list();	};	// strip 'prod' from beginning of string	function pid_from_input_id(id) {		return id.substr(4, id.length);	};	return {		init: init,		Cookie: Cookie,		/* save / remove products */		save_pid: save_pid,		remove_pid: remove_pid,		refresh_product_list: refresh_product_list,		clear_product_list: clear_product_list,		reset_mylist: reset_mylist,		email_data: email_data,		CONTACT_URL: CONTACT_URL,		DEFAULT_REP_EMAIL: DEFAULT_REP_EMAIL	};}();$(function() {	SCFitness.init();});function mapResults(data) {    var $sr = $("#send-rep");	$('#finding-reps').hide();	$("#product-list-wrapper").slideUp(500);	$("#send-rep-status").hide();		$sr.slideDown(500, function() {		$(window).scrollTo($('#my-list-anchor'), {			duration: 600,			onAfter: function() {				$("#first-name").focus();			}		});	}).attr('down', 'true');    SCFitness.REP_RESULTS = data;    $('#representatives').html('');    $.each(data[1], function(i, rep) {        $('#representatives').append('<input type="radio" name="reps" id="rep' + i + '" value="' + i + '"' + (i == 0 ? 'checked="checked"' : '') + ' style="width: auto; float: left; margin: 0 5px 0 0;" />'                                   + '<label for="rep' + i + '">' + ellipsis(rep.name, 20) + '</label>'                                   + '<p>'                                   + (rep.type == 'SF' ? 'Builders Specialist ' : 'Property Management Specialist')                                    + '<br />'                                   + rep.phone                                   + '<br />'                                   + '<a href="mailto:' + rep.email + '">'                                   + rep.email                                   + '</a>'                                   + '</p>');    });}// 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);}//SCFitness.save_pid('1234fdsfsff565345', 'testing 1 2 3 4')function ellipsis(string, length) {    return string.length > length ? (string.substr(0, length - 3) + '...') : string;}
