
// browser sniff
var sniff =  {
	isIE: false,
	isIE6: false,
	isIE7: false,
	isFFMac: 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("Macintosh") != -1 && navigator.userAgent.indexOf("Firefox") != -1) {
			this.isFFMac = true;
		}
	}
}
sniff.init();

(function(){
	document.write('<script type="text/javascript" src="/global/scripts/pt-add-ons/prototip.js"></script>');
	document.write('<script type="text/javascript" src="/global/scripts/pt-add-ons/starbox.js"></script>');
	if (!sniff.isIE) {
		document.write('<script type="text/javascript" src="/global/scripts/pt-add-ons/lightview.js"></script>');
	}
})();

// trace function for firebug
var trace = function(obj) {
	try {
		window.console.log(obj);		
	} catch(err) {
		return false;
	}
}

// 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');
  }
}


// ad object
ads =  {
	dartSite: null,
	dartZone: null,
	ord: Math.floor(Math.random()*10000000000000000),
	adCall: function(site,zone) {
		ads.dartSite = site;
		ads.dartZone = zone;
	},
	sponsorWrite: function(cssPath,urlPath) {
		var newLink = new Element('link',{
			rel: 'stylesheet',
			type: 'text/css',
			media: 'screen',
			href: cssPath
		});
		$$('head')[0].appendChild(newLink);
		if (urlPath) {
			ads.clickableSkin(urlPath);
		}
	},
	clickableSkin: function(urlPath) {
		Event.observe($$('body')[0], 'click', function(e){
			var currentNode = Event.element(e);
			if (currentNode.parentNode == $$('html')[0]) {
				var newWindow = window.open(urlPath, '_blank');
				newWindow.focus();
				return false;
			}
		});
	}
}

// login helper object
var login = {
	testLightView: function() {
		try {
			var test = Lightview;
		} catch (error) {
			var newScript = new Element('script',{
				type: "text/javascript",
				src: "/global/scripts/pt-add-ons/lightview.js"
			});
			$$('head')[0].appendChild(newScript);
			var lagTimer = setTimeout(function() {
				Lightview.load();
				Lightview.start.bind(Lightview)();
			}, 100);
		}
	},
	promptLogin: function(type) {
		login.testLightView();
		if (!$('login_cont') || !$('login_cont').className == type) {
			var newDiv = new Element('div',{
				id: "login_cont",
				className: type
			});
			$('wrapper').appendChild(newDiv);
		}
		if ($('login_cont').childNodes.length == 0 || $('login_cont').className != type) {
			new Ajax.Request('/login/ajax/get_login_prompt/', {
				method: 'post',
				parameters: {
					formType: type	
				},
				onSuccess: function(t) {
					$('login_cont').className = type;
					$('login_cont').update(t.responseText);
				},
				onFailure: function(t) {
					_tools.ajaxBug(t);
				}
			});
		}
		var lagTimer = setTimeout(function() {
			Lightview.show({
			    href: '#login_cont',
			    rel: 'inline',
			    options: {
			        autosize: true
			    }
			});
		}, 200);
		var focusTimer = setTimeout(function() {
			$('username_login').focus();
		}, 1500);
		return false;
	},
	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});
	}
}

document.observe('lightview:hidden',function(){
	if ($('login_cont') && $('login_cont').visible()) {
		$('login_cont').hide();
	}
});

// share functions
var shareIt = {
	init: function(t) {
		var share_title = 'edit_title-' + t;
		var share_blurb = 'edit_blurb-' + t;
		var share_url = 'edit_url-' + t;
		dataReturn = {
			"title": $(share_title).innerHTML,
			"blurb": $(share_blurb).innerHTML,
			"url": $(share_url).innerHTML
		}
		return dataReturn;
	},
	digg: function(t) {
		var dataObject = this.init(t);
		this.goURL("http://digg.com/submit?phase=2&url=" + encodeURIComponent(dataObject.url)+ "&title=" + encodeURIComponent(dataObject.title)+ "&bodytext=" + encodeURIComponent(dataObject.blurb));
	},
	facebook: function(t) {
		var dataObject = this.init(t);
		this.goURL("http://www.facebook.com/share.php?u=" + dataObject.url);
	},
	delicious: function(t) {
		var dataObject = this.init(t);
		this.goURL("https://secure.del.icio.us/login?url=" + encodeURIComponent(dataObject.url) + "&title=" + encodeURIComponent(dataObject.title) + "&jump=close&partner=addthis&v=4");
	},
	stumbleit: function(t) {
		var dataObject = this.init(t);
		this.goURL("http://www.stumbleupon.com/submit?url=" + dataObject.url+ "&title=" + dataObject.title);
	},
/*	widget: function(mode,battleID) {
		new Ajax.Request('/scripts/ajax/widgets/', {
			method: 'post',
			parameters: {
				mode: mode	,
				battleID: battleID
			},
			onSuccess: function(t) {
				appOverlay();
				setApp(t.responseText);		
			},
			onFailure: function(t) {
				appOverlay();
				setApp(t.responseText);		
			}
		});
	},*/
	goURL: function(newURL) {
		window.location.href = newURL;
	}
}

