﻿// Check to see if a mobile device is used and redirect accordingly
(function () {
	var getCookie = function (key) {
		if (document.cookie.length > 0) {
			var cookies = document.cookie.split(';');

			for (n = 0; n < cookies.length; n++) {
				var pair = cookies[n].split('=');
				var name = pair[0].replace(/\s/g, '');

				if (name == key) {
					return pair[1];
				}
			}

			return null;
		} else {
			return null;
		}
	};
	
	var getElementsByClassName = function (tagname, classname) {
		var tag_els = document.getElementsByTagName(tagname);
		var class_els = [];
		
		for (var n = 0; n < tag_els.length; n++) {
			if (tag_els[n].className == classname) {
				class_els.push(tag_els[n]);
			}
		}
		
		return class_els;
	};
	
	var addMobileButton = function() {
		// Add "View Mobile Website" button
		var button = document.createElement('img');
		var hyperlink = document.createElement('a');
		var headerMod = getElementsByClassName('table', 'headerMod');
		
		button.setAttribute('src', '/images/mobile-web-button.png');
		button.setAttribute('alt', 'View Mobile Website');
		
		hyperlink.setAttribute('href', '/mobile/');
		hyperlink.style.marginRight = '10px';
		
		hyperlink.appendChild(button);
		
		// Add button to first table row
		headerMod[0].getElementsByTagName('td')[0].appendChild(hyperlink);
	};

	if (screen.width <= 699) {
		var redirect = getCookie('mobile');

		if (redirect == 'true' || redirect == null) {
			document.location = '/mobile/';
		} else {
			if (window.addEventListener) window.addEventListener('load', addMobileButton, false);
			else if (window.attachEvent) window.attachEvent('onload', addMobileButton);
		}
	}
})();
