﻿var overlayCloseHandler = null;
var smsRecordId = null;

$(document).ready(function () {
    $('#loginForgot').click(function () {
        $('#loginForgot').hide();
        $('#resetPassModal p.error').hide();
        $('#loginForgot').after('<div id="forgotWait" class="modalConfirmWrap"><img src="/Content/images/anim-loading-modal.gif" /></div>');
        $.post('/Search/ResetPassword', {
            "email": $('#emailReset').val(),
            "captcha": $('#resetPassCaptchaField').val(),
            "captcha-guid": $('input[name=captcha-guid]', $('#resetPassCaptchaField').parent()).val()
        }, function (data) {
            $('#resetPassCaptcha input[name=captcha-guid]').val(data.Data.guid);
            $('#resetPassCaptcha img').attr('src', '/captcha.ashx?guid=' + data.Data.guid);

            if (data.Success) {
                $('#forgotWait').html('<img src="/Content/images/icon-tick.png" alt="" id="forgotDone" />');
                setTimeout('$("#overlay").fadeOut();', 2000);
            } else {
                $('#forgotWait').remove();
                $('#loginForgot').show();
                $('#resetPassModal p.error').html(data.Error).show();
                $('#resetPassCaptchaField').val('').focus();
            }
        }, 'json');
    });

    $('form#loginModal').submit(function () {
        $('#loginModal p.error').fadeOut('fast', function () {
            $('#loginSubmit').hide();
            $('#loginSubmit').after('<div id="loginWait" class="modalConfirmWrap"><img src="/Content/images/anim-loading-modal.gif" /></div>');

            $.post('/Search/Login', { "username": $('#login').val(), "password": $('#password').val(), "rememberMe": $('#remember').attr('checked'), "claimBusinessId": $('#hdnClaimBusinessId').val() }, function (data) {
                if (data.Success) {
                    document.location.href = data.Data.Redirect;
                } else {
                    $('#loginWait').remove();
                    $('#loginModal p.error').html(data.Error);
                    $('#loginModal p.error').fadeIn('fast');
                    $('#loginSubmit').show();
                    $('#login').focus();
                }
            }, 'json');
        });

        return false;
    });
    
    $('.closeLink a').click(function () {
        $('#overlay').fadeOut();
        if (overlayCloseHandler != null) {
            overlayCloseHandler();
            overlayCloseHandler = null;
        }
    });
    $('#overlay').click(function () {
        $('#overlay').fadeOut();
        if (overlayCloseHandler != null) {
            overlayCloseHandler();
            overlayCloseHandler = null;
        }
    });
    $('#overlay form').click(function (e) {
        e.stopPropagation();
    });

    if ($('#what').length > 0) {
        $('#what').autocomplete({
            minLength: 2,
            max: 10,
            source: function (request, response) {
                $.getJSON('/Search/What/' + encodeURIComponent(request.term) + '?max=8', function (data) {
                    response(data);
                });
            }
        }).data("autocomplete")._renderItem = function (ul, item) {
            item.label = Util.BoldSubstring(item.label, $('#what').val());
            return $('<li class="ui-menu-item"></li>')
                    .click(function (e) {
                        $('#what').val(item.value);
                        $('#what').focus();
                        ul.hide();
                        e.stopPropagation();
                    })
                    .hover(function () {
                        $(this).parent().parent().find('li a').removeClass('ui-state-hover');
                        $(this).find('a').addClass('ui-state-hover');
                    })
                    .data("item.autocomplete", item)
				    .append('<a class="ui-corner-all">' + item.label + '</a>')
				    .appendTo(ul);
        };
    }
    if ($('#where').length > 0) {
        $('#where').autocomplete({
            minLength: 2,
            max: 10,
            source: function (request, response) {
                $.getJSON('/Search/Where/' + encodeURIComponent(request.term) + '?max=8', function (data) {
                    response(data);
                });
            }
        }).data("autocomplete")._renderItem = function (ul, item) {
            item.label = Util.BoldSubstring(item.label, $('#where').val());

            return $('<li class="ui-menu-item"></li>')
                    .click(function (e) {
                        $('#where').val(item.value);
                        $('#where').focus();
                        ul.hide();
                        e.stopPropagation();
                    })
                    .hover(function () {
                        $(this).parent().parent().find('li a').removeClass('ui-state-hover');
                        $(this).find('a').addClass('ui-state-hover');
                    })
				    .data("item.autocomplete", item)
				    .append('<a class="ui-corner-all">' + item.label + '</a>')
				    .appendTo(ul);
        };
    }

    $('label[for="what"] a').click(function (e) {
        $('#what').val($(this).text());
    });
    $('label[for="where"] a').click(function (e) {
        $('#where').val($(this).text());
    });
    var smsClick = function (e) {
        $(this).replaceWith('<div id="smsWait" class="modalConfirmWrap"><img src="/Content/images/anim-loading-modal.gif" alt="" /></div>');

        $.post('/Search/SendSms', {
            "businessRecordId": smsRecordId,
            "phoneNo": $('#mobile').val(),
            "captcha": $('#smsCaptchaField').val(),
            "captcha-guid": $('input[name=captcha-guid]', $('#smsCaptchaField').parent()).val()
        }, function (data) {
            $('#smsCaptcha input[name=captcha-guid]').val(data.Data.guid);
            $('#smsCaptcha img').attr('src', '/captcha.ashx?guid=' + data.Data.guid);

            if (data.Success) {
                $('#smsWait').html('<img src="/Content/images/icon-tick.png" alt="" id="smsDone" />');
                $('#smsCaptchaField').val('');

                setTimeout(function () {
                    $('#smsModal').hide();
                    $("#overlay").fadeOut(function () {
                        $('#smsWait').replaceWith('<input type="button" value="Send SMS" name="sendSMS" id="sendSMS" class="btn sendSMS">');
                        $('#smsCaptchaField').focus();
                        $('#sendSMS').click(smsClick);
                    });
                }, 2000);
            } else {
                $('#smsWait').replaceWith('<p class="error smsError">' + data.Error + '</p>');
                $('#smsCaptchaField').val('').focus();

                window.setTimeout(function () {
                    $('.smsError').parent().fadeOut(function () {
                        $('.smsError').replaceWith('<input type="button" value="Send SMS" name="sendSMS" id="sendSMS" class="btn sendSMS">');
                        $('#sendSMS').parent().fadeIn(function () {
                            $('#sendSMS').click(smsClick);
                        });
                    });
                }, 2000);
            }
        }, 'json');
    };
    $('#sendSMS').click(smsClick);


    $('#loginModal:input').keypress(function () {
        if (e.keyCode == '13') {
            $('#loginSubmit').click();
        }
    });
    $('#clients .login a').click(function () {
        $('#loginModal').show();
        $('#resetPassModal').hide();
        $('#overlay').fadeIn();
        centreElement($('#loginModal'));
        $('#login').focus();
        overlayCloseHandler = function () {
            $('#loginModal').hide();
        };
    });
    $('.forgotLink a').click(function () {
        $('#loginModal').hide();
        $('#resetPassModal').show();
        centreElement($('#resetPassModal'));
        $('#emailReset').focus();

        overlayCloseHandler = function () {
            $('#resetPassModal').hide();
        };
    });
    $('#smsModal :input').keypress(function (e) {
        if (e.keyCode == '13') {
            $('#sendSMS').click();
        }
    });
    $(':input:not(#searchHeader input, #searchHome input, .userForm input, #searchCriteria input, #loginModal input, .adminReportFilter input)').live('keypress', function (e) {
        if (e.keyCode == '13') {
            var ele = $(this);
            var type = ele.attr('type');
            switch (type) {
                case 'button':
                case 'submit':
                case 'textarea':
                    break;

                default:
                    e.preventDefault();
            }
        }
    });
});

