/*
* 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 ($)
{
    //alert(WPR.userFavorites[0]);
    // Sets up the account page
    if (typeof favsTemplate != 'undefined')
    {
	jQuery.post(WPR.ajaxurl,
		{
		    controller: 'AjaxFavs',
		    action: 'GetFavsTemplated',
		    template: favsTemplate
		},
		function (data)
		{
		    if (data)
		    {
			data = JSON.parse(data);
		    }
		    if (!data.objectContents)
		    {
			jQuery('#favorites_list').html('<div>You have not saved any properties</div>');
		    } else
		    {
			jQuery('#favorites_list').html(data.objectContents);
		    }
		    jQuery('#favorites_list').removeClass('async-list');
		})
    }

    if (typeof searchTemplate != 'undefined')
    {
	jQuery.post(WPR.ajaxurl,
		{
		    controller: 'System',
		    action: 'GetSavedSearches',
		    template: searchTemplate
		},
		function (data)
		{
		    if (data)
		    {
			data = JSON.parse(data);
		    }
		    if (!data.objectContents)
		    {
			jQuery('#searches_list').html('<div>You have not saved any properties</div>');
		    } else
		    {
			jQuery('#searches_list').html(data.objectContents);
		    }
		    jQuery('#searches_list').removeClass('async-list');
		})
    }

    WPR.swapClass = function (el, remclass, newclass)
    {
	$(el).removeClass(remclass);
	$(el).addClass(newclass);
    }

    $.each(WPR.userFavorites, function (i, mls)
    {
	var favTarget = 'rpx_mls_' + mls;
	var newFavTarget = 'fav_' + mls;
	var detailsFavTgt = 'favpage_' + mls;
	if ($("div[data-mls='" + mls + "']").length)
	{
	    //alert('found');
	    WPR.swapClass($("[data-mls='" + mls + "']").find('.icon-fav'), 'icon-fav-off', 'icon-fav-on');
	}
	if (document.getElementById(detailsFavTgt))
	{
	    WPR.swapClass(document.getElementById(detailsFavTgt), 'icon-fav-off', 'icon-fav-on');
	}
	if (document.getElementById(newFavTarget))
	{
	    WPR.swapClass(document.getElementById(newFavTarget), 'icon-fav-off', 'icon-fav-on');
	} else if (document.getElementById(favTarget))
	{
	    //alert(favTarget);
	    $('#' + favTarget).text('SAVED');
	}
    })

    WPR.lastSave = {};
    $('.icon-fav-offx').on('click', function (e)
    {
	e.preventDefault();
	e.stopPropagation();
	//alert('mousedown');
	WPR.swapClass(this, 'icon-fav-off', 'icon-fav-on');
    })

    $('body').on('click', '.icon-fav', function (e)
    {
	e.stopImmediatePropagation();
	e.preventDefault();
	e.stopPropagation();
	SetFavorite(e);
    })

    $('body').on('click', '.listing_unit_price_wrapper .listing_actions', function (e)
    {
	e.preventDefault();
    })

    $('body').on('click', '.icon-favx', function (e)
    {
	//alert('clicked');
	e.preventDefault();
	e.stopPropagation();
	if ($(this).hasClass('icon-fav-on'))
	{
	    WPR.swapClass(this, 'icon-fav-on', 'icon-fav-off');
	    var id_parts = this.id.split('_')
	    WPR.lastSave.data = id_parts[1];
	    WPR.operation = UnsaveListing;
	    CheckLogin();
	} else
	{
	    WPR.swapClass(this, 'icon-fav-off', 'icon-fav-on');
	    var id_parts = this.id.split('_')
	    WPR.lastSave.data = id_parts[1];
	    WPR.operation = SaveListing;
	    CheckLogin();
	}
    })

    //$('.resultsNav4').on('click', function (e)
    $('body').on('click', '.resultsNav4', function (e)
    {
	e.preventDefault();
	var tgt = e.currentTarget;
	WPR.lastSave.data = jQuery(tgt).data('mls');
	WPR.operation = SaveListing;
	CheckLogin();
	//alert('Save from results and sc');
    });

    //$('span.st_fav > a').on('click', function (e)
    $('body').on('click', 'span.st_fav > a', function (e)
    {
	e.preventDefault();
	var tgt = e.currentTarget;
	WPR.lastSave.data = jQuery(tgt).data('mls');
	WPR.operation = SaveListing;
	CheckLogin();
	//alert('Save from listing');
    });

    //$(".savesearch").on('click', function (e)
    $('body').on('click', '.savesearch', function (e)
    {
	e.preventDefault();
	WPR.lastSave.data = window.location.href;
	WPR.operation = SaveSearch;
	CheckLogin();
	//alert('Save search');
    });

    //$("body #searches_list .email_type").on('change', function (e)
    $('body').on('change', '#searches_list .email_type', function (e)
    {
	var id = $(this).attr('data-id');
	var email_type = $(this).val();
	if (id != '')
	{
	    e.preventDefault();
	    WPR.lastSave.data = window.location.href;
	    WPR.operation = UpdateSaveSearch(id, email_type);
	    //alert('Update Save search');
	}
    });

    //$("body #searches_list .email_type").on('change', function (e)
    $('body').on('change', '#alerts_schedule', function (e)
    {
	var alerts_schedule = $(this).val();
	if (alerts_schedule != '')
	{
	    e.preventDefault();
	    WPR.lastSave.data = window.location.href;
	    WPR.operation = AllUpdateSaveSearch(alerts_schedule);
	    //alert('Update Save search');
	}
    });

    $('body').on('click', '.btn_logout a', function (e)
    {
	var site_url = window.location.protocol + "//" + window.location.host;
	WPR.operation = Logout();
	setTimeout(function ()
	{
	    window.location.replace(site_url);
	}, 2000);
    });

    $('body').on('click', '#searches_list .ss_delete', function (e)
    {
	var id = $(this).attr('data-id');
	if (id != '')
	{
	    e.preventDefault();
	    WPR.lastSave.data = window.location.href;
	    WPR.operation = DeleteSaveSearch(id);
	    //alert('Delete Save search');
	}
    });

    $('body').on('click', 'a[href*="my-account"]', function (e)
    {
	e.preventDefault();
	//var tgt = e.currentTarget;
	WPR.operation = GoToAccount;
	CheckLogin();
    });

    $('body').on('click', '.login_popup', function (e)
    {
	e.preventDefault();
	var tgt = e.currentTarget;
	//WPR.operation = GoToAccount;
	CheckLogin();
    });

    //$("#sticker").sticky({ topSpacing: 0});
    $('body').on('RpxListingsInserted', function ()
    {
	ActivateFavorites();
    })

});

function SetFavorite(e)
{
    //alert(e.target.id);
    e.stopImmediatePropagation();
    e.preventDefault();
    e.stopPropagation();

    if (jQuery(e.target).hasClass('icon-fav-on'))
    {
	//alert('on');
	//WPR.swapClass(e.target, 'icon-fav-off', 'icon-fav-on');
	WPR.swapClass(e.target, 'icon-fav-on', 'icon-fav-off');
	var id_parts = e.target.id.split('_');
	//WPR.lastSave.data = jQuery(e.target).closest('.property_listing').data('mls');
	WPR.lastSave.data = id_parts[1];
	WPR.operation = UnsaveListing;
	CheckLogin();
    } else
    {
	//alert('off');
	WPR.swapClass(e.target, 'icon-fav-off', 'icon-fav-on');
	//WPR.swapClass(e.target, 'icon-fav-on', 'icon-fav-off');
	var id_parts = e.target.id.split('_');
	//WPR.lastSave.data = jQuery(e.target).closest('.property_listing').data('mls');
	WPR.lastSave.data = id_parts[1];
	WPR.operation = SaveListing;
	CheckLogin();
    }
}

/**
 * Performs a login check and, if validated, performs the requested action
 * @returns {void}
 */
