var Extend = function () {
    return {
        showGroupChannel: function (channelId, channelName, channelUrl, linkTarget, navLocation, bgColor, textColor, dividerColor, isLast) {
            var chList = Extend.Cookie.getCookie('chList');
            if (chList && chList.indexOf(channelId) != -1) {
                if (dividerColor.length > 0)
                    document.write('<div class="spacer" style="background:' + dividerColor + '"> </div>');
                else
                    document.write('<div class="spacer"> </div>');

                if (bgColor.length > 0)
                    document.write('<div class="' + navLocation + 'nav" style="background:' + bgColor + '">');
                else
                    document.write('<div class="' + navLocation + 'nav">');

                if (textColor.length > 0)
                    document.write('<a style="color:' + textColor + '" target="' + linkTarget + '" href="' + channelUrl + '">' + channelName + '</a></div>');
                else
                    document.write('<a target="' + linkTarget + '" href="' + channelUrl + '">' + channelName + '</a></div>');

                if (isLast) {
                    if (dividerColor)
                        document.write('<div class="spacer" style="background:' + dividerColor + '"> </div>');
                    else
                        document.write('<div class="spacer"> </div>');
                }
            }
        },
        showGroupSubChannel: function (channelId, channelName, channelUrl, linkTarget) {
            var chList = Extend.Cookie.getCookie('chList');
            if (chList && chList.indexOf(channelId) != -1)
                document.write('<a target="' + linkTarget + '" href="' + channelUrl + '">' + channelName + '</a>');
            else
                document.write('&nbsp;');
        },
        showRegisterSignIn: function (showWelcome, showRegister, showSignIn, baseUrl, channelUrl) {
            var accessUser = Extend.Cookie.getCookie('access_user');
            var userName = accessUser || Extend.Cookie.getCookie('extend_user');
            if (userName && showWelcome)
                document.write('<span id="welcome">Welcome ' + userName + ' </span>');
            document.write('<span id="signin">');
            if (userName) {
                if (!accessUser) {
                    document.write('<a href="' + baseUrl + '_profile?returnurl=' + channelUrl + '">Profile</a> | ');
                }
                document.write('<a href="' + baseUrl + '_signout?returnurl=' + channelUrl + '">Sign Out</a>');
            } else {
                if (showRegister)
                    document.write('<a href="' + baseUrl + '_register?returnurl=' + channelUrl + '">Register</a>');
                if (showRegister && showSignIn)
                    document.write(' | ');
                if (showSignIn)
                    document.write('<a href="' + baseUrl + '_signin?returnurl=' + channelUrl + '">Sign In</a>');
            }
            document.write('</span>');
        },
        printPage: function () {
            if (window.print) window.print();
            else alert('Sorry, this feature is not available on your browser.\nPlease use your browser\'s print button.');
        },
        sendToFriend: function (url) {
            url += '&pageurl=' + escape(window.location.href);
            var top = window.screen.height / 2 - 400 / 2;
            var left = window.screen.width / 2 - 400 / 2;
            var win = window.open(url, 'sendtofriend', 'top=' + top + ',left=' + left + ',width=400,height=400,scrollbars=1,resizable=1');
            win.opener = window;
            win.focus();
        },
        bookmarkPage: function () {
            if (document.all) window.external.AddFavorite(window.location.href, document.title);
            else if (window.sidebar) window.sidebar.addPanel(document.title, window.location.href, '');
        },
        getGadgetUrl: function (obj) {
            if (obj.src.indexOf('?') == -1) {
                obj.src += '?context=extend';
                if (login = Extend.Cookie.getCookie('extend_login'))
                    obj.src += '&login=' + login;
            }
        }
    };
} ();

Extend.DateTime = function () {
    return {
        getDay: function () {
            var word_day = new Array('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday');
            var right_now = new Date();
            return word_day[right_now.getDay()];
        },
        getDate: function () {
            var word_month = new Array('January ', 'February ', 'March ', 'April ', 'May ', 'June ', 'July ', 'August ', 'September ', 'October ', 'November ', 'December ')
            var right_now = new Date();
            var right_year = right_now.getYear();
            if (right_year < 2000) right_year = right_year + 1900;
            return word_month[right_now.getMonth()] + right_now.getDate() + ', ' + right_year;
        },
        getTime: function () {
            var right_now = new Date();
            var time;
            var hours = right_now.getHours();
            if (hours >= 12) time = 'PM';
            else time = 'AM';
            if (hours > 12) hours -= 12;
            if (hours == 0) hours = 12;
            var mins = right_now.getMinutes();
            if (mins < 10) mins = '0' + mins;
            return hours + ':' + mins + ' ' + time;
        }
    }
} ();

Extend.Cookie = function () {
    var getCookieVal = function (offset) {
        var endstr = document.cookie.indexOf(';', offset);
        if (endstr == -1)
            endstr = document.cookie.length;
        return document.cookie.substring(offset, endstr);
    };

    return {
        getCookie: function (name) {
            var arg = name + '=';
            var alen = arg.length;
            var clen = document.cookie.length;
            var i = 0;
            while (i < clen) {
                var j = i + alen;
                if (document.cookie.substring(i, j) == arg)
                    return getCookieVal(j);
                i = document.cookie.indexOf(' ', i) + 1;
                if (i == 0) break;
            }
            return null;
        }
    }
} ();

