// GamePro API global.js

var trace = function(obj) {
	try {
		console.log(obj)
	} catch(err) {
		// fail
	}
}

// global object
var global = {
	init: function() {
		global.setSubNav();
		global.setEmbedInputs();
		//util.setMainNav();
	},
	setSubNav: function() {
		$$('ul.api-nav')[0].select('a').each(function(linkAt) {
			if (linkAt.href.indexOf('#') != -1) {
				linkAt.onclick = function() {
					this.blur();
					return false;
				}
			}
		});
	},
	setEmbedInputs: function() {
		if (!$('news_embed')) { return false; }
		var embedCode = {
			'news': '<object width="300" height="250" type="application/x-shockwave-flash" quality="high" id="W4a1f1dce3da75946" data="http://widgets.clearspring.com/o/49f8a96303a6cedf/4a1f1dce3da75946/49f8a96303a6cedf/b862914" allowScriptAccess="always" allowNetworking="all" pluginspage="http://www.macromedia.com/go/getflashplayer"><param value="http://widgets.clearspring.com/o/49f8a96303a6cedf/4a1f1dce3da75946/49f8a96303a6cedf/b862914" name="movie"/><param name="wmode" value="opaque"/><param name="allowScriptAccess" value="always"/></object>',
			'editors': '<object type="application/x-shockwave-flash" data="http://widgets.clearspring.com/o/4a0a11a00688acf6/4a1f1e3b1ca4f01e/4a0a11e5c0a192ef/84d38ad6" id="W4a0a11a00688acf64a1f1e3b1ca4f01e" width="300" height="270"><param name="movie" value="http://widgets.clearspring.com/o/4a0a11a00688acf6/4a1f1e3b1ca4f01e/4a0a11e5c0a192ef/84d38ad6" /><param name="wmode" value="transparent" /><param name="allowNetworking" value="all" /><param name="allowScriptAccess" value="always" /></object>',
			'calendar': '<object type="application/x-shockwave-flash" data="http://widgets.clearspring.com/o/4a1f2bb2d15f8d6c/4a1f2c1bbfdcfa96/4a1f2bb2d15f8d6c/4bb43f9" id="W4a1f2bb2d15f8d6c4a1f2c1bbfdcfa96" width="300" height="320"><param name="movie" value="http://widgets.clearspring.com/o/4a1f2bb2d15f8d6c/4a1f2c1bbfdcfa96/4a1f2bb2d15f8d6c/4bb43f9" /><param name="wmode" value="transparent" /><param name="allowNetworking" value="all" /><param name="allowScriptAccess" value="always" /></object>'
		}
		var inputList = [];
		inputList.push($('news_embed'));
		inputList.push($('editors_embed'));
		inputList.push($('calendar_embed'));
		inputList.each(function(inputAt) {
			var shortName = inputAt.id.split("_")[0];
			var dataName = 'embedCode.' + shortName;
			inputAt.value = eval(dataName);
			Event.observe($(inputAt), 'focus', function(e){
				var target = Event.element(e);
				target.select();
			});
		});
	}
}

