

if (jQuery) (function(jQuery) {
    this.isSlot = false;
    jQuery.extend(jQuery.ark, { fbRegist: function() { } });
    jQuery.extend(jQuery.ark.fbRegist, {
        pageUrl: jQuery.ark.SiteBaseUrl + '/popups/FBRegistrPopups.aspx',
        defaultPageUrl: jQuery.ark.SiteBaseUrl + '/default.aspx',
        BoxPopCloseWithAction: null,
        cancel_event: function() {
            jQuery('#modalWindow_fb').jqmHide();
            showPopUpRegisterSuccess();
        },
        cancel_nonRegistr: function() {
            jQuery('#modalWindow_fb').jqmHide();
        },
        cancel_event_and_logout: function() {
            jQuery('#modalWindow_fb').jqmHide();
            if(typeof FB != "undefined"){
                FB.logout();
            }
        },
        cancel_event_avatar: function (){
            jQuery('#modalWindow_fb').jqmHide();
        },
        endLoad: function (){
			HideUniversalTransition('modalWindow_fb');
        },
        subm: function (){
            top.frames['Gdgfbpopup_00'].Submit();
        }
    });
})(jQuery);


if (jQuery) (function(jQuery) {
	//jQuery.extend(jQuery.ark, { tmpl: function() { } });
	jQuery.extend(jQuery.ark.tmpl, {
		popupRegister: '<div id="registerControl">\
	\
<script type="text/javascript">\
    initFB();\
</script>\
\
<script type="text/javascript" type="text/javascript">\
    jQuery(document).ready(function() {\
        cmSetClientID("90302778", false, "coremetrics.arkadium.com");cmSetProduction();\
cmCreatePageviewTag("Registration|Start", "Registration");\
    });\
</script>\
\
<input type="hidden" value="" name="registerControl$SuccessAction" />\
<input type="hidden" value="popup-screen" name="registerControl$RegType" />\
<div class="fb_register_control coll">\
<div id="registerControl_fBBoxLoginControl_FbLogin">\
		\
<div class="fb coll">\
    <div class="fb_top_bg coll">Sign in using Facebook Connect:</div>\
    <div class="fb_m_bg coll">\
        \
        <a href="#" onclick="facebooklogin(function(){checkFBAuth();}); return false;" class="fb_connect_button coll"></a>\
    </div>\
    <div class="fb_bottom_bg coll"></div>\
</div>\
\
	</div>\
</div>\
<div class="endCol"></div>\
<div class="registrPage_center_block">\
	<div class="registrPage_questions_box endCol">\
		<div class="registrPage_questions">Desired Username:</div>\
		<div style="float: left;">\
			<input name="registerControl$Name" type="text" id="registerControl_Name" class="registrPage_center_textbox" maxlength="100" tabindex="21" onchange="CheckName(this, jQuery.ark.SiteBaseUrl, this.value)" />\
		</div>\
		<div id="registerControl_valName"></div>\
	</div>\
	<div class="registrPage_questions_box endCol">\
		<div class="registrPage_questions">Password:</div>\
		<div style="float: left;">\
			<input name="registerControl$Password" type="password" id="registerControl_Password" class="registrPage_center_textbox" maxlength="50" tabindex="22" onkeyup="registerControl_ValidatePassword();" onchange="CheckPassword(this, jQuery.ark.SiteBaseUrl, this.value)" />\
		</div>\
		<div id="registerControl_valPassword">\
		</div>\
	</div>\
	<div class="registrPage_questions_box endCol">\
		<div class="registrPage_questions">Re-enter Password:</div>\
		<div style="float: left;">\
			<input name="registerControl$PasswordRetype" type="password" id="registerControl_PasswordRetype" class="registrPage_center_textbox" maxlength="50" tabindex="23" onkeyup="registerControl_ValidatePassword();" />\
		</div>\
		<div id="registerControl_valPasswordRetype"> </div>\
	</div>\
	<div class="registrPage_questions_box endCol">\
		<div class="registrPage_questions">Email Address:</div>\
		<div style="float: left;">\
			<input name="registerControl$Email" type="text" id="registerControl_Email" class="registrPage_center_textbox" maxlength="100" tabindex="24" onchange="CheckEmail(this, jQuery.ark.SiteBaseUrl, this.value)" />\
		</div>\
		<div id="registerControl_valEmail"> </div>\
	</div>\
	<div class="registrPage_questions_box endCol">\
		<div class="registrPage_questions">Are you 18 or older?</div>\
		<div style="float: left; height: 30px;">\
			<input type="radio" name="registerControl$Is18Older" value="true" checked="checked"\
				tabindex="25" />Yes\
			<input type="radio" name="registerControl$Is18Older" value="false" tabindex="26" />No\
		</div>\
	</div>\
	<div class="registrPage_questions_box endCol">\
		<div class="registrPage_questions">GDG newsletter</div>\
		<div style="float: left; height: 30px;">\
			<input type="radio" name="registerControl$IsNewsLetterSubscribed" value="true"\
				checked="checked" tabindex="27" />Yes\
			<input type="radio" name="registerControl$IsNewsLetterSubscribed" value="false"\
				tabindex="28" />No\
		</div>\
	</div>\
	<div class="registrPage_lock_caption endCol coll">\
		<div id="registerControl_recaptcha" name="registerControl_recaptcha" style="float: left; height: 110px;"> </div>\
		\
	</div>\
	<div class="registrPage_questions_box endCol">\
		<div id="registerControl_valRecaptcha"></div>\
	</div>\
</div>\
<div class="registrPage_button">\
	<input type="button" class="registrPage_submit_but" onclick="javascript:registerControl.LoadDiv(true);"\
		onmouseover="submitHov.Set(this);" onmouseout="submitHov.Reset(this);"\
		tabindex="30" />\
	\
</div>\
<div class="registrPage_questionsB endCol">\
	By clicking SUBMIT you are agreeing to the GDG <a href="http://www.greatdaygames.com/HelpPages/Conditions.aspx" target="_blank">\
		<font style="text-decoration: underline; cursor: pointer; color: #999999;">terms and conditions</font></a>.\
</div>\
<div class="home_WebGame_sep_long" style="clear: both; margin-bottom: 4px; margin-top: 23px; float: left;"> </div>\
</div>'
	});
})(jQuery);


	var registerControl = new AjaxPanelClass('http://www.greatdaygames.com/ajaxServices/Register.aspx', 'registerControl');
	var submitHov = new HoverManipulator('registrPage_submit_but_hov', 'registrPage_submit_but');
	var cancelHov = new HoverManipulator('registrPage_cancel_but_hov', 'registrPage_cancel_but');
	function registerControl_ValidatePassword() { ValidatePassword('registerControl_Password', 'registerControl_PasswordRetype'); }

