
/***
	SURVEY JAVASCRIPT

	Stanley Tools UK Survey popup

	@Authors
	Hugo & Cat
	Graham Licence

***/
/*globals window, console: true, location, setInterval, clearInterval, document */

/* ---------------------------------------------------------------- */
/* init.js															*/
/* ---------------------------------------------------------------- */

var HC = HC || {};

if (typeof console === "undefined") {
	var console = { log: function () { } };
}

(function () {

	HC.Survey = {
		survey_url: "http://www.surveygizmo.com/s3/561326/Stanley-survey", // live stanley

		asset_url: "http://www.stanleytools.co.uk/a/img/survey/",

		brand: "Stanley",

		time: "", // Time first arrived at site
		active: false,
		int_min: 2, // Time interval to show popup (minutes)
		int_sec: 30, // Time interval to show popup (seconds)
		checker: "",
		to_take: true, // still to take survey
		trigger: "",
		base: "",
		debug: false,

		init: function () {
			/// <summary>Initialise site scripts</summary>
			var c_base = this,
				cur_date = new Date(),
				survey = this.readCookie("hcsurvey"),
				now = new Date(),
				diff = new Date();
			this.base = c_base;
			if (survey) {
				if (survey === "no") {
					if (this.debug === true) {
						console.log("survey not taken yet");
					}
					// check clicks
					// check time (on interval)					
					HC.Survey.time = new Date(c_base.readCookie("su_time"));
					diff = new Date(now - HC.Survey.time);
					if (diff.getMinutes() > HC.Survey.int_min) {
						this.eraseCookie("su_running");
						if (this.debug === true) {
							console.log("del cookie");
						}
					}
					this.surveySettings(c_base);
				} else if (survey === "later") {
					if (this.debug === true) { console.log("later survey"); }
					this.time = new Date(this.readCookie("su_time"));
					// Check if month later set same
					if (this.time.getMonth() === cur_date.getMonth()) {
						// Check if day later set same
						if (this.debug === true) { console.log("same month"); }
						if (this.time.getDate() === cur_date.getDate()) {
							// no survey today
							if (this.debug === true) { console.log("survey later set as today"); }
							this.to_take = false;
						} else {
							// start survey
							this.surveySettings(c_base);
						}
					} else {
						// start survey
						this.surveySettings(c_base);
					}
				} else if (survey === "never") {
					if (this.debug === true) { console.log("never to take"); }
					this.to_take = false;
				} else if (survey === "yes") {
					if (this.debug === true) { console.log("taken"); }
					this.to_take = false;
				}
			} else {
				// Survey not taken or actioned, initialise survey
				if (this.debug === true) { console.log("nope"); }
				this.createCookie("hcsurvey", "no", 30);
				this.surveySettings(c_base);
			}
		},
		getElement: function (element) {
			var link = document.getElementsByTagName('a');
			return link;
		},
		surveySettings: function (c_base) {
			/// <summary>Set survey actions</summary>
			var survey_running = this.readCookie("su_running"),
				survey_status = "",
				cur_click = parseFloat(c_base.readCookie("su_clicks")),
				cur_date = new Date(),
				hostname = new RegExp(location.host),
				link = document.getElementsByTagName('a'),
				loc = window.location.host,
				i = 0;
			if (this.debug === true) {
				console.log("link: " + link[0]);
				console.log("link length:  " + link.length);
			}

			//Check if link external
			for (i = 0; i < link.length; i++) {
				if (link[i].href.indexOf(loc) === -1 && link[i].href.substring(0, 4) !== "java") {
					if (this.debug === true) { console.log("ext: " + link[i].href); }
					link[i].onclick = function () {
						survey_status = HC.Survey.readCookie("hcsurvey");
						console.log("survey status: " + survey_status);
						if (survey_status === "no") {
							c_base.trigger = "external%20link";
							c_base.setPopUp();
							return false;
						}
					}
					link[i].title = "external";
				}
			}

			if (this.to_take === true) {
				if (survey_running === "yes") {
					// continue click count
					this.time = new Date(this.readCookie("su_time"));
					if (this.debug === true) {
						console.log("survey timer running");
						console.log(this.time);
						console.log("current clicks: " + cur_click);
					}
					if (cur_click < 5) {
						cur_click = cur_click + 1;
						c_base.createCookie("su_clicks", cur_click);
						c_base.createCookie("su_url" + cur_click, window.location);
						HC.Survey.timer();
						this.checker = setInterval(HC.Survey.timer, 1000);
					} else { // Five internal clicks/page refresh
						c_base.trigger = "five%20clicks";
						c_base.setPopUp();
					}
				} else {
					if (this.debug === true) { console.log("survey timer started"); }
					this.time = new Date();
					this.createCookie("su_time", this.time, 1);
					this.createCookie("su_running", "yes");
					this.createCookie("su_clicks", "0");
					HC.Survey.timer();
					this.checker = setInterval(HC.Survey.timer, 1000);
				}
			}
		},
		timer: function () {
			/// <summary>Check time on site</summary>
			var then = HC.Survey.time,
				now = new Date(),
				diff = new Date(now - then),
				clicks = HC.Survey.readCookie("su_clicks");
			if (diff.getMinutes() === HC.Survey.int_min && diff.getSeconds() === HC.Survey.int_sec) {
				if (HC.Survey.active === false) {
					HC.Survey.active = true;
					HC.Survey.trigger = "time";
					HC.Survey.setPopUp();
				}
			}

		},
		setPopUp: function () {
			if (HC.Survey.to_take === true) {
				clearInterval(HC.Survey.checker);
				HC.Survey.to_take = false;
				if (this.debug === true) { console.log("launch survey"); }

				// Set opacity in IE
				var filter = function (obj, f, params) {
					var found, nf, dx = "DXImageTransform.Microsoft.";

					// check if DXImageTransform.Microsoft.[Filter] or [Filter] filter is set
					try { nf = obj.filters.item(dx + f); found = true; } catch (e) { }
					if (!found) try { nf = obj.filters.item(f); found = true; } catch (e) { }

					// filter is set - change existing one
					if (found) {
						nf.Enabled = true; // if exists, it might be disabled
						if (params) for (var i in params) nf[i] = params[i];
					} else { // filter is not set - apply new one
						nf = "";
						if (params) for (var i in params) nf += i.toLowerCase() + "=" + params[i] + ",";
						if (params) nf = "(" + nf.substr(0, nf.length - 1) + ")";
						obj.style.filter += "progid:" + dx + f + nf + " ";
					}
					// hasLayout property hack
					if (!obj.style.zoom) obj.style.zoom = 1;
				};

				// Survey Gizmo popup launch
				var sg_overlay = document.createElement("div");
				sg_overlay.id = "sg-popup-overlay";
				//sg_overlay.style.height = document.height + "px";
				sg_overlay.style.height = "100%";
				sg_overlay.style.width = "100%";
				sg_overlay.style.position = "absolute";
				sg_overlay.style.top = "0";
				sg_overlay.style.left = "0";
				sg_overlay.style.zIndex = "5000";
				sg_overlay.style.backgroundColor = "#000";
				sg_overlay.style.opacity = "0.7";
				document.body.appendChild(sg_overlay);
				// Add opacity to IE
				var obj = document.getElementById("sg-popup-overlay");
				if (document.body.filters) {
					filter(obj, "Alpha", { Opacity: 50 });
				}

				var sg_div = document.createElement("div");
				sg_div.innerHTML = "<img src=\"" + this.asset_url + "survey-icon-" + this.brand.toLowerCase().replace(/ /g, "") + ".jpg\" " +
					"style=\"float:left;margin:0 10px 0 0;\" />" +
					"<div style=\"float:left;width:550px;text-align:left;\"><h1 style=\"font-size:20px;color:#fff;margin: 0 0 10px;\">" +
						"Help make this website better</h1>" +
					"<p style=\"font-size:14px;color:#fff;margin: 0 0 22px;\">" +
						"Please spare 10 minutes to complete a short questionaire about our website. " +
						"Your opinion will help us to serve you even better in the future.</p>" +
					"<p style=\"font-size:14px;\">" +
						"<button href=\"#\" class=\"survey-link\" style=\"color:#000;margin: 0 10px 0 0;cursor:pointer;\" " +
							"onclick=\"HC.Survey.launchSurvey()\">Take survey</button>" +
						"<button href=\"#\" style=\"color:#000;margin: 0 10px 0 0;cursor:pointer;\" " +
							" onclick=\"HC.Survey.noSurvey()\">No, thank you.</button>" +
						"<button href=\"#\" style=\"color:#000;cursor:pointer;\" " +
							" onclick=\"HC.Survey.laterSurvey()\">Ask me later</button>" +
					"</p><img src=\"" + this.asset_url + "icon-close-" + this.brand.toLowerCase().replace(/ /g, "") + ".jpg\" " +
						"style=\"position:absolute;top:5px;right:5px;cursor:pointer;\" onclick=\"HC.Survey.laterSurvey()\"/>" +
					"</div>";
				sg_div.id = "sg-popup";
				sg_div.style.position = "fixed";
				sg_div.style.width = "710px";
				sg_div.style.height = "130px";
				sg_div.style.top = "100px";
				// center in browser, get window width (IE)
				if (document.body && document.body.offsetWidth) {
					sg_div.style.left = (document.body.offsetWidth - 710) / 2 + "px";
				}
				if (document.compatMode=='CSS1Compat' && document.documentElement && document.documentElement.offsetWidth ) {
					sg_div.style.left = (document.documentElement.offsetWidth - 710) / 2 + "px";
					}
				if (window.innerWidth){
					sg_div.style.left = (window.innerWidth - 710) / 2 + "px";
				}
				sg_div.style.zIndex = "5001";
				sg_div.style.backgroundColor = "#666666";
				sg_div.style.backgroundImage = "url(" + this.asset_url + "bg-popup.jpg" + ")";
				sg_div.style.padding = "20px";
				sg_div.style.fontSize = "16px";
				document.body.appendChild(sg_div);
				document.onkeydown = function (e) {
					if (e.keyCode === 27) {
						HC.Survey.laterSurvey();
					}
				};
			}
		},
		launchSurvey: function () {
			var survey_link,
				history = "",
				i = 1,
				clicks = parseInt(HC.Survey.readCookie("su_clicks"), 10) + 1;
			clearInterval(HC.Survey.checker);
			if (this.debug === true) { console.log("clicks: " + clicks); }
			for (i = 1; i < clicks; i += 1) {
				history = history + HC.Survey.readCookie("su_url" + i) + "%20";
			}
			history = history.replace(/&/g, "+");
			survey_link = this.survey_url + "?trigger=" + this.trigger + "&currentpage=" + window.location + "&history=" + history + "&brand=" + this.brand;
			if (this.debug === true) { console.log(survey_link); }
			document.getElementById('sg-popup').style.display = 'none';
			document.getElementById('sg-popup-overlay').style.display = 'none';
			this.createCookie("hcsurvey", "yes", 30);
			window.open(survey_link);
			return false;
		},
		laterSurvey: function () {
			clearInterval(HC.Survey.checker);
			document.getElementById('sg-popup').style.display = 'none';
			document.getElementById('sg-popup-overlay').style.display = 'none';
			this.createCookie("hcsurvey", "later", 30);
			this.createCookie("su_running", "later");
			this.to_take = false;
			return false;
		},
		noSurvey: function () {
			clearInterval(HC.Survey.checker);
			document.getElementById('sg-popup').style.display = 'none';
			document.getElementById('sg-popup-overlay').style.display = 'none';
			this.createCookie("hcsurvey", "never", 30);
			this.to_take = false;
			return false;
		},
		createCookie: function (name, value, days) {
			/// <summary>Create cookie</summary>
			var expires = "",
				date;
			if (days) {
				date = new Date();
				date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
				expires = "; expires=" + date.toGMTString();
				if (this.debug === true) { console.log("expires: " + expires); }
			}
			document.cookie = name + "=" + value + expires + "; path=/";
		},
		readCookie: function (name) {
			/// <summary>Read cookie</summary>
			var nameEQ = name + "=",
				ca = document.cookie.split(';'),
				i = 0,
				c = "";
			for (i = 0; i < ca.length; i += 1) {
				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;
		},
		eraseCookie: function (name) {
			/// <summary>Delete cookie</summary>
			this.createCookie(name, "", -1);
		}

	};

} ());

setTimeout("HC.Survey.init()", 0);
//HC.Survey.init();


