﻿var trace = null;
var hotsites = {
	
	initalized: false,
	utilsLoaded: false,
	
	init: function(){
		hotsites.initalized = true;
		$.getScript('http://br.brookfield.com/static/js/lib/jquery.cookie.js', hotsites.jCookie.loadComplete);
		
		try{
			tracking.baseUrl = 'http://br.brookfield.com';
		}catch(e){
			trace('tracking not present', 'info')
		}
	},
	
	openAttWindow: function(){
		var source = arguments[0];
		var url = arguments.length > 1 ? arguments[1] : 'http://www12.directtalk.com.br/server/directtalk_chatr.dll/user?S=I&id_s=A313007841AAA0145737';
		window.open(url + '&origem=' + source, 'atendimento', 'width=450,height=650');
	},

	openAttWindowOutSp: function(){
		var source = arguments[0];
		var url = arguments.length > 1 ? arguments[1] : 'http://www12.directtalk.com.br/server/directtalk_chatr.dll/user?S=I&id_s=2DF1008036E480147157';
		window.open(url + '&origem=' + source, 'atendimento', 'width=450,height=650');
	},
	
	jCookie: {
		loaded: false,
		
		loadComplete: function(e){
			hotsites.jCookie.loaded = true;
			hotsites.ga.schedules.run();
			
			$.getScript('http://br.brookfield.com/static/js/shared/utils.js', function(e){
				hotsites.utilsLoaded = true;
			});
		}
	},
	
	ga: {
		schedules: {
			tags: [],
			
			make: function(tag){
				hotsites.ga.schedules.tags.push(tag);
			},
			
			run: function(){
				for(var i in hotsites.ga.schedules.tags){
					hotsites.ga.callTag( hotsites.ga.schedules.tags[i] );
				}
			}
		},
	
		_callTag: function(tag){
			try{
				_gaq.push(['_trackPageview', tag]);
			}catch(e){
				trace('_gaq not loaded', 'info');
			}
		},
		
		callTag: function(tag){
			if(hotsites.jCookie.loaded){
				var cookie = $.cookie('channel') == null ? '' : '_' + $.cookie('channel').toUpperCase();
				var fnTag = tag + cookie;
				hotsites.ga._callTag(fnTag);
			}else{
				hotsites.ga.schedule.make(tag);
			}
		}
	},
	
	redirAttempts: 0,
	
	setCookieAndRedirect: function(cookieKey, cookieValue, redirectUrl){
		
		if(hotsites.initalized && hotsites.jCookie.loaded){
			$.cookie(cookieKey, cookieValue, { 
				expires: 7, 
				path: '/' 
			}); 
			
			setTimeout(function(){ 
				document.location.href = redirectUrl; 
			}, 500);
		}else{
			if(hotsites.redirAttempts < 10){
				var timeout = setTimeout(function(){
					hotsites.setCookieAndRedirect(cookieKey, cookieValue, redirectUrl);
					hotsites.redirAttempts++;
				}, 1000);
			}else{
				trace('redirect not running after 10 attempts', 'info');
			}
		}
	}
};

$(document).ready( hotsites.init );