Extend.JSON = function () {

    return {
        /*
        This stringify wrapper is required for IE8 to correctly handle values pulled from empty dom elements.
        The full explanation can be found on the MSDN JScript blog:
        http://blogs.msdn.com/jscript/archive/2009/06/23/serializing-the-value-of-empty-dom-elements-using-native-json-in-ie8.aspx
        */
        stringify: function (args) {
            return JSON.stringify(args, function (k, v) { return v === "" ? "" : v });
        }
    }

} ();

Extend.Search = function () {
    var validateSearchText = function (searchTextbox) {
        if (searchTextbox.val().length == 0) {
            alert('Please enter one or more search terms.');
            searchTextbox.focus();
            return false;
        }
        return true;
    };

    var submitSearch = function (searchTextbox, resultsPage, openInNewWindow) {
        if (searchTextbox.attr('disabled').length > 0 || !validateSearchText(searchTextbox))
            return;

        var valid = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789- ';
        var searchText = '';
        var temp = $('#searchtextbox').val();
        for (i = 0; i < temp.length; i++)
            if (valid.indexOf(temp.charAt(i)) > -1)
                searchText += temp.charAt(i);

        if (openInNewWindow)
            window.open(resultsPage + '?q=' + searchText);
        else
            location.href = resultsPage + '?q=' + searchText;
    };

    return {
        init: function () {
            var searchTextbox = $('#searchform #searchtextbox');
            var goButton = $('#searchform #go');
            var searchText = $('#searchform #searchText').val();
            var resultsPage = $('#searchform #resultsPage').val();
            var openInNewWindow = $('#searchform #openInNewWindow').val() == 'true';

            searchTextbox.focus(function () {
                searchTextbox.val('');
            }).blur(function () {
                if (searchTextbox.val.length == 0) {
                    searchTextbox.val(searchText);
                }
            }).keypress(function (event) {
                var keyCode = null;
                if (event.which)
                    keyCode = event.which;
                else if (event.keyCode)
                    keyCode = event.keyCode;
                if (keyCode == 13) {
                    submitSearch(searchTextbox, resultsPage, openInNewWindow);
                    event.preventDefault();
                }
                return true;
            });

            goButton.click(function () {
                submitSearch(searchTextbox, resultsPage, openInNewWindow);
            });
        }
    }
} ();

Extend.Calendar = function () {
    return {
        adjustCalendar: function (calendarViewId, prePostDate, direction) {
            var workingDate = new Date(prePostDate);
            var day = workingDate.getDate();
            var month = workingDate.getMonth() + 1;
            var year = workingDate.getFullYear();

            if (direction == -1) {
                if (month == 1) {
                    month = 12;
                    year--;
                }
                else
                    month--;
            }
            else if (direction == 1) {
                if (month == 12) {
                    month = 1;
                    year++;
                }
                else
                    month++;
            }

            $.get('/controls/calendarofevents_loader.aspx?CalendarViewId=' + calendarViewId + '&EventId=0&WorkingDate=' + month + '/01/' + year + '&Action=ShowCalendar', function (response) {
                $('#ucCalendarOfEvents' + calendarViewId + '_divCalendar').html(response);
            });
        },
        showTodaysEvents: function (calendarViewId, eventDate) {
            var workingDate = new Date(eventDate);
            var day = workingDate.getDate();
            var month = workingDate.getMonth() + 1;
            var year = workingDate.getFullYear();

            $.get('/controls/calendarofevents_loader.aspx?CalendarViewId=' + calendarViewId + '&EventId=0&WorkingDate=' + month + '/' + day + '/' + year + '&Action=ShowTodaysEvents', function (response) {
                $('#ucCalendarOfEvents' + calendarViewId + '_divCalendar').html(response);
            });
        },
        showEvent: function (calendarViewId, eventId, eventDate) {
            var workingDate = new Date(eventDate);
            var day = workingDate.getDate();
            var month = workingDate.getMonth() + 1;
            var year = workingDate.getFullYear();

            $.get('/controls/calendarofevents_loader.aspx?CalendarViewId=' + calendarViewId + '&EventId=' + eventId + '&WorkingDate=' + month + '/' + day + '/' + year + '&Action=ShowEvent', function (response) {
                $('#ucCalendarOfEvents' + calendarViewId + '_divCalendar').html(response);
            });
        }
    }
} ();

