igpHelper = null;
(function($j) {
	$j.fn.pogoIGPHelper = function(params, options, userMgr) {
	    var myOptions = {
			width : 750,
			height : 400,
			posStyle : "position: relative; ",
			domain : "pogo.com",
			generalCookiePrefix : "com.pogo.",
			initPanel : 'completion',
			resources : {
				"Account.ScreenName" : "Screen name",
				"Account.Password" : "Password",
				"Account.Gender" : "Gender",
				"Account.EmailAddress" : "E-mail address",
				"Account.BirthDate" : "Birth date",
				"Account.Country" : "Country"
			},
			site: 'pogo',
			authenticationLevel: 'guest',
			pageSection: "",
			divShimStyle : false,
			preGameRedirect: false
	    } 
	    $j.extend (true, myOptions, options);
	    var followTheLeader = function(panel) {
			$j("#igpDivShim").offset(panel.offset());
			$j("#igpDivShim").css('display', 'block');
	    }
	    var clearMessages = function() {
			// Hide validation errors so that they do not appear next time.
			$j('#signup-errors').css('display', 'none');
			$j('#signin-errors').css('display', 'none');
			$j("#regSignupform .err").removeClass("err");
	    }
	    
		this.html('<div id="igpParent" style="' + myOptions.posStyle + '"></div>');
		
		igpHelper = new (function () {
		    var endOfGameURL = '/game/igp/end-game-' + ((myOptions.authenticationLevel == 'free' ||  myOptions.authenticationLevel == 'club') ? 'auth' : 'guest')  + '.do';
			this.panels = {
				completion: {url: endOfGameURL, width: 550, height: 395, left: 0, hide: false},
				signUp: {url: '/game/igp/sign-up.do', width: 633, height: 400, hide: true},
				signUpConfirmation: {url: '/game/igp/sign-up-confirmation.do', width: 633, height: 400, hide: true},
				signIn: {url: '/game/igp/sign-in.do', width: 633, height: 400, hide: true}
			};
			this.options = myOptions;
			this.params = params; 
			this.additionalParams = {
				site: this.options.site,
				gameCode: this.options.gameCode,
				authenticationLevel: this.options.authenticationLevel,
				pageSection: this.options.pageSection,
				preGameRedirect: this.options.preGameRedirect
			}; 
			this.currentId = null;
			this.userMgr = userMgr;
			this.loaded = {};
			this.transition = false;
			this.attemptingLogin = false;
			this.attemptingRegister = false;
			if (this.options.divShimStyle) {
				$j('#igpParent').append('<iframe id="igpDivShim" src="about:blank" style="border: none; position: absolute;  z-index: 20;' + this.options.divShimStyle + '"></iframe>');
			}

			this.setPanel = function(id) {
				if (id == this.currentId || this.transition) {
					return;
				}
				
				clearMessages();
				
				// Hide the current panel if it's hideable (i.e.: not the
				// "completion" panel).
				if (this.currentId != null) {
					if (this.panels[this.currentId]['hide'] || this.options.divShimStyle) {
						$j('#' + this.currentId).css('display', 'none');
					}
				}
				
				
				if (typeof this.options.preChangePanelCallback == 'function') 
					this.options.preChangePanelCallback(this.currentId, id);
				
				// If the panel was already loaded, display the div.
				if (typeof this.loaded[id] != 'undefined') {				
					if (this.panels[id]['hide'] || this.options.divShimStyle)  {
						var panel = $j('#' + id);
						panel.css('display', 'block');
					    if (this.options.divShimStyle) {
				    		$j("#igpDivShim").css('display', this.panels[id]['hide'] ? 'none' : 'block');
					    }
					}
					this.currentId = id;
					return;
				}
				
				var delegateThis = this;
				var url = '';
				if (typeof this.options.protocol != 'undefined') url += this.options.protocol; 
				if (typeof this.options.host != 'undefined') url += this.options.host;
				url +=  this.panels[id]['url'] + '?site=' + this.options.site + '&game=' + this.options.gameCode;
				this.transition = true;
				$j.ajax({
					url: url,
					context: document.body,
					dataType: "html",
					success: function(result){
						for (var key in delegateThis.params) {
							result = result.replace(new RegExp('%' + key + '%', 'g'), delegateThis.params[key]);
						}
						for (var key in delegateThis.additionalParams) {
							result = result.replace(new RegExp('%' + key + '%', 'g'), delegateThis.additionalParams[key]);
						}
						try {
							var zIndex = delegateThis.options.divShimStyle ? "50" : "auto";
							$j('#igpParent').hide();  // before any appending is done, hide the parent container (prevents user from seeing incomplete pages)
                            if (typeof delegateThis.panels[id]['left'] != 'undefined') {
								$j('#igpParent').append('<div id="' + id + '" style="z-index: ' + zIndex + '; position: absolute; top: 0px; left: ' + delegateThis.panels[id]['left'] + 'px; ">' +  result + '</div>');
							} else if (delegateThis.options.divShimStyle) {
								var left = 33;
								var top = 0;
								$j('#igpParent').append('<div id="' + id + '" style="z-index: ' + zIndex + '; position: absolute; top: ' + top + 'px; left: ' + left + 'px; ">' +  result + '</div>');
							} else {
								$j('#igpParent').append('<div id="' + id + '" style="z-index: ' + zIndex + '; margin: 0 auto; ">' +  result + '</div>');
							}
                            $j('#igpParent').show();  // once page is completed show it
						    if (delegateThis.options.divShimStyle) {
						    	if (delegateThis.panels[id]['hide']) 
						    		$j("#igpDivShim").css('display', 'none');
						    	else followTheLeader($j('#' + id));

								// Remove features known to break
								$j("#" + id + " #lightreg").css("background-color", "white");
								$j("#igp").css("border-radius", "0");
						    }
						}
						finally {
							delegateThis.currentId = id;
							delegateThis.loaded[id] = true;
							delegateThis.transition = false;
						}
					},
					error: function(jqXHR, textStatus, errorThrown) {
						alert(textStatus);
						delegateThis.transition = false;
					}
				});	
			}

			this.close = function() {
				$j("#igpParent").remove();
				if (typeof this.options.closeCallback == 'function') this.options.closeCallback(); 
			}
			this.closeModal = function() {
				if (this.options.initPanel=='completion') this.setPanel('completion');
				else this.close(); 
			}
			this.showHighScores = function() {
				if (this.canShowHighScores()) this.options.showHighScoresCallback(); 
			}
			this.canShowHighScores = function () {
				return typeof this.options.showHighScoresCallback == 'function';
			}
			this.login = function() {
                this.doLogin($j('#l_screenname').val(),$j('#l_password').val(),typeof ($j('#l_remember_password').attr("checked")) != 'undefined', false);
			}
			this.doLogin = function(username, password, remember, signUpFlow) {
                // skip the login attempt if we are currently attempting one
                if ( this.attemptingLogin ) {
                    return;
                }

                if (!username || !password) {
                    $j('#signin-errors-list').empty();
                    var errHtml = "<ul>";
                    if (!username) errHtml += "<li><strong>Please enter your screen name</strong></li>";
                    if (!password) errHtml += "<li><strong>Please enter your password</strong></li>";
                    errHtml += "</ul>";
                    $j('#signin-errors-list').append(errHtml);
                    $j('#signin-errors').css('display', 'block');
                    return;
                }

                if (typeof this.userMgr == 'undefined' || typeof this.userMgr.signIn == 'undefined') {
                    alert('sign-in library not found');
                    return;
                }

                var delegateThis = this;
                this.attemptingLogin = true;
                this.userMgr.signIn({
                    screenname : username,
                    password : password,
                    remember : remember,
                    success : function(lKey, rememberCookie){
                        try {
                            var domain = delegateThis.options.domain;
                            document.cookie = delegateThis.options.generalCookiePrefix + 'lkey=' + escape( lKey ) + ';path=/;domain=' + domain;
                            if (remember) {
                                document.cookie = rememberCookie + ';domain=' + domain;
                            }
                            if (signUpFlow) {
                                delegateThis.additionalParams.screenname = username;
                                delegateThis.setPanel('signUpConfirmation');
                            } else {
                                delegateThis.fireLoginEvent(delegateThis.options.gameCode);
                                var redirectURL = "/action/pogo/backtogamepopup.do?preGameRedirect=";
                                redirectURL += (delegateThis.options.preGameRedirect) ? "true" : "false"
                                if (typeof delegateThis.options.pageSection != 'undefined') {
                                    redirectURL += "&pageSection=";
                                    redirectURL += delegateThis.options.pageSection;
                                }
                                redirectURL += "&game=" + delegateThis.options.gameCode;
                                window.top.location = redirectURL;
                            }
                        }
                        finally {
                            delegateThis.attemptingLogin = false;
                        }
                    },
                    error : function(err){
                        $j('#signin-errors-list').empty();
                        var errHtml = "<ul>";
                        for (errIdx = 0; errIdx < err.length; ++errIdx) {
                            var detail = err[errIdx];
                            errHtml += "<li><strong>" + detail + "</strong></li>";
                        }
                        errHtml += "</ul>";
                        $j('#signin-errors-list').append(errHtml);
                        $j('#signin-errors').css('display', 'block');
                        delegateThis.attemptingLogin = false;
                    }
                });
			}
			this.fireLoginEvent = function() {
				if(typeof OmnitureCustomEvent=='function') {
			         var options = {'eVar3' :  this.options.gameCode};
			         if (typeof this.options.pageSection != 'undefined') {
			        	 options['eVar18'] = this.options.pageSection;
			         }
				     OmnitureCustomEvent("IGP Login modal", 'event36', options);
				}
			}
			var regValidationFields = { "Account.ScreenName" : "s_screenname", "Account.EmailAddress" : "s_email",
				"Account.Password" : "s_password", "Account.BirthDate" : "s_year", "Account.Country" : "s_country",
				 "Account.PasswordConfirm" : "s_password_confirm"};			
			this.register = function() {
                // skip the register attempt if we are currently attempting one
                if ( this.attemptingRegister ) {
                    return;
                }

				if (typeof this.userMgr == 'undefined' || typeof this.userMgr.signUp == 'undefined') {
					alert('sign-up library not found');
					return;
				}
				var delegateThis = this;
                this.attemptingRegister = true;
				var preLoginErr = { };
				var displayErrors = function(err) {
				    $j.extend (true, err, preLoginErr);
					$j('#signup-errors-list').empty();
					$j("#regSignupform .err").removeClass("err");
					var errHtml = "<ul>";
					for (key in delegateThis.options.resources) {
						if (!err[key]) continue;
						var error = err[key];							
						if (key == 'Account.BirthDate' && error.reason.indexOf('too young') > 0) {
							errHtml += "<li>Sorry, you haven't met the criteria for registration.</li>";
							delete err[key];
							continue;
						}
						$j("#" + regValidationFields[key]).addClass("err");
						if ("Account.Password" === key) 
							$j("#" + regValidationFields["Account.PasswordConfirm"]).addClass("err");
						errHtml += "<li><b>";
						errHtml += delegateThis.options.resources[key] + "</b>: ";
						errHtml += error.reason;
						if (error.suggestedScreenNames) {
							errHtml += ". Choose from one of our suggestions, or enter a different screen name.<ul>";
							for (nameIdx = 0; nameIdx < error.suggestedScreenNames.length; ++nameIdx) {
								errHtml += "<li>" + error.suggestedScreenNames[nameIdx] + "</li>";
							}
							errHtml += "</ul>";
						}
						errHtml += "</li>";
						delete err[key];
					} 
					for (key in err) {
						$j("#" + regValidationFields[key]).addClass("err");
						if ("Account.Password" === key) 
							$j("#" + regValidationFields["Account.PasswordConfirm"]).addClass("err");
						errHtml += "<li>" + err[key].reason + "</li>";
					}
					errHtml += "</ul>";
					$j('#signup-errors-list').html(errHtml);
					$j('#signup-errors').css('display', 'block');

                    delegateThis.attemptingRegister = false; // if an error is displayed, the registering attempt failed; release flag so that user may try again
				}
				var password = $j('#s_password').val();
				var passwordConfirm = $j('#s_password_confirm').val();
				var gender = $j(':checked[name="s_gender"]').val()
				var screenname = $j('#s_screenname').val();
				var email = $j('#s_email').val();
				var country = $j('#s_country').val();
				if (!gender) preLoginErr["Account.Gender"] = { reason : "Please select a gender" };
				if (password && password != passwordConfirm) preLoginErr["Account.Password"] = { reason : "Passwords do not match, please enter re-enter the password for confirmation"};
				if (country=='---') preLoginErr["Account.Country"] = { reason : "Please select a country" };
				if (screenname && password && email && !$j.isEmptyObject(preLoginErr)) {
					displayErrors({}); 
					return;
				}
			    var info = {
			    	password : password,
					screenname : screenname,
					gender : gender,
					day : $j('#s_day').val(),
					month : $j('#s_month').val(),
					year : $j('#s_year').val(),
					country : country,
					email : email,
					guestReg : this.params.guestReg,
					roomKey : this.params.roomKey,
					success : function(){
                        try {
						    delegateThis.doLogin(screenname, password, false, true);
                        }
                        finally {
                            delegateThis.attemptingRegister = false; // attempt succeeded, release flag
                        }
					},
					error : displayErrors
				}
				this.userMgr.signUp(info);
			}
		})();
		igpHelper.setPanel(myOptions.initPanel);
		return igpHelper;
	}
})(jQuery);


