// browser sniff
var sniff =  {
	isIE: false,
	isIE6: false,
	isIE7: false,
	isIPhone: false,
	isAndroid: false,
	isBB: false,
	init: function() {
		if (navigator.userAgent.indexOf("MSIE 6.0") != -1) {
			this.isIE6 = true;
		} else if (navigator.userAgent.indexOf("MSIE 7.0") != -1) {
			this.isIE7 = true;	
		}
		if (this.isIE6 || this.isIE7) { this.isIE = true }
		
		if (navigator.userAgent.indexOf("iPhone") != -1) {
			this.isIPhone = true;
		} 
		
		if (navigator.userAgent.indexOf("Android") != -1) {
			this.isAndroid = true;
		}
		
		
		if (navigator.userAgent.indexOf('BlackBerry') != -1) {
			this.isBB = true;
		}
	}	
}

// trace function for firebug
var trace = function(obj) {
	if (window.console.log) {
		window.console.log(obj);
	}
}

// search helper app
var search = {
	init: function() {
		$('search').value = '';
		Event.observe('search','focus',this.focusApp);
		Event.observe('search','blur',this.blurApp);
	},
	focusApp: function(e) {
		var target = Event.element(e);
		if (!$F(target)) {
			$('search_label').hide();
		}
	},
	blurApp: function(e) {
		var target = Event.element(e);
		if (!$F(target)) {
			$('search_label').show();
		}
	}
}

var login = {
	regSlide: function(mode) {
		var obj = $('login_slide');
		switch (mode) {
			case "down":
				new Effect.SlideDown(obj, {duration: .5});
				var focusTimer = window.setTimeout(function(){
					$('username_login').focus();
				},500)
			break;
			case "up":
				new Effect.SlideUp(obj, {duration: .5});
			break;			
		}
	},
	toolBar: function() {
		//$('user_tools_menu').toggle();
		new Effect.toggle('user_tools_menu','blind',{duration: .5});
	}
}



var ads = {
	sponsorWrite: function(cssPath,urlPath) {
	}
}

// cookie helper app
var Cookie = {
  set: function(name, value, daysToExpire) {
    var expire = '';
    if (daysToExpire != undefined) {
      var d = new Date();
      d.setTime(d.getTime() + (86400000 * parseFloat(daysToExpire)));
      expire = '; expires=' + d.toGMTString();
    }
    return (document.cookie = escape(name) + '=' + escape(value || '') + expire);
  },
  get: function(name) {
    var cookie = document.cookie.match(new RegExp('(^|;)\\s*' + escape(name) + '=([^;\\s]*)'));
    return (cookie ? unescape(cookie[2]) : null);
  },
  erase: function(name) {
    var cookie = Cookie.get(name) || true;
    Cookie.set(name, '', -1);
    return cookie;
  },
  accept: function() {
    if (typeof navigator.cookieEnabled == 'boolean') {
      return navigator.cookieEnabled;
    }
    Cookie.set('_test', '1');
    return (Cookie.erase('_test') === '1');
  }
}

// new cookie helper app
var Cookies = Class.create({
    initialize: function(path, domain) {
        this.path = path || '/';
        this.domain = domain || null;
    },
    // Sets a cookie
    set: function(key, value, days) {
        if (typeof key != 'string') {
            throw "Invalid key";
        }
        if (typeof value != 'string' && typeof value != 'number') {
            throw "Invalid value";
        }
        if (days && typeof days != 'number') {
            throw "Invalid expiration time";
        }
        var setValue = key+'='+escape(new String(value));
        if (days) {
            var date = new Date();
            date.setTime(date.getTime()+(days*24*60*60*1000));
            var setExpiration = "; expires="+date.toGMTString();
        } else var setExpiration = "";
        var setPath = '; path='+escape(this.path);
        var setDomain = (this.domain) ? '; domain='+escape(this.domain) : '';
        var cookieString = setValue+setExpiration+setPath+setDomain;
        document.cookie = cookieString;
    },
    // Returns a cookie value or false
    get: function(key) {
        var keyEquals = key+"=";
        var value = false;
        document.cookie.split(';').invoke('strip').each(function(s){
            if (s.startsWith(keyEquals)) {
                value = unescape(s.substring(keyEquals.length, s.length));
                throw $break;
            }
        });
        return value;
    },
    // Clears a cookie
    clear: function(key) {
        this.set(key,'',-1);
    },
    // Clears all cookies
    clearAll: function() {
        document.cookie.split(';').collect(function(s){
            return s.split('=').first().strip();
        }).each(function(key){
            this.clear(key);
        }.bind(this));
    }
});