// login helper object
var login = {
	firstLogin: true,
	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);
			(function(){
				Lightview.load();
				Lightview.start.bind(Lightview)();
			}).delay(.1);
		}
	},
	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	
				},
				onFailure: function(t) {
					_tools.ajaxBug(t);
				},
				onSuccess: function(t) {
					$('login_cont').className = type;
					$('login_cont').update(t.responseText);
				}
			});
		}
		(function(){
			Lightview.show({
			    href: '#login_cont',
			    rel: 'inline',
			    options: {
					width: 420,
					height: 170
			    }
			});
			if (login.firstLogin) {
				login.firstLogin = false;
				document.observe('lightview:opened', function() {
				  	$('login_cont').addClassName('show');
					if ($('username_login')) {
						$('username_login').focus();
					}
				});
				Event.observe($$('.lv_Close')[0], 'click', function(){
					$('login_cont').removeClassName('show');
				});
				Event.observe($('lv_overlay'), 'click', function(){
					$('login_cont').removeClassName('show');
				});
			}
		}).delay(.2);
		return false;
	},
	passwordReset: function() {
		new Ajax.Request('/login/ajax/password_email_form/', {
			onFailure: function(t) {
				_tools.ajaxBug(t);
			},
			onSuccess: function(t) {
				$('login_cont').update(t.responseText);
			}
		});
		return false;
	},
	sendPassReset: function() {
		new Ajax.Request('/login/ajax/password_reset/', {
			method: 'post',
			parameters: $('passReset').serialize(true),
			onFailure: function(t){
				_tools.ajaxBug(t);
			},
			onSuccess: function(t) {
				$('login_cont').update(t.responseText);
			}
		});
	},
	validatePassReset: function() {
		var errorMssg = [];
		if (!$F('password_1') || !$F('password_2')) {
			errorMssg.push('Please enter matching passwords in both supplied fields.');
		}
		if ($F('password_1') && $F('password_2')) {
			if ($F('password_1') != $F('password_2')) {
				errorMssg.push('The supplied passwords do not match');
			}
		}
		if (errorMssg.length == 0) {
			$('passForm').submit();
		} else {
			var mssg = {
				"header": "There is an error",
				"bodyContent": ""
			}
			mssg.bodyContent += "<ol>";
			$(errorMssg).each(function(mssgAt) {
				mssg.bodyContent += "<li>" + mssgAt + "</li>";
			});
			mssg.bodyContent += "</ol>";
			util.talkbox($H(mssg).toJSON());
		}
	},
	resetPass: function(userName) {
		login.promptLogin('standard');
		document.observe('lightview:opened', login.passwordReset);
		if (userName) {
			(function(){
				if ($('email_reset')) {
					$('email_reset').value = userName;
				}
			}).delay(2);
		}
		return false;
	},
	bounce: function() {
		var currentCount = 10;
		var timer = function() {
			if (currentCount > 1) {
				currentCount--;
				$('log_counter').update(currentCount);
				timer.delay(1);
			} else {
				new Ajax.Request('/login/logout/', {
					onSuccess: function(t) {
						window.location.href = '/';
					}
				});
			}
		}
		timer.delay(1);
	},
	van_login: function(cf_email,cf_pw){
		
		var van_url = '/support/forums/people/';
		var splitName = cf_email.split('@')[0];
		
		new Ajax.Request(van_url, {
			method:'post',
			parameters: {
				PostBackAction : 'Apply',
				ReadTerms : 1,
				AgreeToTerms: 1,
				Email: cf_email,
				Name: splitName,
				NewPassword : cf_pw,
				ConfirmPassword : cf_pw,
				RoleID : 3
			}
			
		});
		
	}
}

document.observe('lightview:hidden',function(){
	if ($('login_cont') && $('login_cont').visible()) {
		$('login_cont').removeClassName('show');
	}
});

// contest for validation

var contest = {
	validateForm: function() {
		var errorFields = [];
		var errorMssg = [];
		var formObj = $('contestForm');
		
		// app name
		if (!$F('app_name')) {
			errorFields.push($('app_name'));
			errorMssg.push('Please enter a name for your application for our records');
		}
		
		// email address field
		if (!$F('email_address')) {
			errorFields.push($('email_address'));
			errorMssg.push('Please enter your email address');
		} else if ($F('email_address') && ($F('email_address').indexOf('@') == -1 || $F('email_address').indexOf('.') == -1)) {
			errorFields.push($('email_address'));
			errorMssg.push('Please enter a valid email address');
		}
		
		// url field
		if (!$F('app_url')) {
			errorFields.push($('app_url'));
			errorMssg.push('Please enter a url where your application can be viewed or downloaded');
		}
		
		// opt in check
		if (!$('opt_in').checked) {
			errorFields.push($('opt_in'));
			errorMssg.push('Please agree to the contest rules and GamePro API Terms of Service');
		}
		
		// build argument object for valiation function
		var argObj = {
			formObj: formObj,
			formFields: errorFields,
			errorMssg: errorMssg,
			successFunction: contest.ajaxSubmit
		}
		// ... and send it
		formValidate.init(argObj);
	},
	ajaxSubmit: function() {
		var thisClass = this;
		new Ajax.Request('/contest/ajax/submission_send/', {
			method: 'post',
			parameters: thisClass.formObj.serialize(),
			onSuccess: function(t) {
				thisClass.formObj.update(t.responseText);
			}
		});
	}
}

