/*
 * Author:	Charles Dorner
 * Owner:	SiteCrafting, Inc.  Copyright 2011, All Rights Reserved.
 * Date:	November 4, 2011
 * Version:	1.0
 * Website: http://www.sitecrafting.com/
 * License:	This code is proprietary (Written on company time and equipment).  You do not have a license to reuse it.
 *			handleEvent is similar to many existing techniques, but does not standardize the event objects cross browser since
 *			I didn't need event data.  You should be able to find something similar on google.
 *			getCookie, setCookie, and deleteCookie are all in the public domain, and can be found with google as well.
 *			Pretty much everything else is only useful to this script.  Feel free to email me if you have questions.
 *
 * Notes:	This file was built to serve as a communication medium between two separate sites one mobile, one not mobile.
 *			These sites would serve similar content but there is not a one to one correlation between the pages.
 *			I.E. the mobile site doesn't just look different, it has different content on it.
 *
 *			The content difference matters to UI: user expectations landing on an internal page are different depending on
 *			how they arrived there - browsing a site vs. coming from a google search.
 *
 *			The basic logic here is:
 *
 *			I.	If we are NOT on a mobile browser, install the event handlers on the elements listed to link from one site to the other.
 *			II.	If we are on a mobile browser, then
 *				A.	If we are on the full site, then
 *					a.	If we are on the homepage, then
 *						1.	If we have a cookie from the user that says I want the mobile site, redirect user to the mobile homepage.
 *						2.	If we have a cookie from the user that says I want the full site, do nothing more.
 *						3.	If we have no cookie, or an "undecided" cookie, prompt the user if they would like the mobile or full site.
 *					b.	If we are not on the homepage, then
 *						1.	If we have a cookie from the user that says I want the mobile site, set the cookie to "undecided".
 *							[Since the content is different between sites, even if the cookie is set	]
 *							[to want the mobile site, the user may have landed here from google search	]
 *							[and is "perusing" the site.  We set to "maybe" because if the user clicks	]
 *							[a link to view the homepage, we want to reprompt them, not just redirect	]
 *							[back to mobile.															]
 *						2.	If we have a cookie from the user that says I want the full site, do nothing more.
 *						3.	If we have no cookie, or an "undecided" cookie, do nothing more.
 *				A.	If we are on the mobile site, then
 *					a.	If we are on the homepage, then
 *						1.	If we have a cookie from the user that says I want the mobile site, do nothing more.
 *						2.	If we have a cookie from the user that says I want the full site, redirect user to the full site.
 *						3.	If we have no cookie, or an "undecided" cookie, prompt the user if they would like the mobile or full site.
 *					b.	If we are not on the homepage, then
 *						1.	If we have a cookie from the user that says I want the mobile site, do nothing more.
 *						2.	If we have a cookie from the user that says I want the full site, set the cookie to "undecided".
 *							[Since the content is different between sites, even if the cookie is set	]
 *							[to want the full site, the user may have landed here from google search	]
 *							[and is "perusing" the site.  We set to "maybe" because if the user clicks	]
 *							[a link to view the homepage, we want to reprompt them, not just redirect	]
 *							[back to the full site.														]
 *						3.	If we have no cookie, or an "undecided" cookie, do nothing more.
 *
 *
 *			This code was written encapsulated in an immediate execution closure to isolate it from all other javascript. It attempts
 *			to be cross browser and friendly toward any existing event handlers.  It exists to be able to be dropped into an existing
 *			site where we have no control - and our code will not affect the current functionality.  It should work, even if other js
 *			components of the rest of the site do not.
 *
 */

