/*
function MM_reloadPage(init) {  //reloads the window if Nav4 resized
  if (init==true) with (navigator) {if ((appName=="Netscape")&&(parseInt(appVersion)==4)) {
    document.MM_pgW=innerWidth; document.MM_pgH=innerHeight; onresize=MM_reloadPage; }}
  else if (innerWidth!=document.MM_pgW || innerHeight!=document.MM_pgH) location.reload();
}
MM_reloadPage(true);
*/


function my_openBrWindow(theURL,winName,features) {
  window.open(theURL,winName,features);
}	


function showLiveSupportIdleNotice() {
	// Only show during business hours M-F so we don't have to rely on 'real-time' detection which slows down the site
	if(document.liveSupport.isAvailable() && !document.liveSupport.isInUse()) {
		document.supportReminderBar.show();
	}
}

function scheduleLiveSupportIdleNotice() {
	setTimeout('showLiveSupportIdleNotice()', 600000);	
}

function closeSupportIdleNotice() {
	document.supportReminderBar.hide();
}

function followSupportIdleNotice() {
	document.supportReminderBar.hide();	
	document.liveSupport.openWindow();
}


// Add the behavior to track the service code on any prouduct links
// that have RUSH class assigned to them
// Note in addition to having a RUSH classes assigned, links need to have a "rushdata_<servicecode>_<productid>" class assigned to them also
function applyServiceCodeTracker() {
	jQuery("a.rush, img.rush").click(
			function(e) {
			trackServiceCode(jQuery(this));
			return;
		}		
	)
}


// Make the SYNCHRONOUS Ajax call to track the user wans to view service-level specific pricing on a product
// Use synchronous call so the user's session is already modified before proceeding to product details screen
function trackServiceCode($e) {
	var clazzes = $e.attr('class').split(/\s+/);
	
	for(var i=0; i<clazzes.length; i++) {
		if(clazzes[i].indexOf('rushdata_') == 0) {
			var parts = clazzes[i].split('_');
			
			jQuery.ajax(
				{
					type: 'GET',
					url: '/catalog/serviceCodeTracker.cfm?productID=' + parts[2] + '&serviceCode=' + parts[1],
					async: false
				}
			)
			
			return;
		}
	}

	return;	
}


function URLEncode(str)
{
	// The Javascript escape and unescape functions do not correspond
	// with what browsers actually do...
	var SAFECHARS = "0123456789" +					// Numeric
					"ABCDEFGHIJKLMNOPQRSTUVWXYZ" +	// Alphabetic
					"abcdefghijklmnopqrstuvwxyz" +
					"-_.!~*'()";					// RFC2396 Mark characters
	var HEX = "0123456789ABCDEF";

	var plaintext = str;
	var encoded = "";
	for (var i = 0; i < plaintext.length; i++ ) {
		var ch = plaintext.charAt(i);
	    if (ch == " ") {
		    encoded += "+";				// x-www-urlencoded, rather than %20
		} else if (SAFECHARS.indexOf(ch) != -1) {
		    encoded += ch;
		} else {
		    var charCode = ch.charCodeAt(0);
			if (charCode > 255) {
			    alert( "Unicode Character '" 
                        + ch 
                        + "' cannot be encoded using standard URL encoding.\n" +
				          "(URL encoding only supports 8-bit characters.)\n" +
						  "A space (+) will be substituted." );
				encoded += "+";
			} else {
				encoded += "%";
				encoded += HEX.charAt((charCode >> 4) & 0xF);
				encoded += HEX.charAt(charCode & 0xF);
			}
		}
	} // for

	return encoded;
}


function URLDecode(str)
{
   // Replace + with ' '
   // Replace %xx with equivalent character
   // Put [ERROR] in output if %xx is invalid.
   var HEXCHARS = "0123456789ABCDEFabcdef"; 
   var encoded = str;
   var plaintext = "";
   var i = 0;
   while (i < encoded.length) {
       var ch = encoded.charAt(i);
	   if (ch == "+") {
	       plaintext += " ";
		   i++;
	   } else if (ch == "%") {
			if (i < (encoded.length-2) 
					&& HEXCHARS.indexOf(encoded.charAt(i+1)) != -1 
					&& HEXCHARS.indexOf(encoded.charAt(i+2)) != -1 ) {
				plaintext += unescape( encoded.substr(i,3) );
				i += 3;
			} else {
				//alert( 'Bad escape combination near ...' + encoded.substr(i) );
				plaintext += "%[ERROR]";
				i++;
			}
		} else {
		   plaintext += ch;
		   i++;
		}
	} // while
   
   return plaintext;
}


