var utm = utm || {};
(function() {
	function alertObj(obj)  {
		var str = '';
		for (option in obj) {
				str += option + ' : ' + obj[option] + '\n';
		}
		alert(str);
	};

	function alertWin(msg,ttl) {
		var oldMsg = $('#alertWindowDiv').html();
		if (oldMsg==null) {
			oldMsg='';
		}
		$('#alertWindowDiv').remove();

		var newArr = new Array();
		newArr = msg.split('<br><br>');

		var i;
		var findstring;
		for (i in newArr) {
			findstring = (jQuery.trim(newArr[i])!='') ? newArr[i]+'<br><br>' : '';
			oldMsg = oldMsg.replace(findstring,'')
		}

		$("body").append('<div id="alertWindowDiv" style="display:none">'+oldMsg+msg+'</div>')
		$("#alertWindowDiv").dialog({
		modal:true,
		resizable:false,
		title: '<h3 style="margin-left:175px;">'+ttl+'</h3>',
		width: 600,
		buttons: {
				"Turn off notification": function() {
					$(this).dialog("close");
					var pathname = window.location.pathname;
					var patharr = pathname.split('/'); 
					var url = '';					
					switch (patharr[1]) {
						case 'dashboard': 
							url = 'http://dreamhomehub.com/dashboard/setup.php' + window.location.search;
							window.location.href=url;
							break;	
						case 'account': 
							url = 'http://dreamhomehub.com/account/tour-settings.php' + window.location.search;
							window.location.href=url;
							break;	
					};					
										
				},
				"Close": function() {
					$(this).dialog("close");
				}
		},
		close: function(event, ui) {
				$('#alertWindowDiv').remove();
			}
		});
	};

	function alertWin2(msg,ttl) {
		var oldMsg = $('#alertWindowDiv2').html();
		if (oldMsg==null) {
			oldMsg='';
		}
		$('#alertWindowDiv2').remove();

		var newArr = new Array();
		newArr = msg.split('<br><br>');

		var i;
		var findstring;
		for (i in newArr) {
			findstring = (jQuery.trim(newArr[i])!='') ? newArr[i]+'<br><br>' : '';
			oldMsg = oldMsg.replace(findstring,'')
		}

		$("body").append('<div id="alertWindowDiv2" style="display:none">'+oldMsg+msg+'</div>')
		$("#alertWindowDiv2").dialog({
		modal:true,
		resizable:false,
		title: '<h3 style="margin-left:175px;">'+ttl+'</h3>',
		width: 600,
		buttons: {
				"Turn off notification": function() {
					$(this).dialog("close");
					
					var pathname = window.location.pathname;
					var patharr = pathname.split('/'); 
					var url = '';					
					switch (patharr[1]) {
						case 'dashboard': 
							url = 'http://dreamhomehub.com/dashboard/setup.php' + window.location.search;
							window.location.href=url;
							break;	
						case 'account': 
							url = 'http://dreamhomehub.com/account/tour-settings.php' + window.location.search;
							window.location.href=url;
							break;	
					};	
					/* 
					$(this).dialog("close");
					var url = 'http://dreamhomehub.com/account/tour-settings.php' + window.location.search;
					window.location.href=url;
					*/
				},
				"Close": function() {
					$(this).dialog("close");
				}
		},
		close: function(event, ui) {
				$('#alertWindowDiv2').remove();
			}
		});
	};

	function alertObj(obj)  {
		var str = '';
		for (option in obj) {
				str += option + ' : ' + obj[option] + '\n';
		}
		alert(str);
	};

	function checkAns(msg) {
		// Вызывает исключение в: mozilla, ie, safari
		// ie: SCRIPT5007: Не удалось получить значение свойства "online": значением объекта является NULL или он не определен
		if (jQuery.trim(msg)!='') {
			var ans = jQuery.parseJSON(msg)
			//if (jQuery.trim(ans['online'])!='') alertWin(ans['online'],'Visitor Online Notification');
			//if (jQuery.trim(ans['offline'])!='') alertWin2(ans['offline'],'Visitor Offline Notification');
			if (jQuery.trim(ans[0])!='') alertWin(ans[0],'Visitor Online Notification');
			if (jQuery.trim(ans[1])!='') alertWin2(ans[1],'Visitor Offline Notification');
		}
	};

	var param = {thd: 0, usr: 0, txe: 0, pxe: 0, stt: 0};
	var tid = 0;
	utm.init = function(enable) {
		if (enable) {
			$.post('/traking.php',{ts:Math.round((new Date()).valueOf()/1000),tp:'load',pg:encodeURIComponent(location.pathname)});
			tid = setInterval(function(){$.post('/traking.php',{ts:Math.round((new Date()).valueOf()/1000),tp:'ping',pg:encodeURIComponent(location.pathname)},function(msg) {checkAns(msg);});},10000);
		};
//		param.thd = parseInt(utm.server.THD) || 300000;
//		param.stt = parseInt(utm.server.GMT) || 0;
//		param.pxe = (param.stt > 0 ? (new Date).valueOf() - (new Date(param.stt * 1000)).valueOf() : 0);
//		param.usr = parseInt(utm.server.TYP) || 0;
//		var __utm_p = utm.cookie.get('__utm_p');
//		if (__utm_p) {

//		};
		utm.cookie.set('lasturl', utm.url.current().toString());		
		
		var regEx = /\/account\//i;
		if(regEx.test(utm.url.current().toString())) {		
			utm.cookie.set('lastaccounturl', utm.url.current().toString(),31536000,'/');		
		};
		
//		utm.cookie.set('__utm_i', Math.round((new Date).valueOf() / 1000));
//		if ((utm.server.TYP && parseInt(utm.server.TYP) == utm.server.TYP) &&
//			(utm.server.GMT && parseInt(utm.server.GMT) == utm.server.GMT) &&
//			(utm.server.THD && parseInt(utm.server.THD) == utm.server.THD)) {
//			utm.timer.set();
//		};
	};
	utm.dispose = function(enable) {
		if (enable) {
			if (tid) {
				clearInterval(tid);
			};
			$.post('/traking.php',{ts:Math.round((new Date()).valueOf()/1000),tp:'unload',pg:encodeURIComponent(location.pathname)});
		};
//		var __utm_s = parseInt(utm.cookie.get('__utm_i'));
//		utm.cookie.set('__utm_u', Math.round((new Date).valueOf() / 1000));
//		var data = {
//			__utm_i: __utm_s,
//			__utm_u: Math.round((new Date).valueOf() / 1000),
//			path: location.pathname,
//			query: location.search
//		};
//		utm.request.send(data);
	};
	utm.cookie = {};
	utm.cookie.set = function(name, value, expires, path, domain, secure) {
		expires instanceof Date ? expires = expires.toGMTString() : typeof(expires) == 'number' && (expires = (new Date(+(new Date()) + expires * 1e3)).toGMTString());
		var r = [name + "=" + encodeURIComponent(unescape(value))], s, i;
		for (i in s = {
			expires: expires,
			path: path,
			domain: domain
		}) {
			s[i] && r.push(i + "=" + s[i]);
		};
		return secure && r.push("secure"), document.cookie = r.join(";"), true;
	};
	utm.cookie.get = function(name) {
		var rows = document.cookie.split(';'), r = [], i, value = '';
		for (i in rows) {
			r = rows[i].split('=');
			if (name in r) {
				value = decodeURIComponent(escape(r[1]));
				break;
			};
		};
		return value;
	};
	utm.request = {};
	utm.request.send = function(data, callback) {
		function success(value) {
			if (callback) {
				callback(value);
			};
		};
		$.post(location.href, data, callback);
	};
	utm.request.load = function(data, callback) {
		function success(value) {
			if (callback) {
				callback(value);
			};
		};
		$.get(location.href, data, success);
	};
	utm.url = {};
	utm.url.current = function() {
		var o = {
			host:location.hostname,
			path:location.pathname,
			query:location.search,
			toString: function() { return (this.path + this.query); }
		};
		return o;
	};
	utm.timer = {};
	utm.timer.set = function() {
		if (utm.timer.id) {
			clearTimeout(utm.timer.id);
		};
		if (utm.server.THD && parseInt(utm.server.THD) == utm.server.THD) {
//			utm.timer.id = setTimeout(function() {utm.timer.handler.call(utm.timer);}, param.thd);
		};
	};
	utm.timer.handler = function() {
//		if (param.usr == 1) {
//			$.post('/admin/logout.php', {logout:true}, function() { location.href = '/admin/login.php'; });
//		} else {
//			$.post('/logout.php', {logout:true}, function() { location.href = '/login.php'; });
//		};
	};
})();