function RegisterProcessor()
{
    this.isShowStandardRegistrationSuccessDialog = true;
}

function OpenPopupFBRegister()
{
    ClosePopup();
	jQuery.ark.dialog.open('arkDialog', 'popupFBRegisterControl',	'FB Registration on Great Day Games!',
		tmpl('<iframe name="Gdgfbpopup_00" onload="jQuery.ark.fbRegist.endLoad()" id="popupFBRegisterControlIframe" src="http://www.greatdaygames.com/popups/FBRegistrPopups.aspx" scrolling="no" frameborder="0" allowtransparency="true" style="width:576px; height:277px;"></iframe>', {})
	);
}

var registerProcessor = new RegisterProcessor();

function closeLoginPopUpDialog(){
    jQuery.ark.dialog.close('popupLogin_popupDialog');
    
}

function OpenPopupRegister(isSpecPopUp, addStyle, contentStyle)
{
    registerProcessor.isShowStandardRegistrationSuccessDialog = true;
    if (isSpecPopUp == 'undefined'){
        isSpecPopUp = false;
    }
    jQuery.ark.dialog.open('arkDialog', 'popupRegisterControl',
		'Great Day Games Membership is Easy and Free!',
		tmpl('popupRegister', {}),
        closeLoginPopUpDialog(),
        isSpecPopUp,
        addStyle,
        contentStyle
        
	);
	GenerateRecaptcha('registerControl_recaptcha', 29);
	document.getElementById('registerControl_Name').focus();
}
function OpenGameEndPopupRegister()
{
    registerProcessor.isShowStandardRegistrationSuccessDialog = true;
	jQuery.ark.dialog.open('arkDialog', 'popupRegisterControl',
		'Great Day Games Membership is Easy and Free!',
		tmpl('popupRegister', {})
	);
	GenerateRecaptcha('registerControl_recaptcha', 29);
	document.getElementById('registerControl_Name').focus();
}

