﻿/// <reference path="jquery-1.3.2-vsdoc.js" />

var WCH = function () {
    return {
        Flash: function (msg) {
            $('#flashClientSide').show().find('.message').html(msg);
            $('#flash').addClass('active').hide().slideDown('fast');
        },
        Log: function (msg) {
            if (console.log) console.log(msg);
        },
        ShowLoading: function () {
            $('#loading').show();
        },
        HideLoading: function () {
            $('#loading').hide();
        },
        InitMemberBadge: function($e) {
            var username = $('a.profileLink', $e)[0].href.split('/')[3]; //todo: change to username
            $e.qtip({
                content: {
                    title: { text: '<a href="/' + username + '" title="Click to view this member\'s public profile.">' + username + '</a>' },
                    url: '/' + username + '/badge',
                    data: username,
                    method: 'post'
                },
                style: {
                    classes: { tooltip: 'memberBadgeQTipTooltip' }
                },
                position: {
                    corner: { target: 'topLeft' },
                    adjust: { y: 0, x: 0 }
                },
                show: { delay: 750, when: { event: 'mouseover'}, effect: 'slide' },
                hide: { delay: 250, fixed: true, when: { event: 'mouseout'} },
            });
        }
    };
} ();

$(function () {
    $('body').css('background-color', $('#footerContainer').css('background-color'));
    
    $('.fileInputMask input[type="file"]').change(function () {
        var filePath = $(this).val();
        var fileName = filePath.substring(filePath.lastIndexOf('\\') + 1);
        $(this).closest('.fileInputMask').siblings('.fileName').text(fileName);
    });

    var InitSearchByCategory = function () {
        $('#searchByCategorySelect').change(function () {

            if ($('#searchByRegionSelect').length > 0 && $('#searchByAreaSelect').length > 0) {
                window.location = '/' + $('#searchByRegionSelect').val() + '/' + $('#searchByAreaSelect').val().replace(' ', '') + '?categoryId=' + $('#searchByCategorySelect').val();
            }
            if ($('#searchByRegionSelect').length > 0 && $('#searchByAreaSelect').length == 0) {
                window.location = '/' + $('#searchByRegionSelect').val() + '?categoryId=' + $('#searchByCategorySelect').val();
            }
            if ($('#searchByRegionSelect').length > 0 && $('#searchByAreaSelect').length == 0) {
                window.location = '/search?categoryId=' + $(this).val();
            }

            //window.location = '/search?categoryId=' + $(this).val();
        });

        $('#searchBySubcategorySelect').change(function () {
            if ($('#searchByRegionSelect').length > 0 && $('#searchByAreaSelect').length > 0) {
                window.location = '/' + $('#searchByRegionSelect').val() + '/' + $('#searchByAreaSelect').val().replace(' ', '') + '?categoryId=' + $('#searchByCategorySelect').val() + '&subcategoryId=' + $(this).val();
            }
            if ($('#searchByRegionSelect').length > 0 && $('#searchByAreaSelect').length == 0) {
                window.location = '/' + $('#searchByRegionSelect').val() + '?categoryId=' + $('#searchByCategorySelect').val() + '&subcategoryId=' + $(this).val();
            }
            if ($('#searchByRegionSelect').length > 0 && $('#searchByAreaSelect').length == 0) {
                window.location = '/search?categoryId=' + $('#searchByCategorySelect').val() + '&subcategoryId=' + $(this).val();
            }
            //window.location = '/search?categoryId=' + $('#searchByCategorySelect').val() + '&subcategoryId=' + $(this).val();
            //window.location = '/' + $('#searchByRegionSelect').val() + '/' + $('#searchByAreaSelect').val().replace(' ', '') + '?categoryId=' + $('#searchByCategorySelect').val() + '&subcategoryId=' + $(this).val();
        });
    };
    var InitSearchByLocation = function () {
        $('#searchByRegionSelect').change(function () {
            window.location = '/' + $(this).val();
        });

        $('#searchByAreaSelect').change(function () {
            window.location = '/' + $('#searchByRegionSelect').val() + '/' + $(this).val().replace(' ', '') + '?categoryId=' + $('#searchByCategorySelect').val() + '&subcategoryId=' + $('#searchBySubcategorySelect').val();
        });
    };
    var InitSetLoation = function () {
        $('#setLocationCriteria').find('input[name=location]').autocomplete('/dashboard/leads/areas', { autoFill: true });

        $('.setLocation').click(function () {
            $('#setLocationCriteria').toggle();
            return false;
        });
    };
    var InitFlashOnHash = function () {
        var id = window.location.hash;
        if (id.length > 0) {
            var $item = $(id);
            setTimeout(function () {
                $item.css('background-color', '#fff')
                    .animate({ backgroundColor: '#EDD519' }, 300)
                    .animate({ backgroundColor: '#fff' }, 800);
            }, 400);
        }
    };
    var InitLabelify = function () {
        $('.setLocationForm input[type=text]').labelify({ labelledClass: 'inTextBoxLabel' });
        $('.createPostForm input[type=text]').labelify({ labelledClass: 'inTextBoxLabel' });
        $('.labelify').labelify({ labelledClass: 'inTextBoxLabel' });
        //$('#p').labelify({ labelledClass: 'inTextBoxLabel' });
    };
    var InitSearchTermPersist = function () { //todo: if this is only going to be on the search page like it is now, we can probably move it there and out of the common js file. -lance
        var $searchInput = $(".searchForm input[type=text]");
        if ($searchInput.length === 0) return;
        var searchQuery = $searchInput.val();
        if (searchQuery.length < 1) {
            $searchInput.labelify({ labelledClass: "inTextBoxLabel" });
        } else {
            $searchInput.focus();
            $searchInput.val($searchInput.val());
        }
    };
    var InitTimeago = function () {
        $('abbr[class*=timeago]').timeago();
    };

    var InitFlashMessage = function () {
        $('#flash.active').show();
        $('#flash a.close').click(function () {
            $(this).closest('li').slideUp('fast');
            return false;
        });
    };
    var InitEmailValidation = function () {
        $('a.emailValidation').live('click', function () {
            WCH.ShowLoading();

            $.ajax({
                type: 'POST',
                url: this.href,
                dataType: 'json',
                success: function (response) {
                    WCH.HideLoading();
                    WCH.Flash(response.success ?
    					        'A confirmation email was sent to ' + response.email + '. Check your email (and SPAM FILTER) for the confirmation message and follow the instructions.' :
    					        'Could not send the email confirmation.');
                }
            });

            return false;
        });
    };

    var InitFirstTimeUserDismissLink = function () {
        $('#flash a.welcomeLink')
            .closest('#flash')
            .find('.close a.close')
            .click(function () {
                var expireDate = new Date();
                expireDate.setFullYear(2037, 0, 1);
                $.cookie('f', 0, { expires: expireDate, path: '/' });
            });

    };

    var InitQTip = function () {
        $('.memberBadge').each(function () {
            WCH.InitMemberBadge($(this));
        });

        $('#profileHelper').qtip({
            content: {
                text: $('#profileHelperTooltipContent').html(),
                title: { text: 'Profile Helper' }
            },
            style: {
                tip: { corner: 'topLeft', size: { x: 5, y: 5 }, color: '#333' },
                classes: { content: 'profileHelperQTipContent' }
            },
            position: {
                corner: { target: 'bottomLeft', tooltip: 'topLeft' },
                adjust: { y: -2, screen: true }
            },
            show: { delay: 500, when: { event: 'mouseover'} },
            hide: { delay: 500, fixed: true, when: { event: 'mouseout'} }
        });
    };

    var InitSubmitLinks = function () {
        $('.submit-link').live('click', function () {
            var confirmText = $(this).attr('confirm');
            if (confirmText && !confirm(confirmText))
                return false;

            $('<form>').attr('action', this.href).attr('method', 'POST').appendTo('body').submit();
            return false;
        });
    };

    var InitFocusForm = function () {
        $('.focus-form input[type=text]')
            .add('.focus-form input[type=password]')
            .add('.focus-form input[type=checkbox].triggerFocus')
            .add('.focus-form select')
            .add('.focus-form textarea')
            .focus(function () {
                removeFocus($(this).closest('.focus-form').children('.formLine.focus'));

                $(this).closest('.formLine')
                    .addClass('focus')
                    .children(".helpText").show();
            })
            .blur(function () {
                removeFocus($(this).closest('.formLine'));
            });

        function removeFocus($e) {
            $e.removeClass('focus').children(".helpText").hide();
        }
    };

    function InitDatePickers() {
        var now = new Date();
        $('.datePicker').each(function () {
            var $datePicker = $(this);
            $datePicker.DatePicker({
                format: 'm/d/Y',
                current: $datePicker.val(),
                date: '1/1/2009',
                onBeforeShow: function () {
                    $datePicker.DatePickerSetDate($datePicker.val() || now.valueOf(), true);
                },
                onChange: function (formatted, dates) {
                    $datePicker.val(formatted).focus().DatePickerHide();
                }
            });

            $datePicker.focus(function () {
                $datePicker.DatePickerShow();
            });

            $('input, textarea, select').not($datePicker).focus(function () {
                $datePicker.DatePickerHide();
            });
        });
    };

    InitSearchByCategory();
    InitSetLoation();
    InitFlashOnHash();
    InitLabelify();
    InitSearchTermPersist();
    InitTimeago();
    InitFlashMessage();
    InitEmailValidation();
    InitFirstTimeUserDismissLink();
    InitQTip();
    InitSubmitLinks();
    InitSearchByLocation();
    InitFocusForm();
    InitDatePickers();
});

