/*
* Commercial Codebase by RETS PRO Development Team.
* Copyright RETS PRO - 2009 - 2020 - All Rights Reserved
* License: https://retspro.com/faq/license/
*/
jQuery(document).ready(function ($)
{
    $('#div_forms').show();

    //$.getScript("http://ajax.aspnetcdn.com/ajax/jquery.validate/1.14.0/jquery.validate.min.js", function(){
    //alert("Script loaded and executed.");
    //});
    //
    // Display form from link inside a popup
    //$('#pop_login, #pop_signup').on('click', function (e)
    $('body').on('click', '#pop_login, #pop_signup', function (e)
    {
	formToFadeOut = $('form#register');
	formtoFadeIn = $('form#login');
	if ($(this).attr('id') == 'pop_signup')
	{
	    formToFadeOut = $('form#login');
	    formtoFadeIn = $('form#register');
	}
	formToFadeOut.fadeOut(500, function ()
	{
	    formtoFadeIn.fadeIn();
	})
	return false;
    });

    // Close popup
    $(document).on('click', '.login_overlay, .close', function ()
    {
	$('form#login, form#register').fadeOut(500, function ()
	{
	    $('.login_overlay').remove();
	});
	return false;
    });

    // Show the login/signup popup on click
    //$('#show_login, #show_signup, .show_login, .show_signup').on('click', function (e)
    $('body').on('click', '#show_login, #show_signup, .show_login, .show_signup', function (e)
    {
	$('body').prepend('<div class="login_overlay"></div>');
	if ($(this).attr('id') == 'show_login' || $(this).hasClass('show_login'))
	{
	    $('form#login').fadeIn(500);
	} else
	{
	    $('form#register').fadeIn(500);
	}
	e.preventDefault();
    });

    // Perform AJAX login/register on form submit
    //$('form#login, form#register').on('submit', function (e)
    $('body').on('submit', 'form#login, form#register', function (e)
    {
	if (!$(this).valid())
	{
	    return false;
	}

	$('p.status', this).show().text('Checking your info...');

	controller = 'UserAuth';
	action = 'login';
	username = $('body form#login #username').val();
	password = $('body form#login #password').val();
	email = '';
	humanname = '';
	security = $('body form#login #security').val();

	if ($(this).attr('id') == 'register')
	{
	    action = 'register';
	    username = $('body #email').val();
	    humanname = $('body #humanname').val();
	    password = $('body #signonpassword').val();
	    email = $('body #email').val();
	    security = $('body #signonsecurity').val();
	}

	ctrl = $(this);
	$.ajax({
	    type: 'POST',
	    dataType: 'json',
	    url: WPR.ajaxurl,
	    data: {// Here is where the wpr vars interface with da form
		'controller': controller,
		'action': action,
		'un': username,
		'humanname': humanname,
		'pw': password,
		'email': email
	    },
	    success: function (data)
	    {
		$('p.status', ctrl).text(data.message);
		if (data.loggedin == true)
		{
		    WprFollowingLogin();
		}
	    },
	    complete: function (xhr, data)
	    {
		var xyz = JSON.parse(xhr.responseText);
		$('p.status', ctrl).text(xyz.message);
		if (xyz.loggedin == true)
		{
		    WprFollowingLogin();
		    //document.location.href = ajax_auth_object.redirecturl;
		}
	    }
	});
	e.preventDefault();
    });

    // Client side form validation
    /*if (jQuery("#register").length)
     jQuery("#register").validate(
     {
     rules:{
     password2:{ equalTo:'#signonpassword'
     }
     }}
     );
     else if (jQuery("#login").length)
     jQuery("#login").validate();*/

    $('.bare-login').on('click', function ()
    {
	WprShowLoginForm();
    });

    $('.free_login_check').on('click', function (e)
    {
	e.preventDefault();
	if (getCookie("free_view_limit_over") == "Yes")
	{
	    WprShowLoginForm();
	} else
	{
	    window.location = this.href;
	}
	return false;
    });
});

function WprFollowingLogin()
{
    jQuery('form#login, form#register').fadeOut(500, function ()
    {
	jQuery('.login_overlay').remove();
    });
    location.reload();
    /*
     * comment by Kishan Kothari
     * date : 24th March 2018
     */
    //WPR.operation(); // need to clarify for this being set by the caller at the time of the login request
    //alert('post login');
}

function WprShowLoginForm()
{
    // alert('fade');
    // jQuery('body').prepend('<div class="login_overlay"></div>');
    // jQuery('form#login').fadeIn(500);

    if (jQuery("body #div_forms").length >= 1)
    {
	jQuery('body').prepend('<div class="login_overlay"></div>');
	jQuery('form#login').fadeIn(500);
    } else
    {
	jQuery.ajax({
	    type: 'POST',
	    dataType: 'HTML',
	    url: WPR.ajaxurl,
	    data: {
		'controller': 'UserAuth',
		'action': 'getform',
	    },
	    success: function (data)
	    {
		//console.log(data);
		jQuery('body').prepend(data);
		jQuery('body').prepend('<div class="login_overlay"></div>');
		jQuery('form#login').fadeIn(500);
	    },
	    complete: function (xhr, data)
	    {

	    }
	});
    }
}

// Facebook login stuff
function statusChangeCallback(response)
{
    console.log('statusChangeCallback');
    console.log(response);
// The response object is returned with a status field that lets the
// app know the current login status of the person.
// Full docs on the response object can be found in the documentation
// for FB.getLoginStatus().
    if (response.status === 'connected')
    {
// Logged into your app and Facebook.
	testAPI();
    } else if (response.status === 'not_authorized')
    {
// The person is logged into Facebook, but not your app.
    } else
    {
// The person is not logged into Facebook, so we're not sure if
// they are logged into this app or not.
    }
}

function testAPI()
{
    console.log('Welcome!  Fetching your information.... ');
    FB.api('/me', {fields: 'email,name'}, function (response)
    {
	var input = {
	    controller: 'UserAuth',
	    action: 'FbLogin',
	    username: response.email,
	    email: response.email,
	    humanname: response.name
	};
	jQuery.getJSON(WPR.ajaxurl, input, function (data)
	{
//console.log('fired');
	    WprFollowingLogin();
	});
	console.log('Successful login for: ' + response.name);
	console.log(response);
    });
}

function checkLoginState()
{
    FB.getLoginStatus(function (response)
    {
	statusChangeCallback(response);
    });
}

function getCookie(cname)
{
    var name = cname + "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++)
    {
	var c = ca[i];
	while (c.charAt(0) == ' ')
	{
	    c = c.substring(1);
	}
	if (c.indexOf(name) == 0)
	{
	    return c.substring(name.length, c.length);
	}
    }
    return "";
}