function OpenMonetizPopupRegister()
{
    registerProcessor.isShowStandardRegistrationSuccessDialog = false;
	jQuery.ark.dialog.open('arkDialog', 'popupRegisterControl',
		'Great Day Games Membership is Easy and Free!',
		tmpl('popupRegister', {})
	);
	GenerateRecaptcha('registerControl_recaptcha', 29);
	document.getElementById('registerControl_Name').focus();
}

function HoverManipulator(hoverStyleName, noHoverStyleName)
{
	this.hoverStyleName = hoverStyleName;
	this.noHoverStyleName = noHoverStyleName;
	this.Set = function(control) { control.className = this.hoverStyleName; };
	this.Reset = function(control) { control.className = this.noHoverStyleName; };
}
function CheckName(control, baseUrl, args)
{
	jQuery.ajax({
		type: 'POST',
		async: true,
		timeout: 1000,
		contentType: 'application/json',
		dataType: 'json',
		url:baseUrl + '/ajaxServices/Register.aspx/CheckName',
		data: '{\'name\':\'' + args + '\'}',
		success: function(result) {
			var lastDiv = jQuery(jQuery(control)).parent();
			lastDiv.nextAll().remove();
			if (result.d & 2)
			    resultDiv = validErrorDiv('Taken');
			else if (result.d == 3)
			    resultDiv = validErrorDiv('Incorrect');
			else if (result.d & 4)
			    resultDiv = validErrorDiv('Profanity');
			else if (result.d & 8)
			    resultDiv = validErrorDiv('Incorrect');
			else if (result.d & 32)
			    resultDiv = validErrorDiv('Empty');
			else if (result.d & 128)
			    resultDiv = validErrorDiv('Too short');
			else
			    resultDiv = validSuccessDiv('OK');
			lastDiv.after(resultDiv);
		}
	});
}
function CheckPassword(control, baseUrl, args)
{
	jQuery.ajax({
		type: 'POST',
		async: true,
		timeout: 1000,
		contentType: 'application/json',
		dataType: 'json',
		url:baseUrl + '/ajaxServices/Register.aspx/CheckPassword',
		data: '{\'password\':\'' + args + '\'}',
		success: function(result) {
			var lastDiv = jQuery(jQuery(control)).parent();
			lastDiv.nextAll().remove();
			switch (result.d)
			{
				case 0:
					resultDiv = validSuccessDiv('OK');
					break;
				case 1:
					resultDiv = validErrorDiv('Incorrect');
					break;
				default:
					resultDiv = validErrorDiv('Error');
					break;
			}
			lastDiv.after(resultDiv);
		}
	});
}
function CheckEmail(control,baseUrl, args) {
	var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
	var lastDiv = jQuery(jQuery(control)).parent();
	lastDiv.nextAll().remove();
	if (args != '')
	{
		var resultDiv
		if (reg.test(args) == false)
		{
			resultDiv = validErrorDiv('Invalid');
			lastDiv.after(resultDiv);
		}
		else
		{
			jQuery.ajax({
				type: 'POST',
				async: true,
				timeout: 1000,
				contentType: 'application/json',
				dataType: 'json',
				url:baseUrl + '/ajaxServices/Register.aspx/CheckEmail',
				data: '{\'email\':\'' + args + '\'}',
				success: function(result) {
					var lastDiv = jQuery(jQuery(control)).parent();
					lastDiv.nextAll().remove();
					if (result.d & 1)
					    resultDiv = validErrorDiv('Taken');
					else if (result.d & 16)
					    resultDiv = validErrorDiv('Incorrect');
					else if (result.d & 64)
					    resultDiv = validErrorDiv('Empty');
					else
					    resultDiv = validSuccessDiv('OK');
			        lastDiv.after(resultDiv);
					//var resultDiv = (result.d == false ? validSuccessDiv('OK') : validErrorDiv('Taken'))
					//lastDiv.after(resultDiv);
				}
			});
		}
	}
}
function ValidateEmail(control,address)
{
	var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
	var lastDiv = jQuery(jQuery(control)).parent();
	lastDiv.nextAll().remove();
	if(address != '')
	{
		var result = (reg.test(address) == true ? validSuccessDiv('OK') : validErrorDiv('Invalid'))
		lastDiv.after(result);
	}
}