// various global utility functions, stuff that gets run onload, etc.
var util =  {
	init: function() {
		scores.setReviewScores();
		Custom.init();
	},
	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 and 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/products/download.html?product=firefox-2.0.0.12&os=win&lang=en-US">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/products/winfamily/ie/ie8/readiness/Install.htm">Microsoft Internet Explorer 8 beta</a></li>';
			mssg += '<li class="close"><a href="##" onclick="util.hideIEMssg(); return false;">hide this message</a></li>';
			mssg += '</ul>';
			newDiv.update(mssg);
			$('wrapper').insertBefore(newDiv,$('content'));
		}
	},
	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);
	},
	suckerfish: function() {
		if (!sniff.isIE) { return };
		$A(document.getElementsByClassName('suckerfish')).each(function(menuAt){
			menuAt.onmouseover = function() {
				//$(menuAt).addClassName('hover');
			}
			menuAt.onmouseout = function() {
				//$(menuAt).removeClassName('hover');
			}
		});	
	},
	
	// getting basic non-secure user data
	userData: function() {
		if (Cookie.get('USER')) {
			return $H(Cookie.get('USER').evalJSON())._object;	
		} else {
			return null;
		}
	},
	userName: function() {
		if (util.userData()) {
			return util.userData().login_name;
		} else {
			return null;
		}
	},
	userNameID: function() {
		if (util.userData()) {
			return util.userData().login_name + ':' + util.userData().user_id;
		} else {
			return "";
		}
	},
	
	// makes dialog box for messaging users
	talkbox: function(h) {
		var content = $H(h.evalJSON()).toObject();
		if ($('talkBox')) {
			$('talkHeader').update(content.header);
			$('talkTarget').update(content.bodyContent);
			new Effect.Highlight('talkTarget');
			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()).toObject();
		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});
		util.toggleLeader('off');
		new Draggable('talkBox',{handle: 'talkHeader'});
		var highLightTimer = window.setTimeout(function(){
			new Effect.Highlight('talkTarget');
		},500);
	},
	removebox: function() {
		util.toggleLeader('on');
		new Effect.Fade('talkBox', {duration: .5});
		var removeTimer = window.setTimeout(function(){
			$('talkBox').parentNode.removeChild($('talkBox'));	
		}, 500);

	},
	toggleLeader: function(mode) {
		switch(mode) {
			case "off":
				if ($('leaderboard').select('iframe').length != 0) {
					$('leaderboard').hide();
				}
			break;
			case "on":
				if (!$('leaderboard').visible()) {
					$('leaderboard').show();
				}
			break;
		}
	},
	setLoading: function() {
		var mssg = {
			"header": 'Loading Content',
			"bodyContent": "<div class=\"loading\"><p>Loading</p></div>"
		}
		util.talkbox($H(mssg).toJSON());
	},
	setSaving: function() {
		var mssg = {
			"header": 'Saving Data',
			"bodyContent": "<div class=\"loading\"><p>Saving</p></div>"
		}
		util.talkbox($H(mssg).toJSON());
	},
	promptLogin: function() {
		login.promptLogin('content');
	}
}

var scores = {
	setReviewScores: function() {
		$$('.review-score').each(function(itemAt){
		    var score = itemAt.id.split('_')[1];
			var imagePath = '../skins/' + settings.siteSkin + '/img/starbox/';
		    new Starbox(itemAt, score,{
		        locked: true,
				overlay: 'big.png',
				overlayImages: imagePath
		    });
		});
		$$('.gp-review-score').each(function(itemAt){
		    var score = itemAt.id.split('_')[1];
		    new Starbox(itemAt, score,{
		        locked: true,
				overlay: 'default.png',
				overlayImages: '../skins/' + settings.siteSkin + '/img/starbox/'
		    });
		});
	}
}


document.observe('dom:loaded',util.init);
