﻿///<reference path="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.6-vsdoc.js" />

//######
//## This work is licensed under the Creative Commons Attribution-Share Alike 3.0 
//## United States License. To view a copy of this license, 
//## visit http://creativecommons.org/licenses/by-sa/3.0/us/ or send a letter 
//## to Creative Commons, 171 Second Street, Suite 300, San Francisco, California, 94105, USA.
//######

(function ($) {
    $.fn.idleTimeout = function (options) {
        var defaults = {
            inactivity: 1200000, //20 Minutes
            noconfirm: 15000, //15 Seconds
            sessionAlive: 1200000, //20 Minutes
            redirect_url: '/js_sandbox/',
            click_reset: true,
            alive_url: '/js_sandbox/',
            logout_url: '/js_sandbox/'
        }

        //##############################
        //## Private Variables
        //##############################
        var opts = $.extend(defaults, options);
        var liveTimeout, confTimeout, sessionTimeout;
        var modal = "<div id='modal_pop'><p>You are about to be signed out due to inactivity.</p></div>";
        //##############################
        //## Private Functions
        //##############################
        var start_liveTimeout = function () {
            clearTimeout(liveTimeout);
            clearTimeout(confTimeout);
            liveTimeout = setTimeout(logout, opts.inactivity);

            if (opts.sessionAlive) {
                clearTimeout(sessionTimeout);
                sessionTimeout = setTimeout(keep_session, opts.sessionAlive);
            }
        }

        var logout = function () {

            confTimeout = setTimeout(redirect, opts.noconfirm);
            $(modal).dialog({
                buttons: { "Stay Logged In": function () {
                    $(this).dialog('close');
                    stay_logged_in();
                }
                },
                modal: true,
                title: 'Auto Logout'
            });
        }

        var redirect = function () {
            if (opts.logout_url) {
                $.get(opts.logout_url);
            }
            window.location.href = opts.redirect_url;
        }

        var stay_logged_in = function (el) {
            start_liveTimeout();
            if (opts.alive_url) {
                $.get(opts.alive_url);
            }
        }

        var keep_session = function () {
            $.get(opts.alive_url);
            clearTimeout(sessionTimeout);
            sessionTimeout = setTimeout(keep_session, opts.sessionAlive);
        }

        //###############################
        //Build & Return the instance of the item as a plugin
        // This is basically your construct.
        //###############################
        return this.each(function () {
            obj = $(this);
            start_liveTimeout();
            if (opts.click_reset) {
                $(document).bind('click', start_liveTimeout);
            }
            if (opts.sessionAlive) {
                keep_session();
            }
        });
    };
})(jQuery);

//jquery collapsible panel plugin
(function ($) {
    $.fn.extend({
        collapsiblePanel: function () {
            // Call the ConfigureCollapsiblePanel function for the selected element
            return $(this).each(ConfigureCollapsiblePanel);
        }
    });

})(jQuery);

function ConfigureCollapsiblePanel() {
    $(this).addClass("ui-widget");

    // Check if there are any child elements, if not then wrap the inner text within a new div.
    if ($(this).children().length == 0) {
        $(this).wrapInner("<div></div>");
    }

    // Wrap the contents of the container within a new div.
    $(this).children().wrapAll("<div class='collapsibleContainerContent ui-widget-content'></div>");

    // Create a new div as the first item within the container.  Put the title of the panel in here.
    $("<div class='collapsibleContainerTitle ui-widget-header'><div>" + $(this).attr("title") + "</div></div>").prependTo($(this));

    // Assign a call to CollapsibleContainerTitleOnClick for the click event of the new title div.
    $(".collapsibleContainerTitle", this).click(CollapsibleContainerTitleOnClick);
}

function CollapsibleContainerTitleOnClick() {
    // The item clicked is the title div... get this parent (the overall container) and toggle the content within it.
    $(".collapsibleContainerContent", $(this).parent()).slideToggle();
}

$.fn.clearForm = function () {
    return this.each(function () {
        var type = this.type, tag = this.tagName.toLowerCase();
        if (tag == 'form') return $(':input', this).clearForm();
        if (type == 'text' || type == 'password' || tag == 'textarea') this.value = '';
        else if (type == 'checkbox' || type == 'radio') this.checked = false;
        else if (tag == 'select') this.selectedIndex = 0;
    });
};

$.fn.disableForm = function () {
    return this.each(function () {
        var type = this.type, tag = this.tagName.toLowerCase();
        if (tag == 'form') return $(':input', this).disableForm();
        if (type == 'text' || type == 'password' || tag == 'textarea' ||
			type == 'file' || type == 'checkbox' || type == 'radio' || tag == 'select') $(this).attr('disabled', 'disabled');

    });
};

$.fn.enableForm = function () {
    return this.each(function () {
        var type = this.type, tag = this.tagName.toLowerCase();
        if (tag == 'form') return $(':input', this).enableForm();
        if (type == 'text' || type == 'password' || tag == 'textarea' ||
			type == 'file' || type == 'checkbox' || type == 'radio') $(this).removeAttr('disabled');
        else if (tag == 'select') $(this).disabled = false;
    });
};