function validSuccessDiv(text)
{
	return validDiv(text, 'validGreenS', 'registrPage_valid_green');
}
function validErrorDiv(text)
{
	return validDiv(text, 'validRedS', 'registrPage_valid_red');
}
function validDiv(text, img, cssClass)
{
	return '<span class="coll"><div class="' + cssClass + '"><img src="http://gdgfiles.arkadium.com/static/img/registration/' + img + '.png" />' + text + '</div></span>';
}
function ValidatePassword(password, passwordRetype)
{
	if (typeof(password) == 'string') { password = document.getElementsByName(password)[0]; }
	if (typeof(passwordRetype) == 'string') { passwordRetype = document.getElementsByName(passwordRetype)[0]; }
	var lastDiv = jQuery(jQuery(passwordRetype)).parent();
	lastDiv.nextAll().remove();
	
	if(!password){return;}
	if(!passwordRetype){return;}
	
	if ((password.value != '') && (passwordRetype.value != ''))
	{
		var result = (password.value == passwordRetype.value ? validSuccessDiv('Match') : validErrorDiv('Mismatch'))
		lastDiv.after(result);
	}
}

var redirectUrl;

function MyProfileFunctionality() {
    var profileUrl = 'http://www.greatdaygames.com/PersonProfile.aspx';
    FB.getLoginStatus(function(response) {
         if (response.authResponse) {
            document.location = profileUrl;
        }
        else {
           
        }
    });
}

function facebooklogin(callbackfunction) {
    ClosePopup();
 
    try{
        FB.getLoginStatus(function(response) {
          
          if (response.authResponse) {
            
            if (jQuery.isFunction(callbackfunction)) {
                    callbackfunction();
                }
            }
            else {
                FB.login(function(response) {
                    
                    if (response.authResponse) {
                        if (jQuery.isFunction(callbackfunction)) {
                            callbackfunction();
                        }
                    }
                },
                {
                    scope: 'email, user_about_me, user_birthday, publish_stream'
                });
                return false;
            }
        },
        {
            scope: 'email, user_about_me, user_birthday, publish_stream'
        });
    }
    catch(err){
         console.log("facebooklogin err" + err);
    }

 }

function GetAuthAfterAuthorisation(){
    jQuery.ark.dialog.close('popupFBRegisterControl')
    jQuery(document).ready(function (){
            facebooklogin(function(){checkFBAuth();});
    });
}

function RedirectTo(relativePathWithoutFirstSlash) {
    var baseurl = 'http://www.greatdaygames.com/';
    document.location = baseurl + relativePathWithoutFirstSlash;
}

function changeVisibleSettingsParam(stat)
{
    var GDGAndSocialAuth = jQuery("#GDGAndSocialAuth");
    var GDGAndSocialDontAuth = jQuery("#GDGAndSocialDontAuth");

    if(typeof GDGAndSocialDontAuth != "undefined" 
                && GDGAndSocialDontAuth != null
                && typeof GDGAndSocialAuth != "undefined" 
                && GDGAndSocialAuth != null 
                )
    {
        if (stat == "auth") {
            GDGAndSocialDontAuth.hide();
            GDGAndSocialAuth.show();
        } 
        else 
        {
            jQuery("#GDGAndSocialAuth").hide();
            jQuery("#GDGAndSocialDontAuth").show();
        }
    }
}

