﻿/*
Built on jquery 1.5.2
Author: Jeff J. Crist
Dependency on jsontable.js
*/

(function($) {
    $(function() {
        $.SelectValueInDropDown = function(p) {
            p = $.extend({
                id: '',
                matchValue: '',
                usePartialMatch: true
            }, p);

            $("#" + p.id + " option:eq(0)").attr('selected', 'selected');
            var foundMatch = false;
            $("#" + p.id + " option").each(function() {
                if ($(this).html() == p.matchValue) {
                    $(this).attr('selected', 'selected');
                    foundMatch = true;
                }
            });
            if (p.usePartialMatch) {
                //exact match was not found, try partial match
                var reg = /\w\w\w/;
                var s = reg.exec(p.matchValue);
                if (!foundMatch && s != null) {
                    $("#" + p.id + " option").each(function() {
                        if (!foundMatch && reg.exec($(this).html()) == s[0]) {
                            $(this).attr('selected', 'selected');
                            foundMatch = true;
                        }
                    });
                }
            }
        }; //end SelectValueInDropDown

        $.ManagementSystemRODetails = function(p) {
            p = $.extend({
                roNumber: null,
                yearFunc: null,
                makeFunc: null,
                modelFunc: null,
                refinishHoursFunc: null,
                vinFunc: null,
                runWhenStarted: function() { alert('details started'); },
                runWhenComplete: function() { alert('details complete'); }
            }, p);
            if (p.roNumber === undefined) return;
            $.ajax({
                url: "/HttpHandlers/ManagementSystemAsync.ashx?method=getrodetails&id=" + p.roNumber,
                dataType: 'json',
                success: function(data) {
                    p.runWhenStarted();
                    if (data != null) {
                        //Year
                        if (p.yearFunc != null)
                            p.yearFunc(data.Year);
                        //Make
                        if (p.makeFunc != null)
                            p.makeFunc(data.Make);
                        //Model
                        if (p.modelFunc != null)
                            p.modelFunc(data.Model);
                        //RefinishHours
                        if (p.refinishHoursFunc != null)
                            p.refinishHoursFunc(data.RefinishHours);
                        //Vin
                        if (p.vinFunc != null)
                            p.vinFunc(data.VIN);
                    }
                    p.runWhenComplete();
                }
            }); //end $.ajax()
        }; //end ManagementSystemRODetails

        $.ShowManagementSystemRODropDown = function(p) {
            p = $.extend({
                id: 'roNumberDropDownList',
                name: 'roNumber',
                parentElement: '.openROList',
                selectedRO: '99999',
                dropDownInitialValue: '-Select RO Number-',
                selectBoxStyle: '',
                onChangeEvent: function() { alert('value changed'); },
                runWhenStarted: function() { alert('started'); },
                runWhenComplete: function() { alert('task is complete'); }
            }, p);
            $.getJSON("/HttpHandlers/ManagementSystemAsync.ashx?method=getopenrosummarylist",
                function(data) {
                    p.runWhenStarted();
                    var select = document.createElement('select');
                    $(select).attr('id', p.id);
                    $(select).attr('name', p.name);
                    $(select).attr('style', p.selectBoxStyle);
                    var option = document.createElement('option');
                    var firstOption = $(option).clone();
                    $(firstOption).append(p.dropDownInitialValue);
                    $(select).append(firstOption);
                    $.each(data, function(key, val) {
                        var o = $(option).clone();
                        $(o).append(val.Name);
                        $(o).attr('value', val.ID);
                        if (p.selectedRO == val.ID) {
                            $(o).attr('selected', 'selected');
                        }
                        $(select).append(o);
                    });
                    $(select).change(p.onChangeEvent);
                    $(p.parentElement).append(select);
                    p.runWhenComplete();
                }); //end getJSON
        }; //end ShowManagementSystemRODropDown

        $.ToggleMarkAsComplete = function(p) {
            p = $.extend({
                roNumber: null,
                runOnSuccess: function(msg) { alert(msg); },
                runOnError: function(msg) { alert(msg); },
                runBeforeSend: function() { alert('before send'); },
                runWhenStarted: function() { alert('started'); },
                runWhenComplete: function() { alert('task is complete'); }
            }, p);
            $.ajax({
                url: "/HttpHandlers/ManagementSystemAsync.ashx?method=togglemarkascomplete&id=" + p.roNumber,
                dataType: 'json',
                beforeSend: p.runBeforeSend(),
                success: function(data) {
                    p.runWhenStarted();
                    if (data != null) {
                        if (data.Success != null) { p.runOnSuccess(data.Success); }
                        if (data.Error != null) { p.runOnError(data.Error); }
                    }
                    p.runWhenComplete();
                }
            }); //end ajax
        }; //end ToggleMarkAsComplete

        $.DisplayMsg = function(p) {
            p = $.extend({
                container: '#Message',
                msgClass: 'mgmtSystemInfo',
                msg: 'test message'
            }, p);
            $(p.container).html(p.msg);
            $(p.container).addClass(p.msgClass);
            $(p.container).show('fast');
        }; //end DisplayMsg

        $.RemoveROFromGrid = function(p) {
            p = $.extend({
                container: '#Message',
                ro: ''
            }, p);
            $(p.container + ' table tbody tr').each(function() {
                var ro = $(this).children('td:first').children('a').html();
                if (ro == p.ro) $(this).remove();
            });
        }; //end RemoveROFromGrid

        $.AppendToggleToGrid = function(p) {
            p = $.extend({
                container: '#OpenROsOutput',
                markClosedImg: '/Resources/mgs_x.png',
                markOpenImg: '/Resources/mgs_check.png',
                processingImg: '/Resources/progressindicator.gif',
                imgClass: 'MarkComplete',
                initialState: 'open',
                closeMsg: 'Mark RO Complete',
                openMsg: 'Re-Open RO'
            }, p);

            if (p.initialState == 'open') {
                p.initialImg = p.markClosedImg;
                p.initialImgAlt = p.closeMsg;
            }
            else {
                p.initialImg = p.markOpenImg;
                p.initialImgAlt = p.openMsg;
            }

            $(p.container + ' table tbody tr').each(function() {
                if ($(this).children('td').length > 1) {
                    $(this).children('td:first').prepend('<img class="' + p.imgClass + '" src="' + p.initialImg + '" alt="' + p.initialImgAlt + '" />');
                }
            });
            $(p.container + ' .' + p.imgClass).click(function() {
                var ro = $(this).siblings('a').html();
                var rowId = '#' + $(this).parent().parent().attr('id');
                if ($(this).attr('src').indexOf(p.markClosedImg) >= 0) {
                    if (confirm(p.closeMsg + '?: ' + ro)) {
                        $.ToggleMarkAsComplete({
                            roNumber: ro,
                            runBeforeSend: function() { $(rowId + ' td img').attr('src', p.processingImg); },
                            runOnSuccess: function(msg) { },
                            runOnError: function(msg) { alert(msg); },
                            runWhenStarted: function() { },
                            runWhenComplete: function() { $(rowId + ' td img').attr('src', p.markOpenImg).attr('alt', p.openMsg); $(rowId).hide('slow'); }
                        });
                    }
                }
                else {
                    if (confirm(p.openMsg + '?: ' + ro)) {
                        $.ToggleMarkAsComplete({
                            roNumber: ro,
                            runBeforeSend: function() { $(rowId + ' td img').attr('src', p.processingImg); },
                            runOnSuccess: function(msg) { },
                            runOnError: function(msg) { alert(msg); },
                            runWhenStarted: function() { },
                            runWhenComplete: function() { $(rowId + ' td img').attr('src', p.markClosedImg).attr('alt', p.closeMsg); $(rowId).hide('slow'); }
                        });
                    }
                }
            });
        }; //end AppendToggleToGrid

        $.RepairOrderGrid = function(p) {
            p = $.extend({
                errorContainer: '#errorContainer',
                errorGeneralMsg: 'an error has occured',
                errorAuthMsg: 'authentication was invalid',
                errorTimeoutMsg: 'response timed out',
                errorNoDataMsg: 'no data',
                gridContainer: '#dataContainer',
                roType: 'open',
                responseTimeout: 30000,
                roNumberLabel: 'RO Number',
                targetDateLabel: 'Target Date',
                refinishHoursLabel: 'Refinish Hours',
                vehicleLabel: 'Vehicle',
                runWhenComplete: function() { },
                excludeRO: ''
            }, p);

            $(p.errorContainer).hide();
            $(p.gridContainer).html('<p style="background-color:White;" class="aligncenter">Processing... <img src="/Resources/progressindicator.gif" /></p>');

            if (p.roType == 'open') {
                p.method = 'getopenrolist';
                p.datePassDueClass = 'PastDueDate';
            }
            else {
                p.method = 'getcompletedrolist';
                p.datePassDueClass = '';
            }

            $.ajax({
                url: "/HttpHandlers/ManagementSystemAsync.ashx?method=" + p.method,
                dataType: "json",
                timeout: p.responseTimeout,
                error: function(response, textStatus, errorThrown) {
                    if (response.status > 0 || response.statusText == 'timeout') {
                        var errorMsg = p.errorGeneralMsg;
                        if (response.status == 501) {
                            errorMsg = p.errorAuthMsg;
                        }
                        if (response.statusText == 'timeout') {
                            errorMsg = p.errorTimeoutMsg;
                        }
                        $(p.errorContainer).html('<p class="mgmtSystemError">' + errorMsg + '</p>');
                        $(p.errorContainer).show('fast');
                        $(p.gridContainer).hide('fast');
                    }
                },
                success: function(data) {
                    $(p.gridContainer).html($.CreateTableFromJson({
                        columns: [
                                    { display: p.roNumberLabel, name: 'RONumber', type: 'url', url: '/SearchResults/RepairOrderPage.aspx?Id={val}&amp;SearchType=14', sort: 'desc' },
                                    { display: p.vehicleLabel, name: 'VehicleDescription' }
                                ],
                        theme: 'wideTable',
                        data: data,
                        nodatamsg: p.errorNoDataMsg,
                        rowPrefix: p.roType
                    }));
                    $.AppendToggleToGrid({ container: p.gridContainer, initialState: p.roType });
                    $.RemoveROFromGrid({ container: p.gridContainer, ro: p.excludeRO });

                    p.runWhenComplete();
                }
            }); //end ajax
        }; //end RepairOrderGrid


    });
})(jQuery);
