var preLoad, preLoad2;
preLoad = new Image()
preLoad.src = '/images/snb/header_navbox_sprite.png';
preLoad2 = new Image()
preLoad2.src = '/images/snb/header_navbox_sprite_new.png';


/*Modal Triggers*/
$().ready(function() {
	wireupTopNav();
	//$(document).pngFix();
	$('#TAF,#information,#IOS,#video,#popVideo').jqm();
	$('#TAF').jqmAddTrigger('#TAFlink');
	$('#IOS').jqmAddTrigger('#IOSlink');
	document.createElement('header');
	document.createElement('nav');
	document.createElement('article');
	document.createElement('footer');
	document.createElement('section');
	document.createElement('aside');
});

function wireupTopNav() {
	$('#tabMen, #men-nested-tab, #men-nested-middle, #men-nested-bottom').hover(function(){
		$('#men-nested').show();
	});
	$('#tabMen, #men-nested').mouseleave(function(){
		$('#men-nested').hide();
	});
	$('#tabWomen, #women-nested-tab, #women-nested-middle, #women-nested-bottom').hover(function(){
		$('#women-nested').show();
	});
	$('#tabWomen, #women-nested').mouseleave(function(){
		$('#women-nested').hide();
	});
	$('#tabClearance, #clearance-nested-tab, #clearance-nested-middle, #clearance-nested-bottom').hover(function(){
		$('#clearance-nested').show();
	});
	$('#tabClearance, #clearance-nested').mouseleave(function(){
		$('#clearance-nested').hide();
	});
	$('#tabCustomize, #customize-nested-tab, #customize-nested-middle, #customize-nested-bottom').hover(function(){
		$('#customize-nested').show();
	});
	$('#tabCustomize, #customize-nested').mouseleave(function(){
		$('#customize-nested').hide();
	});
	$('#tabBoys, #boys-nested-tab, #boys-nested-middle, #boys-nested-bottom').hover(function(){
		$('#boys-nested').show();
	});
	$('#tabBoys, #boys-nested').mouseleave(function(){
		$('#boys-nested').hide();
	});
	$('#tabGirls, #girls-nested-tab, #girls-nested-middle, #girls-nested-bottom').hover(function(){
		$('#girls-nested').show();
	});
	$('#tabGirls, #girls-nested').mouseleave(function(){
		$('#girls-nested').hide();
	});
	$('.close-tab').hover(function(){
		$('#men-nested, #women-nested, #clearance-nested, #boys-nested, #girls-nested, #customize-nested').hide();
	});
}

//Function for Homepage Dropdowns
var currentlyOpenObject = '';
var bJustOpened = false;
function bodyPageClick()
{
	if(bJustOpened == true)
	{
		bJustOpened = false;
		return;
	}

	if(currentlyOpenObject == '')
		return;

	document.getElementById(currentlyOpenObject).style.display = 'none';
	currentlyOpenObject = '';
}

function dropdown(inThisDrop){
	// call body page click first to close any already open drop downs
	bodyPageClick();

	currentlyOpenObject = inThisDrop;
	bJustOpened = true;
	document.getElementById(inThisDrop).style.display = 'block';
}

function updateDropDown(inThisDrop,inThisText){
	document.getElementById(inThisDrop).style.display = 'none';
	document.getElementById(inThisDrop+'Input').value = inThisText;
	document.getElementById(inThisDrop+'lbl').innerHTML = inThisText;
}