function newCheckFBAuth(isUpdate){
    
    
    var url = jQuery.ark.SiteBaseUrl + "/ajaxServices/FB/FBAuthorization.aspx";
	jQuery.post(
		url, 
        {
            "isUpdate":isUpdate
        },
		function(data) {

            data = (data.replace("\r\n", ""));
           
		    if (data == "0") {
                
                OpenPopupFBRegister();
		    }
            else if(data == "4"){
                
                jQuery.ark.dialog.ShowOKDialog('ShowDialogPopup', "",  '<div style="display:inline;" class="PopUp_BlueText">Your GDG Account has been linked to your Facebook Account.<br /><br /></div>', function(){MyfblogInEvent();});
            }
            else if(data == "3"){
                
                ConnectMyFacebook();
            }
            else if(data == "2"){
                
                jQuery.ark.dialog.open('arkDialog', 'popupFBRegisterControl',	'FB Registration on Great Day Games!', tmpl('<div style="display:inline;" class="PopUp_BlueText">This Account is Already connected to "Facebook" Users First and Last Name</div><br /><input type="button" onclick="LogIntoFBasaDifferentUser();" class="fb_diff_use" /><br /><a href="#" class="forgot coll" style="margin:0px 0px 5px 33px; height:40px;" onclick="ConnectMyGDGAccountWithFacebook();">Connect my GDG account with “Facebook User name of current request.”</a>', {}));
            }
            else if(data == "5"){
                window.location.reload();
            }
            else if(data == "1"
            || data == "1" ){
            
                
                if (typeof FillUserAfterLogin == "function") {
                    FillUserAfterLogin();
                }
                MyfblogInEvent();
			    //window.location.reload();             
            }
	    }
	);
}

function ConnectMyFacebook()
{
    
    jQuery.ark.dialog.close('popupFBRegisterControl');
    jQuery(document).ready(function (){
        var message = '<div class="coll new_popup_text">This FB ID is already in our DB but belongs to the other user.<br />Logout this GDG USER And Login FB USER?</div><div class="endCol"></div>';
        var caption = '';
        var dialogDivId = 'arkOkCancelDialog';
        var callbackClose = jQuery.ark.dialog.jsCallClose(dialogDivId);
        var okAction = 'FbRelogin()';
        var cancelAction = jQuery.ark.dialog.jsCallClose(dialogDivId);
        jQuery.ark.dialog.ShowOKCancelDialog(dialogDivId, caption, message, okAction, cancelAction);
    });
    
}

function FbRelogin(){
    jQuery.ark.dialog.close('arkOkCancelDialog');
    facebooklogin(function(){newCheckFBAuth(true);});
    console.log("End FbRelogin");
}

function ConnectMyGDGAccountWithFacebook()
{
    
    jQuery.ark.dialog.close('popupFBRegisterControl');
    jQuery(document).ready(function (){
        var message = '<div class="coll new_popup_text">Are you sure you want to connect “GDG User”<br />to “First and Last Name of new FBUID.” <br />This will overwrite your identity as “First and Last Name of existing FBUID in DB”?</div><br />';
        var caption = '';
        var dialogDivId = 'arkOkCancelDialog';
        var callbackClose = jQuery.ark.dialog.jsCallClose(dialogDivId);
        var okAction = 'newCheckFBAuth(true); jQuery.ark.dialog.close("arkOkCancelDialog")';
        var cancelAction = jQuery.ark.dialog.jsCallClose(dialogDivId);
        jQuery.ark.dialog.ShowOKCancelDialog(dialogDivId, caption, message, okAction, cancelAction);
    });
    
}

function LogIntoFBasaDifferentUser (){
    try{
        if (typeof FB != "undefined") {
            if (FB.getAuthResponse() != null) {
                FB.logout(function (response) {
                    GetAuthAfterAuthorisation();
                });
            } else {
                console.log("LogIntoFBasaDifferentUser FB.getAuthResponse() != null else");
            }
        } else {
            console.log("LogIntoFBasaDifferentUser else");
        }
    }
    catch(err){
         console.log("LogIntoFBasaDifferentUser err" + err);
    }
}

function MyfblogInEvent(){
    jQuery(document).ready(function (){
        changeVisibleSettingsParam("auth");
        jQuery("#fb_login_click").hide();
        jQuery("#fb_invite_box_0").show();
    });
}

function MyfblogOutEvent(){
    jQuery(document).ready(function (){
        changeVisibleSettingsParam("out");
        jQuery("#fb_login_click").show();
        jQuery("#fb_invite_box_0").hide();
    });
}

function checkFBAuth() {
   newCheckFBAuth();
}

function logOutFB(data) {
    DoAjaxLogout();
} 