// general form validation object
var formValidate = {
	argObj: {},
	init: function(argObj) {
		this.argObj = {};
		this.argObj = argObj;
		if (this.argObj.formFields.length == 0) {
			this.clearLabels();
			this.clearFields();
			this.argObj.successFunction();
		} else {
			this.setLabels();
			this.setFields();
			this.throwError();
		}
	},
	clearLabels: function() {
		this.argObj.formObj.select('label').each(function(itemAt) {
			itemAt.removeClassName('error');
		});
	},
	setLabels: function() {
		this.clearLabels();
		var thisObj = this;
		this.argObj.formFields.each(function(errorAt) {
			thisObj.argObj.formObj.select('label').each(function(itemAt) {
				if (errorAt.id == itemAt.getAttribute("for")) {
					itemAt.addClassName('error');
				}
			});
		});
	},
	clearFields: function() {
		var formArray = [];
		this.argObj.formObj.select('input').each(function(itemAt){
			formArray.push(itemAt);
		});
		this.argObj.formObj.select('select').each(function(itemAt){
			formArray.push(itemAt);
		});
		this.argObj.formObj.select('textarea').each(function(itemAt){
			formArray.push(itemAt);
		});
		formArray.each(function(itemAt) {
			itemAt.removeClassName('error');
		});
	},
	setFields: function() {
		this.clearFields();
		$A(this.argObj.formFields).each(function(itemAt){
			itemAt.addClassName('error');
		});
	},
	throwError: function() {
		var bodyContent = "<ol>";
		this.argObj.errorMssg.each(function(itemAt) {
			bodyContent += "<li>" + itemAt + "</li>";
		});
		bodyContent += "</ol>";
		var mssg = {
			"header": "There is an error.",
			"bodyContent": bodyContent
		}
		util.talkbox($H(mssg).toJSON());
	}
}


// various global utility functions, stuff that gets run onload, etc.
var util =  {
	init: function() {
		util.setMainNav();
		//util.ie6Pwn();
	},
	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'});
		(function(){
			new Effect.Highlight('talkTarget');
		}).delay(.5);
		document.observe('keypress',function(e){
			if (e.keyCode == 27) {
				util.removebox();
			}
		});
		(function(){
			document.observe('click',function(e){
				var currentNode = Event.element(e);
				while(currentNode.parentNode) {
					currentNode = currentNode.parentNode;
					if (currentNode.id == 'talkBox') {
						return false;
					}
				}
				util.removebox();
			});
		}).delay(1);
	},
	removebox: function() {
		document.stopObserving('keypress');
		document.stopObserving('click');
		util.toggleLeader('on');
		new Effect.Fade('talkBox', {duration: .5});
		var removeTimer = window.setTimeout(function(){
			$('talkBox').parentNode.removeChild($('talkBox'));	
		}, 500);
	},
	toggleLeader: function(mode) {
		if (!$('leaderboard')) { return false; }
		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');
	},
	setMainNav: function() {
		if (!Prototype.Browser.IE){ return false;}
		var itemList = [];
		$$('.api-nav')[0].select('.api').each(function(itemAt) {
			itemList.push(itemAt);
		});
		$A(itemList).each(function(itemAt){
		    Event.observe(itemAt,'mouseover',function(e){
				Event.element(e).addClassName('hover');
		    });
		    Event.observe(itemAt,'mouseout',function(e){
		       Event.element(e).removeClassName('hover');
		    });
		});
	}
}

// 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');
  }
}

// dev debug toolz
var _tools = {
	ajaxBug: function(t) {
		var overLay = new Element('div',{
			id: 'bugOverlay',
			style: 'z-index: 1000; padding: 20px; background: #FFF; position: absolute; left: 0; top: 0; width: ' + document.viewport.getWidth() + 'px; height: ' + document.viewport.getHeight() + 'px;'
		}).update(t.responseText);
		overLay.onclick = function() {
			$('bugOverlay').remove();
		}
		$$('body')[0].appendChild(overLay);
	}
}

document.observe('dom:loaded',global.init);