function CheckLogin()
{
    jQuery.get(WPR.ajaxurl + '?controller=UserAuth&action=logincheck', function (data)
    {
	if (data == 4)
	{
	    WprShowLoginForm();
	} else if (data == 1)
	{
	    WPR.operation();
	}
    });
}

function SaveFav()
{
    alert('prop saved');
}

function GoToAccount()
{
    //alert('Go to account');
}

/**
 * Saves a listing to a user's favorites
 * @returns {void}
 */
function SaveListing()
{
    // Need the ui change on save here
    jQuery.get(WPR.ajaxurl, {mls: WPR.lastSave.data, controller: 'AjaxFavs', action: 'SaveListing'})
	    .done(function (data)
	    {
		var favTarget = 'rpx_mls_' + WPR.lastSave.data;
		jQuery('#' + favTarget).text('SAVED');
	    });
}

/**
 * Removes a listing from a user's favorites
 * @returns {void}
 */
function UnsaveListing()
{
    // Need the ui change on save here
    jQuery.get(WPR.ajaxurl, {mls: WPR.lastSave.data, controller: 'AjaxFavs', action: 'UnsaveListing'})
	    .done(function (data)
	    {
		// Maybe do something
	    });
}

/**
 * Saves a search to a user's favorites
 * @returns {void}
 */