function initFB (){
    jQuery(document).ready(function (){
         FB.init({
            appId: '154265827951897',
            status: true,
            cookie: true,
            xfbml: true,
            oauth: true
        });
    });
}

function redirectToPersonalPage()
{
   if(window.location.pathname.indexOf("register") != -1){
        EditProfileAction();
   }
}

function SendVerificationEmail()
{
    jQuery.ark.dialog.close('__Page_registerDialog');

	var caption = 'Email Verification';
	jQuery.ajax({
			type: 'POST',
			url: 'http://www.greatdaygames.com/ajaxServices/VerifyEmail.asmx/Send',
			data: '{}',
			contentType: 'application/json; charset=utf-8',
			dataType: 'json',
			success: function(data)
				{
					if (data && data.d == false)
					{
                        jQuery.ark.dialog.ShowOKDialog('ShowDialogPopupEmailVerify', caption, '<div style="display:inline;" class="PopUp_BlueText">Was not sent successfully (no success)<br /><br /></div>');
					}
					else
					{
                        jQuery.ark.dialog.ShowOKDialog('ShowDialogPopupEmailVerify', caption, '<div style="display:inline;" class="PopUp_BlueText">Your email verification request was submitted successfully.<br /><br /></div>', redirectToPersonalPage);
					}
				},
			error: function(request) { ShowDialogPopup(caption, 'Was not sent successfully (error)'); }
		});
	}

    function DisconnectFBUser() {
        var url = jQuery.ark.SiteBaseUrl + "/ajaxServices/FB/FB.aspx";
        jQuery.post(
				url,
				{
				    "disconnect": "+"
				},
				function (data) {
                    if(typeof data != "undefined"){
                        if(data == 3){
                            MyfblogOutEvent();
                            jQuery.ark.dialog.ShowOKDialog('ShowDialogPopup', "",  '<div style="display:inline;" class="PopUp_BlueText">All of your Facebook information has been removed from your GDG account,<br />including your profile photo.<br />You can reconnect your account to Facebook at any time.<br /><br /></div>', function(){window.location.reload();});
                        }
                        else if(data == 2){
                            DoAjaxLogout();
                        }
                        else if(data == 0){
                            jQuery.ark.dialog.ShowOKDialog('ShowDialogPopup', "",  '<div style="display:inline;" class="PopUp_BlueText">Unable to delete FB user<br /><br /></div>');
                        }
                    }
				}
			);
    }

    function ClosePopup(){
        popupLogin_cancelClick();
        jQuery.ark.dialog.close('popupRegisterControl');
        if (isSlot != 'undefined'){
            if (isSlot == true){
                HideAllDiv();
                jQuery("#dLoginLock").hide(); 
                jQuery("#dTCLock").hide();
            }
        }
    }

    function showPopUpRegisterSuccess() {
        cmSetClientID("90302778", false, "coremetrics.arkadium.com");cmSetProduction();
cmCreatePageviewTag("Registration|Complete", "Registration");
        if (this.isGame == true){
        prerollStartTC();
    }
	    var dialogDivId = '__Page_registerDialog';
	    var caption = 'Thank you for registering with Great Day Games!';
	    var content = tmpl('arkDialogRegistrationSuccess', {
		    ButtonID: jQuery.ark.dialog.defaultButtonId,
		    RegustrationBonus: '850',
		    EmailVerificationBonus: '1,000',
		    MouseOverClass: "'PopUp_Login_btn_hov';",
		    MouseOutClass: "'PopUp_Login_btn';",
            MouseOverSendEmailClass: "'settings_SendVerificationEmailBTNHover';",
            MouseOutSendEmailClass: "'settings_SendVerificationEmailBTN';",
            MouseOverPlayGamesClass: "'settings_PlayGamesBTNHover';",
            MouseOutPlayGamesClass: "'settings_PlayGamesBTN';",
            MouseOverEditProfileClass: "'settings_EditProfileBTNHover';",
            MouseOutEditProfileClass: "'settings_EditProfileBTN';"
	    });
	    jQuery.ark.dialog.open('arkDialog', dialogDivId, caption, content);
	    document.getElementById(jQuery.ark.dialog.defaultButtonId).focus();
    }

   