// various global utility functions, stuff that gets run onload, etc.
var util =  {
	init: function() {
		sniff.init();
		util.bbRedirect();
		util.e3insider_headerHide();
		search.init();
		util.mobileLink();
		util.ie6Pwn();
	},
	e3insider_headerHide: function() {
		if (!$('main-header')) {return false;}
		(function() {
			var masterNav = $$('.mast-nav')[0];
			masterNav.style.position = 'static';
			new Effect.Morph('main-header', {style: 'height: 41px; background: color: #000', duration: 2});
			(function() {
				Effect.Appear('nav-bar',{duration: .5});
			}).delay(2);
		}).delay(7);

		
	},
	bbRedirect: function() {
		if (	navigator.userAgent.indexOf('AppleWebKit') == -1
				&& navigator.userAgent.indexOf('Mozilla') == -1
				&& navigator.userAgent.indexOf('Opera') == -1) {
			window.location = 'http://m.e3expo.com'
		}
	},
	mobileLink: function() {
		if(sniff.isIPhone || sniff.isAndroid) {
			var mobileButton = new Element('a', {'href': 'http://m.e3expo.com', 'title': 'E3 Expo Mobile', 'class': 'mobile-link'});
			mobileButton.innerHTML = 'E3 Expo Mobile';
			$('header').insert(mobileButton);
		} 
	},
	ie6Pwn: function() {
		if (sniff.isIE6 && Cookie.get('ie_alert') == null) {
			var newDiv = new Element('div',{id: 'ie6_alert'});
			var mssg = '<h2>You are using Internet Explorer 6.</h2>';
			mssg += '<p>You\'re using IE 6, this site works best with FireFox and/or IE7. We suggest you upgrade or switch to one of the following: </p>';
			mssg += '<ul>';
			mssg += '<li class="ff"><a href="http://www.mozilla.com/en-US/firefox/all.html">Mozilla Firefox</a></li>';
			mssg += '<li class="safari"><a href="http://www.apple.com/safari/download/">Apple Safari</a></li>';
			mssg += '<li class="ie7"><a href="http://www.microsoft.com/windows/downloads/ie/getitnow.mspx">Microsoft Internet Explorer 7</a></li>';
			mssg += '<li class="ie8"><a href="http://www.microsoft.com/windows/downloads/ie/getitnow.mspx">Microsoft Internet Explorer 8</a></li>';
			mssg += '<li class="close"><a href="##" onclick="util.hideIEMssg()">close</a></li>';
			mssg += '</ul>';
			newDiv.update(mssg);
			$('main_wrap').insertBefore(newDiv,$('ad_bar'));
		}
	},
	hideIEMssg: function() {
		Cookie.set('ie_alert','false',7);
		new Effect.BlindUp('ie6_alert',{duration: .5});
		var removeTimer = window.setTimeout(function(){
			$('ie6_alert').parentNode.removeChild($('ie6_alert'));
		},1000);
	},
	// makes dialog box for messaging users
	talkbox: function(h) {
		var content = $H(h.evalJSON());
		content = content._object;
		if ($('talkBox')) {
			$('talkHeader').update(content.header);
			$('talkTarget').update(content.bodyContent);
			return;
		}
		var newX = $('wrapper').getWidth() / 2 - 400 / 2;
		if (self.pageYOffset)  {
			newY = self.pageYOffset;
		}
		else if (document.documentElement && document.documentElement.scrollTop) {
			newY = document.documentElement.scrollTop;
		}
		else if (document.body) {
			newY = document.body.scrollTop;
		}
		newY += 200;
		var newDiv = Builder.node('div',{
				id: 'talkBox', 
				className: 'app-window',
				style: 'top: ' + newY + 'px; left: ' + newX +'px; display: none;'},
			[Builder.node('a',
				{href: '#', className: 'close', onclick: 'util.removebox(); return false;'},
				[Builder.node('span','close')]
			)]
		);
		var content = $H(h.evalJSON());
		content = content._object;
		var talkHeader = Builder.node('h2',{id: 'talkHeader'}, content.header);
		var targetDiv = Builder.node('div',{id: 'talkTarget'}, '');
		$('wrapper').appendChild(newDiv);
		$('talkBox').appendChild(talkHeader);
		$('talkBox').appendChild(targetDiv);
		$('talkTarget').update(content.bodyContent);
		new Effect.Appear('talkBox', {duration: .5});
		new Draggable('talkBox',{handle: 'talkHeader'});
	},
	removebox: function() {
		new Effect.Fade('talkBox', {duration: .5});
		var removeTimer = window.setTimeout(function(){
			$('talkBox').parentNode.removeChild($('talkBox'));	
		}, 500);
	},
	adContainer: null
}

// dev debug toolz
var _tools = {
	ajaxBug: function(t) {
		$$('body')[0].style.background = 'none';
		$('wrapper').update(t.responseText);
	}
}

//email a friend tool
var email = {
	reveal: function(title) {
		new Effect.BlindDown($$('.email-form')[0]);
		return false;
	},
	cloak: function() {
		new Effect.BlindUp($$('.email-form')[0]);
		return false;
	},
	sbt: function() {
		if ($('email_to').value == '') 
			alert('Please enter an email address to send to.');
		else {
			if ($('email_from').value == '') 
				alert('Please enter your email address.');
			else {
				new Ajax.Request('/bin/email/email-a-friend.cfm', {
					method: 'post',
					parameters: {
						sendTo: $('email_to').value,
						sendFrom: $('email_from').value,
						title: $('title').value
					},
					onSuccess: function(t){
						$('emailContent').update(t.responseText);
					},
					onFailure: function(t){
						$('emailContent').update('Failure!');
					}
				});
			}
		}
	}
}

document.observe("dom:loaded",util.init);