/* Autocomplete */
(function ($) {
    $(".ui-autocomplete-input").live("autocompleteopen", function () {
        var autocomplete = $(this).data("autocomplete"),
		menu = autocomplete.menu;
        if (!autocomplete.options.selectFirst) {
            return;
        }
        menu.activate($.Event({ type: "mouseenter" }), menu.element.children().first());
    });
} (jQuery));

(function ($) {
    $.fn.watermark = function (css, text) {
        return this.each(function () {
            var i = $(this), w;
            i.focus(function () {
                w && !(w = 0) && i.removeClass(css).data('w', 0).val('');
            })
					.blur(function () {
					    !i.val() && (w = 1) && i.addClass(css).data('w', 1).val(text);
					})
					.closest('form').submit(function () {
					    w && i.val('');
					});
            i.blur();
        });
    };
    $.fn.removeWatermark = function () {
        return this.each(function () {
            $(this).data('w') && $(this).val('');
        });
    };
})(jQuery);


/* Custom functions */

function centreElement(e) {
    var top = ($('#overlay').outerHeight() / 2) * 0.8 - (e.outerHeight() / 2);
    if (top < 20)
        top = 20;
    e.css('top', top + 'px');
}

function endsWith(str, ending) {
    if (str.substr(str.length - ending.length) == ending)
        return true;
    return false;
}

function startsWith(str, start) {
    if (str.substr(0, start.length) == start)
        return true;
    return false;
}

function doSearch() {
    var what = jQuery.trim($("#what").val());
    what = Util.replaceAll(what, '/', ' ');
    what = what.replace('\\', ' ');
    what = escape(what);

    var where = jQuery.trim($("#where").val());
    where = Util.replaceAll(where, '/', ' ');
    where = where.replace('\\', ' ');
    where = escape(where);

    if (what.length == 0) {
        alert("Please include something in the 'what' field");
        return false;
    }

    var url = "/Search/Find/" + what;

    if (where.length > 0)
        url += "/" + where;

    window.location = url;

    return false;
}

