﻿/// <reference path="jquery-1.4.4-vsdoc.js" />
/*

this file and contents are copyright (c) Sweeney Research 2011

all rights reserved

*/

(function($) {
    $.fn.ButtonCountdown = function(e) {
        ///	<summary>
		///		adds a function to disable a button and put a countdown on it &#13;
		///	</summary>
		///	<param name="e" type="Object" optional="true">
		///		One or more of the following objects:
        ///     'seconds': countdown in seconds &#13;
		///	</param>
		///	<returns type="jQuery" />


        var self = this;

        self.btn = $(this);

        if (self.btn.length == 0) {
            return this;
        }

        self.seconds = e && e.seconds ? e.seconds : 1;
        self.buttonText = self.btn.val();

        self.btn.attr('disabled', 'disabled');

        self.timerClick = function() {
            if (self.seconds == 0) {
                self.btn.val(self.buttonText);
                self.btn.removeAttr('disabled');
            }
            else {
                self.btn.val(self.seconds + 's');
                self.seconds--;
                window.setTimeout(function() {
                    self.timerClick();
                }, 1000);
            }
        };

        self.timerClick();

        return this;
    };
    
    $.fn.HighlightRadios = function(e) {
        ///	<summary>
		///		adds a function to use css on radio buttons when they're checked &#13;
        ///     jQuery selector will include all radio buttons wanting the function
		///	</summary>
		///	<param name="e" type="Object" optional="true">
		///		One or more of the following objects:
        ///     'css': css to apply to checkboxes when selected &#13;
		///	</param>
		///	<returns type="jQuery" />


        var self = this;

        self.radios = $(this);

        self.css = e && e.css ? e.css : '';

        self.clickFunction = function(e) {
            $(e.radio).parent().addClass(self.css);

            self.otherRadios = $(":radio[name='" + e.radio.name + "'][checked=false]");

            self.otherRadios.parent().removeClass(self.css);
        };

        self.radios.click(function() {
            self.clickFunction({ radio: this });
        });

        return this;
    };
    
    $.fn.HighlightCheckboxes = function(e) {
        ///	<summary>
		///		adds a function to use css on checkboxes when they're checked &#13;
        ///     jQuery selector will include all checkboxes wanting the function
		///	</summary>
		///	<param name="e" type="Object" optional="true">
		///		One or more of the following objects:
        ///     'css': css to apply to checkboxes when selected &#13;
		///	</param>
		///	<returns type="jQuery" />


        var self = this;

        self.radios = $(this);

        self.css = e && e.css ? e.css : '';

        self.clickFunction = function(e) {
            if ($(e.radio).filter(':checked').length == 0) {
                self.parent().removeClass(self.css);
            } else {
                $(e.radio).parent().addClass(self.css);
            }
        };

        self.radios.click(function() {
            self.clickFunction({ radio: this });
        });

        return this;
    };
    
    $.fn.RandomiseColumns = function(e) {
        ///	<summary>
		///		randomise columns of a table &#13;
        ///     jQuery selector should be any id within any table wanting randomisation
		///	</summary>
		///	<param name="e" type="Object" optional="true">
		///		One or more of the following objects:
        ///     'skip': how many columns to skip (from the left) before we start randomising &#13;
        ///     'take': how many columns to randomise (from the left) &#13;
		///	</param>
		///	<returns type="jQuery" />


        var self = this;

        if ($(this).parents("table").length == 0) {
            return this;
        }

        self.table = $($(this).parents("table").get(0));

        self.cols = self.table.find("tr:nth-child(1)").find("td,th").length;

        self.skip = e && e.skip ? e.skip : 0;
        self.take = e && e.take ? e.take : self.cols - self.skip;

        self.moveCol = function(e) {
            if (e.from != e.to) {
                self.cells = self.table.find("tr > td:nth-child(" + e.from + "), tr > th:nth-child(" + e.from + ")");
                self.table.find("tr > td:nth-child(" + e.to + "), tr > th:nth-child(" + e.to + ")").each(function(i, o) {
                    $(o).before(self.cells.get(i));
                });
            }
        };

        self.rndColIdx = function() {
            self.x = self.take;
            self.rnd = self.x * Math.random();
            return Math.floor(self.rnd + self.skip + 1);
        };

        for (var i = self.skip + 1; i <= self.skip + self.take; i++) {
            self.rnd = i;
            while (self.rnd == i) {
                self.rnd = self.rndColIdx();
            }
            self.moveCol({ from: i, to: self.rnd });
        }

        return this;
    };
    
    $.fn.SingleResponseCheckboxes = function(e) {
        ///	<summary>
		///		enables checkboxes with values passed in as object to act as single response.&#13;
        ///     include all checkboxes in a collection for the function to be applied to.&#13;
        ///     multiple checkbox groups need to be run separately.&#13;
		///	</summary>
		///	<param name="e" type="Object" optional="true">
		///		One or more of the following objects:&#13;
        ///     'values': array of text values of checkboxes to enable as single response &#13;
		///	</param>
		///	<returns type="jQuery" />


        var self = this;

        self.values = e && e.values && e.values.length > 0 ? e.values : null;

        self.cbs = $(this);

        if (!self.values) {
            return this;
        }

        self.parseCheckboxes = function(e) {

            self.rb = e.rb;
            self.multiSel = false;
            self.cbs.filter(":checked").each(function() {
                if ($.inArray(this.value, self.values) == -1) {
                    self.multiSel = true;
                }
            });
            self.cbs.each(function() {
                if ($.inArray(this.value, self.values) != -1) {
                    if (self.multiSel || (this != self.rb && self.rb.checked)) {
                        this.checked = false;
                        $(this).attr('disabled', 'disabled');
                    } else {
                        $(this).removeAttr('disabled');
                    }
                }
            });
            
        };

        self.cbs.click(function() {
            self.parseCheckboxes({ rb: this });
        });

        return this;
    };
})(jQuery);