function SaveSearch()
{
    var name = prompt("Please enter a name for your search");
    name = name != null ? name : 'default';
    var search_criteria = jQuery("body .search_criteria").val();
    //var name = jQuery("input[name*='favorite_name']").val().length ? jQuery("input[name*='favorite_name']").val() : 'default';
    jQuery.post(WPR.ajaxurl, {url: window.location.href, controller: 'AjaxFavs', action: 'SaveSearch', name: name, search_criteria: search_criteria})
	    .done(function (data)
	    {
		jQuery("#svsrchres").show();
	    });
}

/**
 * Saves a search to a user's favorites
 * @returns {void}
 */
function UpdateSaveSearch(id, email_type)
{
    var result = id.split('|');
//var name = jQuery("input[name*='favorite_name']").val().length ? jQuery("input[name*='favorite_name']").val() : 'default';
    jQuery.post(WPR.ajaxurl, {controller: 'AjaxFavs', action: 'UpdateSaveSearch', favorite_id: result[0], uid: result[1], email_type: email_type})
	    .done(function (data)
	    {
		jQuery("#svsrchres").show();
	    });
    location.reload();
}

function AllUpdateSaveSearch(email_type)
{
    var user_id = jQuery("table.saved_search_result").attr('data-user-id');
    //alert(user_id);

    //var name = jQuery("input[name*='favorite_name']").val().length ? jQuery("input[name*='favorite_name']").val() : 'default';
    jQuery.post(WPR.ajaxurl, {controller: 'AjaxFavs', action: 'AllUpdateSaveSearch', uid: user_id, email_type: email_type})
	    .done(function (data)
	    {
		jQuery("#prefs").show();
	    });
    location.reload();
}

function Logout()
{
    jQuery.post(WPR.ajaxurl, {controller: 'AjaxFavs', action: 'Logout'})
	    .done(function (data)
	    {
	    });
}

function DeleteSaveSearch(id)
{
    var result = id.split('|');
    //var name = jQuery("input[name*='favorite_name']").val().length ? jQuery("input[name*='favorite_name']").val() : 'default';
    jQuery.post(WPR.ajaxurl, {controller: 'AjaxFavs', action: 'UnsaveSearch', favorite_id: result[0], uid: result[1]})
	    .done(function (data)
	    {
		jQuery("#svsrchres").show();
	    });
    location.reload();
}

/**
 * Sets the fav icon to on when a member of the result set is in user's favs
 * @returns null
 */
function ActivateFavorites()
{
    //alert(WPR.userFavorites);
    jQuery.each(WPR.userFavorites, function (i, mls)
    {
	var favTarget = 'rpx_mls_' + mls;
	var newFavTarget = 'fav_' + mls;
	var detailsFavTgt = 'favpage_' + mls;
	//alert(mls);
	if (jQuery("div[data-mls='" + mls + "']").length)
	{
	    //alert('found');
	    WPR.swapClass(jQuery("[data-mls='" + mls + "']").closest('.icon-fav'), 'icon-fav-off', 'icon-fav-on');
	}
	if (document.getElementById(detailsFavTgt))
	{
	    WPR.swapClass(document.getElementById(detailsFavTgt), 'icon-fav-off', 'icon-fav-on');
	}
	if (document.getElementById(newFavTarget))
	{
	    WPR.swapClass(document.getElementById(newFavTarget), 'icon-fav-off', 'icon-fav-on');
	} else if (document.getElementById(favTarget))
	{
	    //alert(favTarget);
	    jQuery('#' + favTarget).text('SAVED');
	}
    });
}