Extend.Form = function () {

    var getFieldValue = function (field) {
        var value = '';
        if (field.is('.name')) {
            var firstName = $.trim(field.find('input.firstname').val());
            var lastName = $.trim(field.find('input.lastname').val());
            if (firstName.length > 0 && lastName.length > 0) {
                value = firstName + ' ' + lastName;
            }
        }
        else if (field.is('.fullname')) {
            var firstName = $.trim(field.find('input.firstname').val());
            var middleName = $.trim(field.find('input.middlename').val());
            var lastName = $.trim(field.find('input.lastname').val());
            if (firstName.length > 0 && middleName.length > 0 && lastName.length > 0) {
                value = firstName + ' ' + middleName + ' ' + lastName;
            }
        }
        else if (field.is('.phone')) {
            var area = $.trim(field.find('.area').val());
            var prefix = $.trim(field.find('.prefix').val());
            var suffix = $.trim(field.find('.suffix').val());
            var ext = $.trim(field.find('.ext').val());
            if (area.length > 0 || prefix.length > 0 || suffix.length > 0) {
                value = '(' + area + ') ' + prefix + '-' + suffix;
                if (ext.length > 0) {
                    value += ' ext. ' + ext;
                }
            }
        }
        else if (field.is('.dropdown')) {
            value = $.trim(field.find('select').val());
        }
        else if (field.is('.multiline')) {
            value = $.trim(field.find('textarea').val());
        }
        else if (field.is('.checkbox')) {
            value = field.find('input:checkbox').is(':checked');
        }
        else if (field.is('.radiobutton')) {
            value = field.find('input:radio:checked').val();
        }
        else {
            value = $.trim(field.find('input').val());
        }

        return value;
    };

    var validateField = function (field, label, value, validationSummary) {
        // Validate required fields
        if (!value || value.length == 0) {
            if (field.find('span.required').length > 0) {
                validationSummary.children('ul').append('<li>' + label + ' is a required field.</li>');
                return false;
            }
            return true;
        }

        // Validate formatting
        if (field.is('.email')) {
            var expression = /\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/;
            if (value.search(expression) < 0) {
                validationSummary.children('ul').append('<li>' + label + ' is not in the correct format. (eg. name@domain.com).</li>');
                return false;
            }
        }
        if (field.is('.datepicker')) {
            var expression = /^\d{1,2}\/\d{1,2}\/\d{4}$/;
            if (value.search(expression) < 0) {
                validationSummary.children('ul').append('<li>' + label + ' must be a valid date in the format mm/dd/yyyy.</li>');
                return false;
            }
        }
        if (field.is('.zip')) {
            var expression = /\d{5}(\-\d{4})?$/;
            if (value.search(expression) < 0) {
                validationSummary.children('ul').append('<li>' + label + ' is not in the correct format. (eg. 12345 or 12345-1234).</li>');
                return false;
            }
        }
        if (field.is('.phone')) {
            var expression = /^\(\d{3}\) \d{3}\-\d{4}( ext\. \d{1,6})?$/;
            if (value.search(expression) < 0) {
                validationSummary.children('ul').append('<li>' + label + ' is not in the correct format. (eg. (123) 456-7890).</li>');
                return false;
            }
        }

        return true;
    };

    var submitForm = function () {
        var submitButton = $(this);
        var formWrapper = submitButton.parent().parent();
        var validationSummary = formWrapper.children('div.error');
        var formId = formWrapper.attr('id').replace('form', '');
        var formData = [];
        var isValid = true;

        // Reset validation summary
        validationSummary.children('ul').remove();
        validationSummary.append('<ul></ul>');
        validationSummary.hide();

        formWrapper.children('div.formfield').each(function () {
            var field = $(this);
            var label = field.attr('title');
            var value = getFieldValue(field);

            if (!validateField(field, label, value, validationSummary)) {
                isValid = false;
            }

            formData.push(value);
        });

        if (!isValid) {
            validationSummary.show();
            validationSummary.focus();
            return;
        }

        $.ajax({
            url: '/presentation.asmx/SubmitForm',
            type: 'POST',
            contentType: 'application/json; charset=utf-8',
            dataType: 'json',
            data: Extend.JSON.stringify({
                submittedFormId: formId,
                submittedFormData: formData
            }),
            beforeSend: function () {
                // Disable the form
                submitButton.after('<span class="saving"> Submitting...</span>');
                formWrapper.find('*').attr('disabled', 'disabled').css('cursor', 'wait');
            },
            success: function (result) {
                if (result.d.Success) {
                    formWrapper.html(result.d.SuccessMessage);
                }
                else {
                    for (var i = 0; i < result.d.Errors.length; i++) {
                        validationSummary.children('ul').append('<li>' + result.d.Errors[i] + '</li>');
                        validationSummary.show();
                        validationSummary.focus();
                    }
                }
            },
            error: function () {
                validationSummary.children('ul').append('<li>The form submission failed unexpectedly.  Please try again.</li>');
                validationSummary.show();
                validationSummary.focus();
            },
            complete: function () {
                // Re-enable the form
                $('span.saving').remove();
                formWrapper.find('*').attr('disabled', '').css('cursor', '');
            }
        });
    };

    return {
        init: function () {
            // Preload css images for validation summary and date picker
            $('<img />').attr('src', '/admin/images/error-bg.gif');
            $('<img />').attr('src', '/admin/images/symbol_restricted_16.gif');
            $('<img />').attr('src', '/admin/images/boxtitle_bg.gif');

            // Bind submit action
            $('.formwrapper input[type="button"]').click(submitForm);
        }
    }

} ();

$(document).ready(function () {
    Extend.Search.init();
    Extend.Form.init();
});