jQuery.extend({
    dragDrop: function(e) {
        ///	<summary>
		///		enables drag and drop functionality on the page and stores the names of the images in inputs
		///	</summary>
		///	<param name="e" type="Object" optional="true">
		///		One or more of the following objects:&#13;
        ///     'containerName': the name attribute of the input which contains the images at init. ALL images in the selection (appended with the suffix) will have the draggable function applied. ('Container')&#13;
        ///     'dropzone': the jQuery selector for the class of divs which will be droppable. ('.dropzone')&#13;
        ///     'dropzonenames': the names of the inputs which will contain the values of the dropped images ('Container,drop1,drop2,drop3')&#13;
        ///     'suffix': the suffix of the divs that will match the inputs ('_box')&#13;
		///	</param>
		///	<returns type="jQuery" />


        // check for jqueryui
        if (!$.ui){
            alert('DragDrop error: jQueryUI not loaded/referenced.');
            return this;
        }

        // set up variables
        var containerName = e && e.containerName ? e.containerName : 'Container';
        var dropzone = e && e.dropzone ? e.dropzone : '.dropzone';
        var dropzonenames = e && e.dropzonenames ? e.dropzonenames : 'Container,drop1,drop2,drop3';
        var suffix = e && e.suffix ? e.suffix : '_box';

        var allImages = $('#' + containerName + suffix + ' img');

        // make images draggable
        allImages.draggable({
            revert: true,
            scroll: true,
            stack: '#' + containerName + suffix + ' img'
        });
        
        // set up initial array of images
        var allImagesString = [];
        $.each(allImages, function () {
            allImagesString.push(
                $(this).attr('src').match(/[^/]+$/)[0]
            );
        });
        $('input[name="' + containerName + '"]').val(allImagesString.join(','));

        // make zones droppable and 
        // revert images to former position if they're not dropped in a zone
        $(dropzone).droppable({
            tolerance: 'fit',
            over: function (event, ui) {
                $(ui.draggable).draggable('option', 'revert', false);
            },
            out: function (event, ui) {
                $(ui.draggable).draggable('option', 'revert', true);
            },
            drop: function (event, ui) {
            
                var picName = $(ui.draggable).attr('src').match(/[^/]+$/)[0];
                    
                var txtName = $(this).attr('id').replace(suffix, '');

                var names = dropzonenames.split(',');

                for (var i = 0; i < names.length; i++) {
                    names[i] = 'input[name="' +  names[i] + '"]'; 
                }

                // remove the picture from any current lists
                $.each($(names.join(',')), function() {
                    var arr = $(this).val() == '' ? [] : $(this).val().split(',');
                    var idx = $.inArray(picName, arr);
                    if (idx > -1) {
                        arr.splice(idx, 1);
                    }
                    $(this).val(arr.join(','));
                });

                // add item everytime its dropped into the box
                var currList = $('input[name="' + txtName + '"]').val() == '' ? [] : $('input[name="' + txtName + '"]').val().split(',');
                currList.push(picName);
                $('input[name="' + txtName + '"]').val(currList.join(','));
            }
        });

        return this;
    },

    rangeAlignment: function (id,html) {
        ///	<summary>
        ///		aligns range codes horizontally rather than vertically
        ///	</summary>
        var $tr = $('input[name=' + id + ']:first').parents('table:eq(1)').parents('tr:first');

        $tr
            .find('td:first')
            .css('text-align','right')
            .css('padding-right','50px')
            .clone()
            .appendTo($tr)
            .css('text-align','left')
            .find('span')
            .html(html);


        return this;
    }

});