$.fn.clearDefault = function () {
    return this.each(function () {
        var default_value = $(this).val();
        $(this).focus(function () {
            if ($(this).val() == default_value) $(this).val("");
        });
        $(this).blur(function () {
            if ($(this).val() == "") $(this).val(default_value);
        });
    });
};

function setModalDialog(dialogSelector) {

    $(dialogSelector).dialog({
        autoOpen: false,
        modal: true,
        resizable: false,
        buttons: {
            "Ok": function () {
                $(this).dialog('close');
            }
        }
    });
}

function loadMCE(textAreaSelector, mceWidth, mceHeight) {
    $(textAreaSelector).tinymce({
        // Location of TinyMCE script
        script_url: 'Scripts/tiny_mce/tiny_mce.js',

        // General options
        theme: "advanced",
        skin: "o2k7",
        skin_variant: "silver",
        width: mceWidth,
        height: mceHeight,
        plugins: "safari,autolink,lists,pagebreak,style,layer,table,save,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template,advlist",

        // Theme options
        theme_advanced_buttons1: "bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,formatselect,fontsizeselect",
        theme_advanced_buttons2: "cut,copy,paste,pastetext,pasteword,|,search,replace,|,bullist,numlist,|,outdent,indent,blockquote,|,undo,redo,|,forecolor,backcolor",
        theme_advanced_buttons3: "tablecontrols,|,hr,removeformat,visualaid,|,sub,sup",
        theme_advanced_toolbar_location: "top",
        theme_advanced_toolbar_align: "left",
        theme_advanced_statusbar_location: "bottom",
        theme_advanced_resizing: true
    });
}


function loadMCENoCommands(textAreaSelector, mceWidth, mceHeight) {
    $(textAreaSelector).tinymce({
        // Location of TinyMCE script
        script_url: 'Scripts/tiny_mce/tiny_mce.js',

        // General options
        theme: "advanced",
        skin: "o2k7",
        skin_variant: "silver",
        width: mceWidth,
        height: mceHeight,
        plugins: "safari,autolink,lists,pagebreak,style,layer,table,save,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template,advlist",

        // Theme options
        theme_advanced_buttons1: "bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull",
        theme_advanced_buttons2: "",
        theme_advanced_toolbar_location: "top",
        theme_advanced_toolbar_align: "left",
        theme_advanced_statusbar_location: "bottom",
        theme_advanced_resizing: true
    });
}

function loadHTMLMCE(textAreaSelector, mceWidth, mceHeight) {
    $(textAreaSelector).tinymce({
        // Location of TinyMCE script
        script_url: 'Scripts/tiny_mce/tiny_mce.js',

        // General options
        theme: "advanced",
        skin: "o2k7",
        skin_variant: "silver",
        width: mceWidth,
        height: mceHeight,
        plugins: "safari,autolink,lists,pagebreak,style,layer,table,save,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template,advlist",

        // Theme options
        theme_advanced_buttons1: "bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,formatselect,fontsizeselect",
        theme_advanced_buttons2: "cut,copy,paste,pastetext,pasteword,|,search,replace,|,bullist,numlist,|,outdent,indent,blockquote,|,undo,redo,|,forecolor,backcolor",
        theme_advanced_buttons3: "tablecontrols,|,hr,removeformat,visualaid,|,sub,sup,|,code",
        theme_advanced_toolbar_location: "top",
        theme_advanced_toolbar_align: "left",
        theme_advanced_statusbar_location: "bottom",
        theme_advanced_resizing: true
    });
}

//$.fn.row = function (i) { return $('tr:nth-child(' + (i + 1) + ') td', this); }
//$.fn.column = function (i) { return $('tr td:nth-child(' + (i + 1) + ')', this); }

function changeCheckBoxState(checkboxID) {

    checkboxID = "#" + checkboxID;
    $(checkboxID)[0].checked = !$(checkboxID)[0].checked;
}

function ToJsnString(o) { return encodeURIComponent(JSON.stringify(o)); }

//found on stack overflow http://stackoverflow.com/questions/901115/get-query-string-values-in-javascript/5158301#5158301
function getParameterByName(name) {

    var match = RegExp('[?&]' + name + '=([^&]*)').exec(window.location.search);

    return match && decodeURIComponent(match[1].replace(/\+/g, ' '));
}

/* Set up of Dialog boxes */
function showModalDialog(dialogSelector) { $(dialogSelector).dialog('open'); }

function closeModalDialog(dialogSelector) { $(dialogSelector).dialog('close'); }

/* OK message dialog */

function showModalDialog2(dialogSelector, headerText, dialogText) {

    $(dialogSelector).dialog("option", "title", headerText);
    $(dialogSelector + ' p').html(dialogText);
    $(dialogSelector).dialog('open');
}

function showDialogWithRedirectOnClose(dialogSelector, headerText, dialogText, pageToRedirect) {

    showModalDialog2(dialogSelector, headerText, dialogText);

    $(dialogSelector).bind('dialogclose', function (event) {
        window.location.replace(pageToRedirect);
    });
}