(function() {


	/*	Settings  */
	//  Main site settings
	var NON_MOBILE_SUBDOMAIN = 'www';
	var NON_MOBILE_HOMEPAGE_PATH = '/';
	var NON_MOBILE_VIEW_MOBILE_LINK_ID = 'view-mobile-site';

	//	Mobile site settings
	var MOBILE_SUBDOMAIN = 'm';
	var MOBILE_SITE_HOMEPAGE_PATH = '/';
	var MOBILE_VIEW_NON_MOBILE_LINK_ID = 'view-main-site';

	//	Cookie setting
	var COOKIE_NAME = 'view-mobile';


	/*	Base functions  */
	var getCookie = function(name) {
		var start = document.cookie.indexOf( name + "=" );
		var len = start + name.length + 1;

		if( (!start) && (name != document.cookie.substring( 0, name.length )) ) {
			return null;
		}
		if( start == -1 ) {
			return null;
		}

		var end = document.cookie.indexOf( ';', len );
		if( end == -1 ) {
			end = document.cookie.length;
		}

		return unescape( document.cookie.substring( len, end ) );
	};

	var setCookie = function(name, value, expires, path, domain, secure) {
		var today = new Date();
		today.setTime( today.getTime() );

		if( expires ) {
			expires = expires * 1000 * 60 * 60 * 24;
		}

		var expires_date = new Date( today.getTime() + (expires) );

		document.cookie = name+'='+escape( value ) +
			( ( expires ) ? ';expires='+expires_date.toGMTString() : '' ) +
			( ( path ) ? ';path=' + path : '' ) +
			( ( domain ) ? ';domain=' + domain : '' ) +
			( ( secure ) ? ';secure' : '' );
	};

	var deleteCookie = function(name, path, domain) {
		if( getCookie(name) ) {
			document.cookie = name + '=' +
				( ( path ) ? ';path=' + path : '') +
				( ( domain ) ? ';domain=' + domain : '' ) +
				';expires=Thu, 01-Jan-1970 00:00:01 GMT';
		}
	};

	var handleEvent = function(element, type, handler) {
		if(element && typeof(element)=="object") {
			if(element.addEventListener) {
				element.addEventListener(type, handler, false);
			}
			else if(element.attachEvent) {
				element.attachEvent("on" + type, handler);
			}
			else if(typeof(element['on' + type])=='function') {
				element['on' + type] = (function () {
					var onEvent = element['on' + type];
					return function () {
						try {
							onEvent();
						}
						catch (e) {
						}
						handler();
					};
				}());
			}
			else {
				element['on' + type] = handler;
			}
		}
	};


	/*	Variable / function setup  */
	var view_mobile;
	var domain;
	var prefix;
	var hostname = window.location.hostname;
	var protocol = window.location.protocol;

	var gotoMainSite = function() {
		if(hostname != NON_MOBILE_SUBDOMAIN + '.' + domain) {
			// Switch the commenting on the next two lines to switch between testing and redirecting
//			console.log('Goto main site: ' + protocol + '//' + NON_MOBILE_SUBDOMAIN + '.' + domain);
			window.location.href = protocol + '//' + NON_MOBILE_SUBDOMAIN + '.' + domain;
		}
	};

	var gotoMobileSite = function() {
		if(hostname != MOBILE_SUBDOMAIN + '.' + domain) {
			// Switch the commenting on the next two lines to switch between testing and redirecting
//			console.log('Goto mobile site: ' + protocol + '//' + MOBILE_SUBDOMAIN + '.' + domain);
			window.location.href = protocol + '//' + MOBILE_SUBDOMAIN + '.' + domain;
		}
	};

	var setMobileCookie = function(value) {
		setCookie(COOKIE_NAME, value, 4000, '/', domain);
		return getMobileCookie();
	};

	var getMobileCookie = function() {
		return getCookie(COOKIE_NAME);
	};


	/*	Actual Processing  */
	// If we are using a mobile browser
	var onMobile = /mobile/i.test(window.navigator.userAgent);
	if(onMobile) {

		var path = window.location.pathname;

		var requestUserChoice = function(onMobileSite) {
			var okay = onMobileSite ? "stay on" : "switch to";
			var cancel = onMobileSite ? "switch to" : "stay on";
			var preference = confirm("You appear to be browsing on a mobile device.  Click 'Okay' to "+okay+" the mobile site, or 'Cancel' to "+cancel+" the full site.");
			if(preference) {
				setMobileCookie('yes');
				gotoMobileSite();
			}
			else {
				setMobileCookie('no');
				gotoMainSite();
			}
		};

		view_mobile = getMobileCookie();
		domain = hostname.split('.');
		prefix = domain.shift();
		domain = domain.join('.');

		if(prefix==MOBILE_SUBDOMAIN) {
			if (path == MOBILE_SITE_HOMEPAGE_PATH) {
				if(view_mobile == "yes") {
				}
				else if (view_mobile == "no") {
					gotoMainSite();
				}
				else {
					requestUserChoice(true);
				}
			}
			else {
				if (view_mobile == "no") {
					setMobileCookie('maybe'); // or delete the cookie
				}
			}
		}
		else if(prefix == NON_MOBILE_SUBDOMAIN) {
			if (path == NON_MOBILE_HOMEPAGE_PATH) {
				if(view_mobile == "yes") {
					gotoMobileSite();
				}
				else if (view_mobile == "no") {
				}
				else {
					requestUserChoice(false);
				}
			}
			else {
				if(view_mobile == "yes") {
					setMobileCookie('maybe'); // or delete the cookie
				}
			}
		}
	}


	/*	Setup link event handlers if we are still around.  */
	var onLoadEvent = function() {
		handleEvent(document.getElementById(MOBILE_VIEW_NON_MOBILE_LINK_ID), 'click', function(){
			setMobileCookie('no');
			gotoMainSite();
			return false;
		});

		handleEvent(document.getElementById(NON_MOBILE_VIEW_MOBILE_LINK_ID), 'click', function(){
			setMobileCookie('yes');
			gotoMobileSite();
			return false;
		});
	};

	handleEvent(window, 'load', onLoadEvent);

}());
