﻿/**
 * Common methods plugin
 * by Brandon Goldman
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 */

(function($) {
    $.extend({
        //returns today's date
        dateToday: function() {
            var d = new Date;
            var month = d.getMonth() + 1;
            var day = d.getDate();
            var year = d.getFullYear();
            return month + '/' + day + '/' + year;
        },
        
        //reloads the current page
        reload: function() {
            window.location.reload();
        },
    
        //returns the requested GET parameter from the URL
        url: function(param) {
            var regex = '[?&]' + param + '=([^&#]*)';
            var results = (new RegExp(regex)).exec(window.location.href);
            if(results) return results[1];
            return '';
        },
    
        //opens a new window given the url and window name
        window: function(url, name, width, height) {
            var width = width || screen.width / 2;
            var height = height || screen.height / 2;
            var left = (screen.width - width) / 2;
            var top = (screen.height - height) / 2;
            features = 'channelmode=0,dependent=0,directories=0,fullscreen=0,location=1,menubar=0,resizable=1,scrollbars=1,status=1,toolbar=1';    
            var params = 'width={0},height={1},left={2},top={3},{4}'.format(width, height, left, top, features);
            win = open(url, name, params);
            win.focus();
            return win;
        },
        
        //closes any window given the window name
        windowClose: function(name) {
            open('', name, '').close();
        }
    });
    
    //protects a form from spammers by adding a field and optional token for the server-side form processing to verify against
    $.fn.protectForm = function(params) {
        params = params || {};
        var fieldName = params.fieldName || '__protect';
        var token = params.token || (Math.floor(Math.random() * (1 + 99999999 - 11111111)) + 11111111);
        var submitNow = false;
        this.submit(function() {
            if(submitNow == true) return true;
            var input = $('<input type="hidden" />').attr('name', fieldName).val(token);
            $(this).append(input);
            submitNow = true;
            this.submit();
            return false;
        });
    };

    //adds zebra stripes and a hover stripe to the selected tables
    $.fn.zebraTables = function(rowEven, rowHover) {
        rowEven = rowEven || 'row_even';
        rowHover = rowHover || 'row_hover';
        $('tr:even', this).addClass(rowEven);
        $('tr', this).mouseover(function() {
            $(this).addClass(rowHover);
        }).mouseout(function() {
            $(this).removeClass(rowHover);
        });
    };
})(jQuery);