function createFormPopup(dialogSelector, width, dialogTitle, buttons) {

    $(dialogSelector).dialog({ title: dialogTitle, buttons: buttons, width: width, height: 'auto' });
    $(dialogSelector).dialog('open');
    $(dialogSelector).parent().appendTo($('#form1'));
}

/* methjod to do ajax posting */
function doAjaxPost(url, asyncronous, datastring) {

    var rt = false;

    $.ajax({
        type: "POST",
        async: asyncronous,
        url: url,
        data: datastring,
        success: function (msg) {
            if (msg == "") {
                rt = true;
            }
            else {
                rt = eval("(" + msg + ")");
            }
        },
        error: function () {
            return false;
        }
    }).responseText;

    return rt;
}

function addDefaultToDropDown(dropDownSelector, text, value) {

    $(dropDownSelector).get(0).options.length = 0;
    $(dropDownSelector).get(0).options[0] = new Option(text, value);
}

/* Paging methods */
function initPagination(pageSelector, numButtonsEdge, numButtonsDisplay, totalEntries, callbackFunction, itemsPerPage) {

    $(pageSelector).pagination(totalEntries,
			{ num_edge_entries: numButtonsEdge,
			    num_display_entries: numButtonsDisplay,
			    callback: callbackFunction,
			    items_per_page: itemsPerPage
			});
}

function formatJSONDate(jsonDate, format) {
    var date = eval(jsonDate.replace(/\/Date\((\d+)\)\//gi, "new Date($1)"));
    var newDate = dateFormat(date, format);
    return newDate;
}

function loadDateControls(textBoxSelector) {

    $(textBoxSelector).datepicker({
        showOn: 'both',
        showWeek: true,
        buttonImage: 'images/calendar.png',
        buttonImageOnly: true,
        numberOfMonths: 1,
        changeMonth: true,
        changeYear: true,
        showButtonPanel: true,
        dateFormat: 'dd/mm/yy',
        minDate: 1
    });
};

function loadOpenDateControls(textBoxSelector) {

    $(textBoxSelector).datepicker({
        showOn: 'both',
        showWeek: true,
        buttonImage: 'images/calendar.png',
        buttonImageOnly: true,
        numberOfMonths: 1,
        changeMonth: true,
        changeYear: true,
        showButtonPanel: true,
        dateFormat: 'dd/mm/yy'
    });

};

function FormatAsCurrency(amount) {
    var i = parseFloat(amount);
    if (isNaN(i)) { i = 0.00; }
    var minus = '';
    if (i < 0) { minus = '-'; }
    i = Math.abs(i);
    i = parseInt((i + .005) * 100);
    i = i / 100;
    s = new String(i);
    if (s.indexOf('.') < 0) { s += '.00'; }
    if (s.indexOf('.') == (s.length - 2)) { s += '0'; }
    s = minus + s;
    return s;
};

function CommaFormatted(amount) {
    var delimiter = ","; // replace comma if desired
    var a = amount.split('.', 2)
    var d = a[1];
    var i = parseInt(a[0]);
    if (isNaN(i)) { return ''; }
    var minus = '';
    if (i < 0) { minus = '-'; }
    i = Math.abs(i);
    var n = new String(i);
    var a = [];
    while (n.length > 3) {
        var nn = n.substr(n.length - 3);
        a.unshift(nn);
        n = n.substr(0, n.length - 3);
    }
    if (n.length > 0) { a.unshift(n); }
    n = a.join(delimiter);
    if (d.length < 1) { amount = n; }
    else { amount = n + '.' + d; }
    amount = minus + amount;
    return amount;
}

function padLeft(number, width) {
    width -= number.toString().length;
    if (width > 0) {
        return new Array(width + (/\./.test(number) ? 2 : 1)).join('0') + number;
    }
    return number;
}

function S4() {
    return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
}

function guid() {
    return (S4() + S4() + "-" + S4() + "-" + S4() + "-" + S4() + "-" + S4() + S4() + S4());
}

function getDayOfWeek(intday) {
    switch (intday) {
        case -1: return "All Week"; break;
        case 0: return "Sunday"; break;
        case 1: return "Monday"; break;
        case 2: return "Tuesday"; break;
        case 3: return "Wednesday"; break;
        case 4: return "Thursday"; break;
        case 5: return "Friday"; break;
        case 6: return "Saturday"; break;
    }
}

function getShortMonth(intMonth) {
    switch (intMonth) {
        case 1: return "JAN"; break;
        case 2: return "FEB"; break;
        case 3: return "MAR"; break;
        case 4: return "APR"; break;
        case 5: return "MAY"; break;
        case 6: return "JUN"; break;
        case 7: return "JUL"; break;
        case 8: return "AUG"; break;
        case 9: return "SEP"; break;
        case 10: return "OCT"; break;
        case 11: return "NOV"; break;
        case 12: return "DEC"; break;
    }
}