function urlEncodeString(inURL)
{
	var url = inURL;
	url = url.replace(/\//g,'%2F');
	url = url.replace(/=/g,'%3D');
	url = url.replace(/_/g, '%5F');
	url = url.replace(/\,/g, '%2C');
	url = url.replace(/&/g, '%26');
	url = url.replace(/\?/g, '%3F');
	url = url.replace(/\'/g, '%27');
	url = url.replace(/\"/g, '%22');
	url = url.replace(/!/g, '%21');
	return url;
}

function validateTAF(inStyle){
	var from_name, from_email, to_name, to_email, message, subject, bcc_name, bcc_email, stayintouch, thisDetailUrl;
	var TAF_form = document.form_TAF;
	//reset all the error messages
	//document.getElementById('TAF_valid_rname').style.display = 'none';
	//document.getElementById('TAF_valid_remail1').style.display = 'none';
	//document.getElementById('TAF_valid_semail1').style.display = 'none';
	//document.getElementById('TAF_valid_sname').style.display = 'none';
	//document.getElementById('TAF_valid_contact').style.display = 'none';
	//get form values
	from_name = TAF_form.from_name.value;
	from_name = from_name.replace(/ /g,'%20').replace(/&/g, '%26');
	from_email = TAF_form.from_email.value;
	to_name = TAF_form.to_name.value;
	thisDetailUrl = TAF_form.thisDetailUrl.value;
	to_name = to_name.replace(/ /g,'%20').replace(/&/g, '%26');
	to_email = TAF_form.to_email.value;
	subject = 'A message from '+to_name+' about products at shopnewbalance.com.';
	subject = subject.replace(/ /g,'%20').replace(/&/g, '%26');
	message = '<html><head><!DOCTYPE html PUBLIC"-//W3C//DTDXHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><title>Shop New Balance Tell A Friend</title><meta http-equiv="Content-Type" content="text/html;charset=utf-8"/></head><body bgColor=#ffffff style="margin:0px; padding:0px">'+TAF_form.body_msg.value+'<br><br>Style Number: '+inStyle+'<br><br>To view this item, click the following link: <br>' + thisDetailUrl + '<br>- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -<br><br>Shop New Balance is the premier online source for New Balance shoes and apparel. Here\'s what you\'ll find:<br>- INVENTORY AVAILABLE FOR ALL SIZES (5-20) AND ALL WIDTHS (4A-6E)<br>- CONVENIENT ONLINE SHOPPING FROM THE COMFORT OF YOUR HOME<br>- FAST DELIVERY RIGHT TO YOUR DOORSTEP<br>- TOTAL FIT GUARANTEE WITH FREE RETURN SHIPPING AND HASSLE-FREE REFUNDS<br><br><br>Visit us today!<br><br>Shop New Balance http://www.shopnewbalance.com</body></html>';
	message = message.replace(/ /g,'%20').replace(/&/g, '%26').replace(/"/g, '%22').replace(/</, '%3C').replace(/>/g, '%3E').replace(/:/g, '%3A');
	bcc_name = '';
	bcc_email = '';
	stayintouch = '';
	for (var i=0; i < TAF_form.radStayInTouch.length; i++){
	   if (TAF_form.radStayInTouch[i].checked)
	   {
	      stayintouch = TAF_form.radStayInTouch[i].value;
	   }
	}
	if (stayintouch == '') {
		stayintouch = false;
	}
	//filter for quick email validation
	var emailFilter = /^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/; 
	//tests each field, works it's way down the form, success uses the ajax send email
	if ((from_name.length)>0) { 
		if (emailFilter.test(from_email)) { 
			if ((to_name.length)>0) { 
				if (emailFilter.test(to_email)) {
					$.post('/includes/ajax_send_email.asp','from_name='+from_name+'&from_email='+from_email+'&to_name='+to_name+'&to_email='+to_email+'&subject='+subject+'&message='+message+'&bcc_name='+bcc_name+'&bcc_email='+bcc_email+ '&style=' + inStyle + '&stayintouch=' + stayintouch,TAF_success());
				} else {
					document.getElementById('TAF_error').style.display = 'block';
					document.getElementById('TAF_error').innerHTML = 'Invalid e-mail address of sender.'
				}
			} else {
				document.getElementById('TAF_error').style.display = 'block';
				document.getElementById('TAF_error').innerHTML = 'Missing name of sender.'
			}
		} else { 
			document.getElementById('TAF_error').style.display = 'block';
			document.getElementById('TAF_error').innerHTML = 'Invalid e-mail address of recipeint';
		} 
	} else {
		document.getElementById('TAF_error').style.display = 'block';
		document.getElementById('TAF_error').innerHTML = 'Missing name of recipient.'
	}
	return false 
}

function TAF_success(){
	//closes the TAF modal and opens the modal that confirms the email being sent	
	$('#information').jqmHide();
	info_pop('taf_response');
}

function validateIOS () {
	var from_name, from_email, subject, message;
	var IOS_form = document.ImproveOurSite;
	//reset all the error messages
	document.getElementById('IOS_valid_name').style.display = 'none';
	document.getElementById('IOS_valid_email').style.display = 'none';
	document.getElementById('IOS_valid_subject').style.display = 'none';
	document.getElementById('IOS_valid_message').style.display = 'none';
	//get form values
	from_name = IOS_form.from_name.value;
	from_name = from_name.replace(/ /g,'%20').replace(/&/g, '%26');
	from_email = IOS_form.from_email.value;
	subject = IOS_form.subjectline.value;
	subject = subject.replace(/ /g,'%20').replace(/&/g, '%26');
	message = IOS_form.body_msg.value;
	message = message.replace(/ /g,'%20').replace(/&/g, '%26').replace(/"/g, '%22').replace(/</, '%3C').replace(/>/g, '%3E').replace(/:/g, '%3A');
	//filter for quick email validation
	var emailFilter = /^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/; 
	
	if ((from_name.length)>0) { 
		if (emailFilter.test(from_email)) { 
			if ((subject.length)>0) { 
				if ((message.length)>0) {
				$.post('/information/ios_send_email.asp','from_name='+from_name+'&from_email='+from_email+'&subjectline='+subject+'&body_msg='+message,IOS_success());
				} else {
					document.getElementById('IOS_valid_message').style.display = 'block';
				}
			} else {
				document.getElementById('IOS_valid_subject').style.display = 'block';
			}
		} else {
			document.getElementById('IOS_valid_email').style.display = 'block';
		}
	} else { 
		document.getElementById('IOS_valid_name').style.display = 'block';
	} 
	return false
}

function IOS_success() {
		$('#information').jqmHide();
		info_pop('improve_our_site_response');
}

function info_pop(thisLink){
	var theHTML;
	if(thisLink == 'tellafriend')
	{
		var thisStyle,thisBrand;
		thisStyle = document.getElementById('thisStyle_detail').value;
		thisBrand = document.getElementById('thisBrand_detail').value;
		
		var prodImage = $("#altViewsWrapper ul li:first img").attr("src");
		var tmpFrmAction;
		if(document.frmAddToCart)
		{
			if(document.frmAddToCart.imageURL)
				prodImage = document.frmAddToCart.imageURL.value + '&wid=125&hei=125';
			
			tmpFrmAction = document.frmAddToCart.action;
		}
		
		$.post('/information/default.asp',"thisLink="+thisLink+"&style="+thisStyle+"&brand="+thisBrand,function(data) {
		document.getElementById('modal_wrapper').innerHTML = data.replace(/IMAGEURL/g, prodImage).replace(/DETAILURL/g, tmpFrmAction);
		$('#information').jqmShow();
		});
	} else if(thisLink == 'tellafriendnoimage')
	{
		var thisStyle,thisBrand;
		thisStyle = document.getElementById('thisStyle_detail').value;
		thisBrand = document.getElementById('thisBrand_detail').value;
		
		var tmpFrmAction;
		if(document.frmAddToCart)
		{
			tmpFrmAction = document.frmAddToCart.action;
		}
		
		$.post('/information/default.asp',"thisLink="+thisLink+"&style="+thisStyle+"&brand="+thisBrand,function(data) {
		document.getElementById('modal_wrapper').innerHTML = data.replace(/DETAILURL/g, tmpFrmAction);
		$('#information').jqmShow();
		});
	} else {
		$.post('/information/default.asp',"thisLink="+thisLink,function(data) {
		document.getElementById('modal_wrapper').innerHTML = data;
		$('#information').jqmShow();

		if(thisLink == 'security_policy')
		{
			$('#sslVerisignTd').html('<img border="true" alt="Click to Verify - This site has chosen a VeriSign SSL Certificate to improve Web site security" oncontextmenu="return false;" src="https://seal.verisign.com/getseal?at=0&amp;sealid=1&amp;dn=www.shopnewbalance.com&amp;lang=en" name="seal">');
			$('#sslVerisignTd').css('cursor', 'pointer');
		}

		});
	}
}

function info_Hide(){
	$('#information').jqmHide();
}

function video_fs_pop_Show(video_content){
	var theHTML;
	jQuery.post('/includes/misc_tasks/pop_video_ajax_fs.asp',"video_content="+video_content,function(data) {
		document.getElementById('the_video_skin').innerHTML = data;
		jQuery('#popVideo').jqmShow();
		jQuery('#popVideo').css({'left':'50%'});
	});
}

function LimitMsg( inLen, inVar, inCounter )
{
	var ct, ct2;
	ct = document.getElementById(inVar);
	counter = document.getElementById(inCounter);
	if((ct) && (counter))
	{
		if(ct.value.length >= inLen)
			ct.value = ct.value.substring(0, inLen);
		
		counter.innerHTML = ct.value.length;
	}
}


/************ JQUERY EXTENSIONS *************/

(function($) {                                          // Compliant with jquery.noConflict()
$.fn.jCarouselLite = function(o) {
    o = $.extend({
        btnPrev: null,
        btnNext: null,
        btnGo: null,
        mouseWheel: false,
        auto: null,

        speed: 200,
        easing: null,

        vertical: false,
        circular: true,
        visible: 3,
        start: 0,
        scroll: 1,

        beforeStart: null,
        afterEnd: null
    }, o || {});

    return this.each(function() {                           // Returns the element collection. Chainable.

        var running = false, animCss=o.vertical?"top":"left", sizeCss=o.vertical?"height":"width";
        var div = $(this), ul = $("ul", div), tLi = $("li", ul), tl = tLi.size(), v = o.visible;

        if(o.circular) {
            ul.prepend(tLi.slice(tl-v-1+1).clone())
              .append(tLi.slice(0,v).clone());
            o.start += v;
        }

        var li = $("li", ul), itemLength = li.size(), curr = o.start;
        div.css("visibility", "visible");

        li.css({overflow: "hidden", float: o.vertical ? "none" : "left"});
        ul.css({margin: "0", padding: "0", position: "relative", "list-style-type": "none", "z-index": "1"});
        div.css({overflow: "hidden", position: "relative", "z-index": "2", left: "0px"});

        var liSize = o.vertical ? height(li) : width(li);   // Full li size(incl margin)-Used for animation
        var ulSize = liSize * itemLength;                   // size of full ul(total length, not just for the visible items)
        var divSize = liSize * v;                           // size of entire div(total length for just the visible items)

        li.css({width: li.width(), height: li.height()+30});
        ul.css(sizeCss, ulSize+"px").css(animCss, -(curr*liSize));

        div.css(sizeCss, divSize+"px");                     // Width of the DIV. length of visible images

        if(o.btnPrev)
            $(o.btnPrev).click(function() {
                return go(curr-o.scroll);
            });

        if(o.btnNext)
            $(o.btnNext).click(function() {
                return go(curr+o.scroll);
            });

        if(o.btnGo)
            $.each(o.btnGo, function(i, val) {
                $(val).click(function() {
                    return go(o.circular ? o.visible+i : i);
                });
            });

        if(o.mouseWheel && div.mousewheel)
            div.mousewheel(function(e, d) {
                return d>0 ? go(curr-o.scroll) : go(curr+o.scroll);
            });

        if(o.auto)
            setInterval(function() {
                go(curr+o.scroll);
            }, o.auto+o.speed);

        function vis() {
            return li.slice(curr).slice(0,v);
        };

        function go(to) {
            if(!running) {

                if(o.beforeStart)
                    o.beforeStart.call(this, vis());

                if(o.circular) {            // If circular we are in first or last, then goto the other end
                    if(to<=o.start-v-1) {           // If first, then goto last
                        ul.css(animCss, -((itemLength-(v*2))*liSize)+"px");
                        // If "scroll" > 1, then the "to" might not be equal to the condition; it can be lesser depending on the number of elements.
                        curr = to==o.start-v-1 ? itemLength-(v*2)-1 : itemLength-(v*2)-o.scroll;
                    } else if(to>=itemLength-v+1) { // If last, then goto first
                        ul.css(animCss, -( (v) * liSize ) + "px" );
                        // If "scroll" > 1, then the "to" might not be equal to the condition; it can be greater depending on the number of elements.
                        curr = to==itemLength-v+1 ? v+1 : v+o.scroll;
                    } else curr = to;
                } else {                    // If non-circular and to points to first or last, we just return.
                    if(to<0 || to>itemLength-v) return;
                    else curr = to;
                }                           // If neither overrides it, the curr will still be "to" and we can proceed.

                running = true;

                ul.animate(
                    animCss == "left" ? { left: -(curr*liSize) } : { top: -(curr*liSize) } , o.speed, o.easing,
                    function() {
                        if(o.afterEnd)
                            o.afterEnd.call(this, vis());
                        running = false;
                    }
                );
                // Disable buttons when the carousel reaches the last/first, and enable when not
                if(!o.circular) {
                    $(o.btnPrev + "," + o.btnNext).removeClass("disabled");
                    $( (curr-o.scroll<0 && o.btnPrev)
                        ||
                       (curr+o.scroll > itemLength-v && o.btnNext)
                        ||
                       []
                     ).addClass("disabled");
                }

            }
            return false;
        };
    });
};



function css(el, prop) {
    return parseInt($.css(el[0], prop)) || 0;
};
function width(el) {
    return  el[0].offsetWidth + css(el, 'marginLeft') + css(el, 'marginRight');
};
function height(el) {
    return el[0].offsetHeight + css(el, 'marginTop') + css(el, 'marginBottom');
};

})(jQuery);


/*

  Author - Rudolf Naprstek
  Website - http://www.thimbleopensource.com/tutorials-snippets/jquery-plugin-filter-text-input
  Version - 1.2.0
  Release - 20th November 2010

  Thanks to Niko Halink from ARGH!media for bugfix!

*/

(function($){  
  
    $.fn.extend({   

        filter_input: function(options) {  

          var defaults = {  
              regex:".*",
              live:false
          }  
                
          var options =  $.extend(defaults, options);  
          var regex = new RegExp(options.regex);
          
          function filter_input_function(event) {

            var key = event.charCode ? event.charCode : event.keyCode ? event.keyCode : 0;

            // 8 = backspace, 9 = tab, 13 = enter, 35 = end, 36 = home, 37 = left, 39 = right, 46 = delete
            if (key == 8 || key == 9 || key == 13 || key == 35 || key == 36|| key == 37 || key == 39 || key == 46) {

              if ($.browser.mozilla) {

                // if charCode = key & keyCode = 0
                // 35 = #, 36 = $, 37 = %, 39 = ', 46 = .
         
                if (event.charCode == 0 && event.keyCode == key) {
                  return true;                                             
                }

              }
            }


            var string = String.fromCharCode(key);
            if (regex.test(string)) {
              return true;
            } 
            return false;
          }
          
          if (options.live) {
            $(this).live('keypress', filter_input_function); 
          } else {
            return this.each(function() {  
              var input = $(this);
              input.unbind('keypress').keypress(filter_input_function);
            });  
          }
          
        }  
    });  
      
})(jQuery); 

/* jQuery Easing Plugin */
jQuery.easing['jswing'] = jQuery.easing['swing'];

jQuery.extend( jQuery.easing,
{
	def: 'easeOutQuad',
	swing: function (x, t, b, c, d) {
		//alert(jQuery.easing.default);
		return jQuery.easing[jQuery.easing.def](x, t, b, c, d);
	},
	easeInQuad: function (x, t, b, c, d) {
		return c*(t/=d)*t + b;
	},
	easeOutQuad: function (x, t, b, c, d) {
		return -c *(t/=d)*(t-2) + b;
	},
	easeInOutQuad: function (x, t, b, c, d) {
		if ((t/=d/2) < 1) return c/2*t*t + b;
		return -c/2 * ((--t)*(t-2) - 1) + b;
	},
	easeInCubic: function (x, t, b, c, d) {
		return c*(t/=d)*t*t + b;
	},
	easeOutCubic: function (x, t, b, c, d) {
		return c*((t=t/d-1)*t*t + 1) + b;
	},
	easeInOutCubic: function (x, t, b, c, d) {
		if ((t/=d/2) < 1) return c/2*t*t*t + b;
		return c/2*((t-=2)*t*t + 2) + b;
	},
	easeInQuart: function (x, t, b, c, d) {
		return c*(t/=d)*t*t*t + b;
	},
	easeOutQuart: function (x, t, b, c, d) {
		return -c * ((t=t/d-1)*t*t*t - 1) + b;
	},
	easeInOutQuart: function (x, t, b, c, d) {
		if ((t/=d/2) < 1) return c/2*t*t*t*t + b;
		return -c/2 * ((t-=2)*t*t*t - 2) + b;
	},
	easeInQuint: function (x, t, b, c, d) {
		return c*(t/=d)*t*t*t*t + b;
	},
	easeOutQuint: function (x, t, b, c, d) {
		return c*((t=t/d-1)*t*t*t*t + 1) + b;
	},
	easeInOutQuint: function (x, t, b, c, d) {
		if ((t/=d/2) < 1) return c/2*t*t*t*t*t + b;
		return c/2*((t-=2)*t*t*t*t + 2) + b;
	},
	easeInSine: function (x, t, b, c, d) {
		return -c * Math.cos(t/d * (Math.PI/2)) + c + b;
	},
	easeOutSine: function (x, t, b, c, d) {
		return c * Math.sin(t/d * (Math.PI/2)) + b;
	},
	easeInOutSine: function (x, t, b, c, d) {
		return -c/2 * (Math.cos(Math.PI*t/d) - 1) + b;
	},
	easeInExpo: function (x, t, b, c, d) {
		return (t==0) ? b : c * Math.pow(2, 10 * (t/d - 1)) + b;
	},
	easeOutExpo: function (x, t, b, c, d) {
		return (t==d) ? b+c : c * (-Math.pow(2, -10 * t/d) + 1) + b;
	},
	easeInOutExpo: function (x, t, b, c, d) {
		if (t==0) return b;
		if (t==d) return b+c;
		if ((t/=d/2) < 1) return c/2 * Math.pow(2, 10 * (t - 1)) + b;
		return c/2 * (-Math.pow(2, -10 * --t) + 2) + b;
	},
	easeInCirc: function (x, t, b, c, d) {
		return -c * (Math.sqrt(1 - (t/=d)*t) - 1) + b;
	},
	easeOutCirc: function (x, t, b, c, d) {
		return c * Math.sqrt(1 - (t=t/d-1)*t) + b;
	},
	easeInOutCirc: function (x, t, b, c, d) {
		if ((t/=d/2) < 1) return -c/2 * (Math.sqrt(1 - t*t) - 1) + b;
		return c/2 * (Math.sqrt(1 - (t-=2)*t) + 1) + b;
	},
	easeInElastic: function (x, t, b, c, d) {
		var s=1.70158;var p=0;var a=c;
		if (t==0) return b;  if ((t/=d)==1) return b+c;  if (!p) p=d*.3;
		if (a < Math.abs(c)) { a=c; var s=p/4; }
		else var s = p/(2*Math.PI) * Math.asin (c/a);
		return -(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b;
	},
	easeOutElastic: function (x, t, b, c, d) {
		var s=1.70158;var p=0;var a=c;
		if (t==0) return b;  if ((t/=d)==1) return b+c;  if (!p) p=d*.3;
		if (a < Math.abs(c)) { a=c; var s=p/4; }
		else var s = p/(2*Math.PI) * Math.asin (c/a);
		return a*Math.pow(2,-10*t) * Math.sin( (t*d-s)*(2*Math.PI)/p ) + c + b;
	},
	easeInOutElastic: function (x, t, b, c, d) {
		var s=1.70158;var p=0;var a=c;
		if (t==0) return b;  if ((t/=d/2)==2) return b+c;  if (!p) p=d*(.3*1.5);
		if (a < Math.abs(c)) { a=c; var s=p/4; }
		else var s = p/(2*Math.PI) * Math.asin (c/a);
		if (t < 1) return -.5*(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b;
		return a*Math.pow(2,-10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )*.5 + c + b;
	},
	easeInBack: function (x, t, b, c, d, s) {
		if (s == undefined) s = 1.70158;
		return c*(t/=d)*t*((s+1)*t - s) + b;
	},
	easeOutBack: function (x, t, b, c, d, s) {
		if (s == undefined) s = 1.70158;
		return c*((t=t/d-1)*t*((s+1)*t + s) + 1) + b;
	},
	easeInOutBack: function (x, t, b, c, d, s) {
		if (s == undefined) s = 1.70158; 
		if ((t/=d/2) < 1) return c/2*(t*t*(((s*=(1.525))+1)*t - s)) + b;
		return c/2*((t-=2)*t*(((s*=(1.525))+1)*t + s) + 2) + b;
	},
	easeInBounce: function (x, t, b, c, d) {
		return c - jQuery.easing.easeOutBounce (x, d-t, 0, c, d) + b;
	},
	easeOutBounce: function (x, t, b, c, d) {
		if ((t/=d) < (1/2.75)) {
			return c*(7.5625*t*t) + b;
		} else if (t < (2/2.75)) {
			return c*(7.5625*(t-=(1.5/2.75))*t + .75) + b;
		} else if (t < (2.5/2.75)) {
			return c*(7.5625*(t-=(2.25/2.75))*t + .9375) + b;
		} else {
			return c*(7.5625*(t-=(2.625/2.75))*t + .984375) + b;
		}
	},
	easeInOutBounce: function (x, t, b, c, d) {
		if (t < d/2) return jQuery.easing.easeInBounce (x, t*2, 0, c, d) * .5 + b;
		return jQuery.easing.easeOutBounce (x, t*2-d, 0, c, d) * .5 + c*.5 + b;
	}
});


jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined'  ||  (name  &&  typeof name != 'string')) { // name and value given, set cookie
        if (typeof name == 'string') {
            options = options || {};
            if (value === null) {
                value = '';
                options.expires = -1;
            }
            var expires = '';
            if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
                var date;
                if (typeof options.expires == 'number') {
                    date = new Date();
                    date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
                } else {
                    date = options.expires;
                }
                expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
            }
            // CAUTION: Needed to parenthesize options.path and options.domain
            // in the following expressions, otherwise they evaluate to undefined
            // in the packed version for some reason...
            var path = options.path ? '; path=' + (options.path) : '';
            var domain = options.domain ? '; domain=' + (options.domain) : '';
            var secure = options.secure ? '; secure' : '';
            document.cookie = name + '=' + encodeURIComponent(value) + expires + path + domain + secure;
        } else { // `name` is really an object of multiple cookies to be set.
          for (var n in name) { jQuery.cookie(n, name[n], value||options); }
        }
    } else { // get cookie (or all cookies if name is not provided)
        var returnValue = {};
        if (document.cookie) {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (!name) {
                    var nameLength = cookie.indexOf('=');
                    returnValue[ cookie.substr(0, nameLength)] = decodeURIComponent(cookie.substr(nameLength+1));
                } else if (cookie.substr(0, name.length + 1) == (name + '=')) {
                    returnValue = decodeURIComponent(cookie.substr(name.length + 1));
                    break;
                }
            }
        }
        return returnValue;
    }
};

function changeCountry()
{
	var x;
	for(x = 0; x < document.frmCountry.chooseCountry.options.length; x++)
	{
		if(document.frmCountry.chooseCountry.options[x].selected == true)
		{
			if(document.frmCountry.chooseCountry.options[x].value.substring(0, 10) == ".co.uk")
			{
				window.location = 'http://www.newbalance' + document.frmCountry.chooseCountry.options[x].value.substring(0, 10);
			}
			else
			{
				window.location = 'http://www.shopnewbalance' + document.frmCountry.chooseCountry.options[x].value.substring(0, 10);
			}
			break;
		}
	}
}

function areaOnFocus(element, inputText)
{
    if (element.value == null){
       return false;
     }
                
     if(element.value == inputText){
          element.value='';
     }
}
function areaOnBlur(element, inputText)
{
	if (element.value == null){
       return false;
     }

     if(element.value==''){
          element.value = inputText;
     } 
}
function PrintBotFrame()
{
	parent['botFrame'].focus();
	parent['botFrame'].print();
}
//---------------------------------//
function createCookie(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 readCookie(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 eraseCookie(name) {
	createCookie(name,"",-1);
}

$().ready(function(){
	if(document.cookie.indexOf('productcompare2') != -1)
		{
			jsonCookie = $.getJSONCookie('productcompare2');
			
			var ajaxCompareArray = new Array();
			
			for (var i =0; i< jsonCookie.styles.length; i++)
			{
				ajaxCompareArray.push('style'+(i+1)+'='+jsonCookie.styles[i].style + ';' + jsonCookie.styles[i].cls + ';' + jsonCookie.styles[i].name + ';' + jsonCookie.styles[i].image);

				var ids = $('input[id$="'+jsonCookie.styles[i].style+'"]');
				if(ids.length>0)
				{
					$(ids[0]).attr('checked', 'true');
				}
			}
			$.get('/includes/ajax_compare.asp',ajaxCompareArray.join('&'),function(data) {
				//var current_compare = document.getElementById('compare_ul').innerHTML;
				$('#compare_ul').html(data);
				
				if(data.length > 0)
					$('#compareproducts').fadeIn(500);
			});
			
			
		}
});
//For The Compare Tool//
var jsonCookie = new Object();
function AddToCompare(inStyle,inCls,inName,inImage)
{
	//$.setJSONCookie('productcompare2', {testerArray: [{ test:'testing' }]});
	
	var ajaxCompareArray = new Array();
	
	// Create jsonObj of selected style
	var jsonCompareObj = {style: inStyle,cls:inCls,name:inName,image:inImage};
	
	var styleWasInCookie = false;
	//Read JSONCookie
	
	jsonCookie.styles = new Array();
	
	if(document.cookie.indexOf('productcompare2') != -1)
	{
		jsonCookie = $.getJSONCookie('productcompare2');
		for (var i =0; i< jsonCookie.styles.length; i++)
		{
			if(jsonCookie.styles[i].style == jsonCompareObj.style)
			{
				
				jsonCookie.styles.splice(i,1);
				
				$.setJSONCookie('productcompare2',jsonCookie);
				styleWasInCookie = true;
			}
		}
		if(jsonCookie.styles.length>=4)
		{
			alert('Please remove items from your compare basket.  Limit of 4 items to compare.');

			$('input[id$="'+jsonCompareObj.style+'"]').attr('checked', false);
			return 1;
		}
	}
	
	if(!styleWasInCookie)
		jsonCookie.styles.push(jsonCompareObj);
		
		
	// Compare jsonObj to cookie
	
	for (var i = 0; i< jsonCookie.styles.length; i++)
	{
		
		
		if (jsonCookie.styles.length > 0) {
							
			// temp string for ASP Call
			
			ajaxCompareArray.push('style'+(i+1)+'='+jsonCookie.styles[i].style + ';' + jsonCookie.styles[i].cls + ';' + jsonCookie.styles[i].name + ';' + jsonCookie.styles[i].image); 				
		
		} 
		//alert(ajaxCompareArray.join(','));
		
		
		
	}

	$.get('/includes/ajax_compare.asp',ajaxCompareArray.join('&'),function(data) {
		//var current_compare = document.getElementById('compare_ul').innerHTML;
		document.getElementById('compare_ul').innerHTML = data;
	});
	
	if (jsonCookie.styles.length == 0)
		$('#compareproducts').fadeOut(500);
	else if(jsonCookie.styles.length > 0)
		$('#compareproducts').fadeIn(500);
	$.setJSONCookie('productcompare2',jsonCookie);
	
		
		
		
		
		//$.JSONCookie(name, obj, {path: '/'}); 
	//Build style#|style+class+name+image+swatch; string 
	//Ajax POST
	//update ul
}

jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        // CAUTION: Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};


function ShowCompare()
{
	var w9;
	w9 = window.open('/includes/compare_body.asp', 'CompareWin','left=50,top=50,resizable,width=680,height=500,scrollbars=auto,menubar=no,toolbar=no');
	w9.focus();
}

function TrackFlashAd(arg1)
{
//	pageTracker._trackEvent('FlashImpression', arg1);
}

function ProductFinder(arg1)
{
	var s, x, ct;
	s = '';
	if(arg1 == 'shoes')
	{
		ct = document.frmFindProduct.shoeGender;
		for(x = 0; x < ct.length; x++)
		{
			if(ct[x].checked == true)
			{
				s += ct[x].value;
			}
		}
		s = '/' + s + '?filterSize=' +
					document.frmFindProduct.selectBoxSizeShoes.value +
					'&filterWidth=' +
					document.frmFindProduct.selectBoxWidthShoes.value;
	} else if(arg1 == 'apparel')
	{
		ct = document.frmFindProduct.apparelGender;
		for(x = 0; x < ct.length; x++)
		{
			if(ct[x].checked == true)
			{
				s += ct[x].value;
			}
		}
		s = '/' + s + '?filterSize=' +
					document.frmFindProduct.selectBoxSizeApparel.value;
	} else if(arg1 == 'type')
	{
		ct = document.frmFindProduct.typeGender;
		for(x = 0; x < ct.length; x++)
		{
			if(ct[x].checked == true)
			{
				s += ct[x].value;
			}
		}
		s = '' + s + '?filterType=' +
					document.frmFindProduct.selectBoxType.value.replace(' &amp; ', '').replace(' & ', '');
	}
	window.location = s;
}


function selectRadio(arg1)
{
	$(arg1).parent().parent().children().children("label").each(function() {
		$(this).removeClass("selected").addClass("unselected");
	});

	$(arg1).parent().children("label").removeClass("unselected").addClass("selected");
}

(function ($) {
	var isObject = function (x) {
	return (typeof x === 'object') && !(x instanceof Array) && (x !== null);
	};
	
	$.extend({
	getJSONCookie: function (cookieName) {
	var cookieData = $.cookie(cookieName);
	return cookieData ? JSON.parse(cookieData) : {};
	},
	setJSONCookie: function (cookieName, data, options) {
	var cookieData = '';
	
	options = $.extend({
	expires: 7,
	path: '/'
	}, options);
	
	if (!isObject(data)) { // data must be a true object to be serialized
	throw new Error('JSONCookie data must be an object');
	}
	
	cookieData = JSON.stringify(data);
	
	return $.cookie(cookieName, cookieData, options);
	},
	removeJSONCookie: function (cookieName) {
	return $.cookie(cookieName, null);
	},
	JSONCookie: function (cookieName, data, options) {
	if (data) {
	$.setJSONCookie(cookieName, data, options);
	}
	return $.getJSONCookie(cookieName);
	}
	});
})(jQuery); 

function TogglePromoBanners(divName, mode, timeValue)
{
	if(mode == 'hide')
	{
		$('#backOverlay').hide();
		$(divName).hide();
		if($('#modalWinWrapperEmail').length > 0 && divName == '#modalWinWrapper')
			$('#modalWinWrapperEmail').hide();
	}
	else
	{
		$('#backOverlay').show();
		$(divName).show();
		if(timeValue > 0)
		{
			setTimeout('TogglePromoBanners(\'' + divName + '\', \'hide\', 0);', 1000 * timeValue);
		}
	}
}




/*
    http://www.JSON.org/json2.js
    2011-02-23

    Public Domain.

    NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.

    See http://www.JSON.org/js.html


    This code should be minified before deployment.
    See http://javascript.crockford.com/jsmin.html

    USE YOUR OWN COPY. IT IS EXTREMELY UNWISE TO LOAD CODE FROM SERVERS YOU DO
    NOT CONTROL.


    This file creates a global JSON object containing two methods: stringify
    and parse.

        JSON.stringify(value, replacer, space)
            value       any JavaScript value, usually an object or array.

            replacer    an optional parameter that determines how object
                        values are stringified for objects. It can be a
                        function or an array of strings.

            space       an optional parameter that specifies the indentation
                        of nested structures. If it is omitted, the text will
                        be packed without extra whitespace. If it is a number,
                        it will specify the number of spaces to indent at each
                        level. If it is a string (such as '\t' or '&nbsp;'),
                        it contains the characters used to indent at each level.

            This method produces a JSON text from a JavaScript value.

            When an object value is found, if the object contains a toJSON
            method, its toJSON method will be called and the result will be
            stringified. A toJSON method does not serialize: it returns the
            value represented by the name/value pair that should be serialized,
            or undefined if nothing should be serialized. The toJSON method
            will be passed the key associated with the value, and this will be
            bound to the value

            For example, this would serialize Dates as ISO strings.

                Date.prototype.toJSON = function (key) {
                    function f(n) {
                        // Format integers to have at least two digits.
                        return n < 10 ? '0' + n : n;
                    }

                    return this.getUTCFullYear()   + '-' +
                         f(this.getUTCMonth() + 1) + '-' +
                         f(this.getUTCDate())      + 'T' +
                         f(this.getUTCHours())     + ':' +
                         f(this.getUTCMinutes())   + ':' +
                         f(this.getUTCSeconds())   + 'Z';
                };

            You can provide an optional replacer method. It will be passed the
            key and value of each member, with this bound to the containing
            object. The value that is returned from your method will be
            serialized. If your method returns undefined, then the member will
            be excluded from the serialization.

            If the replacer parameter is an array of strings, then it will be
            used to select the members to be serialized. It filters the results
            such that only members with keys listed in the replacer array are
            stringified.

            Values that do not have JSON representations, such as undefined or
            functions, will not be serialized. Such values in objects will be
            dropped; in arrays they will be replaced with null. You can use
            a replacer function to replace those with JSON values.
            JSON.stringify(undefined) returns undefined.

            The optional space parameter produces a stringification of the
            value that is filled with line breaks and indentation to make it
            easier to read.

            If the space parameter is a non-empty string, then that string will
            be used for indentation. If the space parameter is a number, then
            the indentation will be that many spaces.

            Example:

            text = JSON.stringify(['e', {pluribus: 'unum'}]);
            // text is '["e",{"pluribus":"unum"}]'


            text = JSON.stringify(['e', {pluribus: 'unum'}], null, '\t');
            // text is '[\n\t"e",\n\t{\n\t\t"pluribus": "unum"\n\t}\n]'

            text = JSON.stringify([new Date()], function (key, value) {
                return this[key] instanceof Date ?
                    'Date(' + this[key] + ')' : value;
            });
            // text is '["Date(---current time---)"]'


        JSON.parse(text, reviver)
            This method parses a JSON text to produce an object or array.
            It can throw a SyntaxError exception.

            The optional reviver parameter is a function that can filter and
            transform the results. It receives each of the keys and values,
            and its return value is used instead of the original value.
            If it returns what it received, then the structure is not modified.
            If it returns undefined then the member is deleted.

            Example:

            // Parse the text. Values that look like ISO date strings will
            // be converted to Date objects.

            myData = JSON.parse(text, function (key, value) {
                var a;
                if (typeof value === 'string') {
                    a =
/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/.exec(value);
                    if (a) {
                        return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4],
                            +a[5], +a[6]));
                    }
                }
                return value;
            });

            myData = JSON.parse('["Date(09/09/2001)"]', function (key, value) {
                var d;
                if (typeof value === 'string' &&
                        value.slice(0, 5) === 'Date(' &&
                        value.slice(-1) === ')') {
                    d = new Date(value.slice(5, -1));
                    if (d) {
                        return d;
                    }
                }
                return value;
            });


    This is a reference implementation. You are free to copy, modify, or
    redistribute.
*/

/*jslint evil: true, strict: false, regexp: false */

/*members "", "\b", "\t", "\n", "\f", "\r", "\"", JSON, "\\", apply,
    call, charCodeAt, getUTCDate, getUTCFullYear, getUTCHours,
    getUTCMinutes, getUTCMonth, getUTCSeconds, hasOwnProperty, join,
    lastIndex, length, parse, prototype, push, replace, slice, stringify,
    test, toJSON, toString, valueOf
*/


// Create a JSON object only if one does not already exist. We create the
// methods in a closure to avoid creating global variables.

var JSON;
if (!JSON) {
    JSON = {};
}

(function () {
    "use strict";

    function f(n) {
        // Format integers to have at least two digits.
        return n < 10 ? '0' + n : n;
    }

    if (typeof Date.prototype.toJSON !== 'function') {

        Date.prototype.toJSON = function (key) {

            return isFinite(this.valueOf()) ?
                this.getUTCFullYear()     + '-' +
                f(this.getUTCMonth() + 1) + '-' +
                f(this.getUTCDate())      + 'T' +
                f(this.getUTCHours())     + ':' +
                f(this.getUTCMinutes())   + ':' +
                f(this.getUTCSeconds())   + 'Z' : null;
        };

        String.prototype.toJSON      =
            Number.prototype.toJSON  =
            Boolean.prototype.toJSON = function (key) {
                return this.valueOf();
            };
    }

    var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
        escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
        gap,
        indent,
        meta = {    // table of character substitutions
            '\b': '\\b',
            '\t': '\\t',
            '\n': '\\n',
            '\f': '\\f',
            '\r': '\\r',
            '"' : '\\"',
            '\\': '\\\\'
        },
        rep;


    function quote(string) {

// If the string contains no control characters, no quote characters, and no
// backslash characters, then we can safely slap some quotes around it.
// Otherwise we must also replace the offending characters with safe escape
// sequences.

        escapable.lastIndex = 0;
        return escapable.test(string) ? '"' + string.replace(escapable, function (a) {
            var c = meta[a];
            return typeof c === 'string' ? c :
                '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
        }) + '"' : '"' + string + '"';
    }


    function str(key, holder) {

// Produce a string from holder[key].

        var i,          // The loop counter.
            k,          // The member key.
            v,          // The member value.
            length,
            mind = gap,
            partial,
            value = holder[key];

// If the value has a toJSON method, call it to obtain a replacement value.

        if (value && typeof value === 'object' &&
                typeof value.toJSON === 'function') {
            value = value.toJSON(key);
        }

// If we were called with a replacer function, then call the replacer to
// obtain a replacement value.

        if (typeof rep === 'function') {
            value = rep.call(holder, key, value);
        }

// What happens next depends on the value's type.

        switch (typeof value) {
        case 'string':
            return quote(value);

        case 'number':

// JSON numbers must be finite. Encode non-finite numbers as null.

            return isFinite(value) ? String(value) : 'null';

        case 'boolean':
        case 'null':

// If the value is a boolean or null, convert it to a string. Note:
// typeof null does not produce 'null'. The case is included here in
// the remote chance that this gets fixed someday.

            return String(value);

// If the type is 'object', we might be dealing with an object or an array or
// null.

        case 'object':

// Due to a specification blunder in ECMAScript, typeof null is 'object',
// so watch out for that case.

            if (!value) {
                return 'null';
            }

// Make an array to hold the partial results of stringifying this object value.

            gap += indent;
            partial = [];

// Is the value an array?

            if (Object.prototype.toString.apply(value) === '[object Array]') {

// The value is an array. Stringify every element. Use null as a placeholder
// for non-JSON values.

                length = value.length;
                for (i = 0; i < length; i += 1) {
                    partial[i] = str(i, value) || 'null';
                }

// Join all of the elements together, separated with commas, and wrap them in
// brackets.

                v = partial.length === 0 ? '[]' : gap ?
                    '[\n' + gap + partial.join(',\n' + gap) + '\n' + mind + ']' :
                    '[' + partial.join(',') + ']';
                gap = mind;
                return v;
            }

// If the replacer is an array, use it to select the members to be stringified.

            if (rep && typeof rep === 'object') {
                length = rep.length;
                for (i = 0; i < length; i += 1) {
                    if (typeof rep[i] === 'string') {
                        k = rep[i];
                        v = str(k, value);
                        if (v) {
                            partial.push(quote(k) + (gap ? ': ' : ':') + v);
                        }
                    }
                }
            } else {

// Otherwise, iterate through all of the keys in the object.

                for (k in value) {
                    if (Object.prototype.hasOwnProperty.call(value, k)) {
                        v = str(k, value);
                        if (v) {
                            partial.push(quote(k) + (gap ? ': ' : ':') + v);
                        }
                    }
                }
            }

// Join all of the member texts together, separated with commas,
// and wrap them in braces.

            v = partial.length === 0 ? '{}' : gap ?
                '{\n' + gap + partial.join(',\n' + gap) + '\n' + mind + '}' :
                '{' + partial.join(',') + '}';
            gap = mind;
            return v;
        }
    }

// If the JSON object does not yet have a stringify method, give it one.

    if (typeof JSON.stringify !== 'function') {
        JSON.stringify = function (value, replacer, space) {

// The stringify method takes a value and an optional replacer, and an optional
// space parameter, and returns a JSON text. The replacer can be a function
// that can replace values, or an array of strings that will select the keys.
// A default replacer method can be provided. Use of the space parameter can
// produce text that is more easily readable.

            var i;
            gap = '';
            indent = '';

// If the space parameter is a number, make an indent string containing that
// many spaces.

            if (typeof space === 'number') {
                for (i = 0; i < space; i += 1) {
                    indent += ' ';
                }

// If the space parameter is a string, it will be used as the indent string.

            } else if (typeof space === 'string') {
                indent = space;
            }

// If there is a replacer, it must be a function or an array.
// Otherwise, throw an error.

            rep = replacer;
            if (replacer && typeof replacer !== 'function' &&
                    (typeof replacer !== 'object' ||
                    typeof replacer.length !== 'number')) {
                throw new Error('JSON.stringify');
            }

// Make a fake root object containing our value under the key of ''.
// Return the result of stringifying the value.

            return str('', {'': value});
        };
    }


// If the JSON object does not yet have a parse method, give it one.

    if (typeof JSON.parse !== 'function') {
        JSON.parse = function (text, reviver) {

// The parse method takes a text and an optional reviver function, and returns
// a JavaScript value if the text is a valid JSON text.

            var j;

            function walk(holder, key) {

// The walk method is used to recursively walk the resulting structure so
// that modifications can be made.

                var k, v, value = holder[key];
                if (value && typeof value === 'object') {
                    for (k in value) {
                        if (Object.prototype.hasOwnProperty.call(value, k)) {
                            v = walk(value, k);
                            if (v !== undefined) {
                                value[k] = v;
                            } else {
                                delete value[k];
                            }
                        }
                    }
                }
                return reviver.call(holder, key, value);
            }


// Parsing happens in four stages. In the first stage, we replace certain
// Unicode characters with escape sequences. JavaScript handles many characters
// incorrectly, either silently deleting them, or treating them as line endings.

            text = String(text);
            cx.lastIndex = 0;
            if (cx.test(text)) {
                text = text.replace(cx, function (a) {
                    return '\\u' +
                        ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
                });
            }

// In the second stage, we run the text against regular expressions that look
// for non-JSON patterns. We are especially concerned with '()' and 'new'
// because they can cause invocation, and '=' because it can cause mutation.
// But just to be safe, we want to reject all unexpected forms.

// We split the second stage into 4 regexp operations in order to work around
// crippling inefficiencies in IE's and Safari's regexp engines. First we
// replace the JSON backslash pairs with '@' (a non-JSON character). Second, we
// replace all simple value tokens with ']' characters. Third, we delete all
// open brackets that follow a colon or comma or that begin the text. Finally,
// we look to see that the remaining characters are only whitespace or ']' or
// ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval.

            if (/^[\],:{}\s]*$/
                    .test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@')
                        .replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']')
                        .replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) {

// In the third stage we use the eval function to compile the text into a
// JavaScript structure. The '{' operator is subject to a syntactic ambiguity
// in JavaScript: it can begin a block or an object literal. We wrap the text
// in parens to eliminate the ambiguity.

                j = eval('(' + text + ')');

// In the optional fourth stage, we recursively walk the new structure, passing
// each name/value pair to a reviver function for possible transformation.

                return typeof reviver === 'function' ?
                    walk({'': j}, '') : j;
            }

// If the text is not JSON parseable, then a SyntaxError is thrown.

            throw new SyntaxError('JSON.parse');
        };
    }
}());