// We need to DELAY the execution of this because the DOM isn't fully loaded right away
// And we don't want to slow down the rendering of the page
jQuery(window).load(function() {
	// The referrer may NOT be saved on the app server until the user has hit their 3rd or 4th page view on our site
	// So save the value of the referrer in a cookie, and indicate if it was saved or not
	// and try and save the referrer on subsequent page views until we finally successfully save it.
	var REF_COOKIE_NAME = 'ref';
	
	
	// Parse the referer and only leave it populated if it's from an external source
	var ref = getDocReferer();
	var hostParts = window.location.hostname.split('.');
	var re = null;
	
	// Get the last 2 parts of the current host to make sure we only track referrers from domains OTHER than the CURRENT ROOT domain				
	if(hostParts.length >= 2) {
		var pattern = '^http(s)?:\\/\\/([^\\/])*' + hostParts[hostParts.length - 2] + '\\.' + hostParts[hostParts.length - 1];
		re = new RegExp(pattern, 'gi'); 
	}
	
	// Don't bother recording the referrer unless it's an EXTERNAL source
	if(!re || re.test(ref) || ref.length == 0) {
		ref = '';				
	}
	

	// If the referrer is NOT from an external source, see if a previous ref from an external source was saved in a cookie	
	if(ref.length == 0) {
		ref = getCookie(REF_COOKIE_NAME);
		if(ref == null) {
			ref = '';
		}
		
	} else {
		setCookie(REF_COOKIE_NAME, ref, 1);
		
	}
	
	if(ref.length > 0) {
		setTimeout(
			function() {		
				$.ajax({
					type: 'get',
					url: '/refs.cfm?ref=' + URLEncode(ref),
					dataType: 'text',
					success: function() {
						// Once we've successfully saved the referrer, clear it out				
						setCookie(REF_COOKIE_NAME, '', 1);
					}
				});
			},
			
			5000
		);		
	}

});


// document.referer gets ERASED after the FIRST access. So store it in another variable first
// so subsequent accesses can be performed
function getDocReferer() {
	if(document.ref == undefined) {
		document.ref = document.referrer;
		
		if(document.ref == undefined) {
			document.ref = '';
		}
	}
	
	return document.ref;
}


$(document).ready(function() {
	// Update social SHARE link values
	var docTitle = $('title').text();
	if(document.title) { // For IE
		docTitle = document.title;
	}
	
	$('p#socialShare a.shareFacebook').attr(
		'href',
		
		'http://www.facebook.com/share.php'
		+ '?u=' + encodeURIComponent(document.location.href)
		+ '&t=' + encodeURIComponent(docTitle)		
	);

	$('p#socialShare a.shareTwitter').attr(
		'href',
		
		'http://twitter.com/share'
		+ '?count=none'
		+ '&text=' + encodeURIComponent(docTitle)
	);
	
	// Disable auto-complete on forms in CHROME. Auto-Fill in chrome screws stuff up!
	if(navigator.userAgent.toLowerCase().indexOf('chrome') >= 0) {
		$('form').each(function() {
			$(this).attr('autocomplete', 'off');
		});
	}	
	
	
});


function setCookie(c_name, value, exdays) {
	var exdate = new Date();
	exdate.setDate(exdate.getDate() + exdays);

	var c_value = escape(value) + ((exdays == null) ? "" : "; expires="+exdate.toUTCString());
	document.cookie = c_name + "=" + c_value;
}


function getCookie(c_name) {
	var i, x, y, ARRcookies=document.cookie.split(";");

	for (i=0; i<ARRcookies.length; i++) {
		x = ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
		y = ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
		x = x.replace(/^\s+|\s+$/g,"");

		if (x == c_name) {
			return unescape(y);
		}
	}
	
	return null;
}


function isIosDevice() {
	var uagent = navigator.userAgent.toLowerCase();
	 
	if(
		uagent.indexOf('iphone') > -1
		|| uagent.indexOf('ipad') > -1
		|| uagent.indexOf('ipod') > -1
	) {
		return true;
	}
	
	return false;
}
