/*
 * JQuery imgRandom Plugin
 * Copyright (c) 2009 Mathieu Meylan
 * Version: 1.1 (15-FEV-2010)
 *
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 * Requires: jQuery v1.2.6 or later
 *
 * changelog:
 * 1.0 : first release
 * 1.1 : added multi boxes by pages
 *
 * This plugin permit to display group of images randomly on each load of the page efficiency
 * on a given container by using cookie to be sure you don't redisplay the same image!
 *
 * Usage:
 *
 */

/*

   $(function () {
       // minimum 3 images !!!
       $('#promo1_random').imgRandom ({
           image_width: 310,
           image_height: 125,
           // not mandatory if you use the full URL on the image path below
           images_path: '/images/random/',
           images: [
               [
                   'http://www.google.com/',   // link
                   'look on google.com',          // link title
                   'google.png'                       // image or image with path
               ],
               [
                   '/link2/',
                   'title2',
                   'image2.png'
               ],
               [
                   '/link3.php',
                   'my title 3',
                   'link3.png'
               ]
            ]
        });
    });

 */

/*
 * HTML example:
 * <span id="promo1_random"><!-- random image box -></span>
 *
 *
 * Notices:
 *  * no constraint about (here span#promo1_random) the random image container: p, span, div, etc
 *  * but always use 'id' (not class)!
 *  * container (here span#promo1_random) is empty by this script!
 *  * use minimum of 3 images to become useful
 *  * you be able to used more then one box by page (one cookie by box, don't abuse!)
 */

;(function(jQuery) {

    // Cookie plugin based on the work of Peter-Paul Koch - http://www.quirksmode.org
    var Cookie = {
        set: function (name, value) {
            var expires = '', options = arguments[2] || {}, date;
            if (options.duration) {
                date = new Date();
                date.setTime(date.getTime() + options.duration * 1000 * 60 * 60 * 24);
                value += '; expires=' + date.toGMTString();
            }
            document.cookie = name + "=" + value + expires + "; path=/";
        },

        remove: function (name) {
            this.set(name, '', -1);
        },
        get: function (name) {
            var cookies = document.cookie.split(';'), nameEQ = name + "=", i, l, c;
            for (i = 0, l = cookies.length; i < l; i++) {
                c = cookies[i];
                while (c.charAt(0) === ' ') {
                    c = c.substring(1, c.length);
                }
                if (c.indexOf(nameEQ) === 0) {
                    return c.substring(nameEQ.length, c.length);
                }
            }
            return null;
        }
    };

    // Plugin imgRandom
    jQuery.fn.imgRandom = function(options) {
        // support mutltiple elements
        if (this.length > 1) {
            this.each(function() { jQuery(this).imgRandom(options); });
            return this;
        }

        var default_options = {
            image_width: 100,
            image_height: 100,
            images_path: '', // use only if all images come from the same path
            images: []
        };
        options = jQuery.extend({}, default_options, options);

        if (options.images === undefined || options.images.length < 3) {
            if (window.console && window.console.log) {
                window.console.log('[imgRandom] "images" list option not defined (min 3 images)!');
            }
            return;
        }
        var number = options.images.length; //total number of images
        var cashe_limit = number -1; //how many to keep in memory (cookie)

        this.cookiesEnabled = function (test) {
            if (Cookie.get(test)) {
                return true;
            }
            Cookie.set(test, 'test', { duration: 15 });
            return Cookie.get(test);
        };

        this.checkRandomNumber = function(base, array) {
            var num = Math.ceil(Math.random() *base);

            for(var i=0; i <array.length; i++) {
                if(Number(array[i]) == num) {
                    num = this.checkRandomNumber(base, array);
                }
            }
            return num;
        };

        this.getRandomNumber = function() {
            var random_number, cookie_array = Array(), cookie_string ='';
            if(this.cookiesEnabled && Cookie.get('_imgRandom_'+this.attr('id'))) {
                cookie_array = Cookie.get('_imgRandom_'+this.attr('id'));
                cookie_array = cookie_array.split("|");
                if(cookie_array.length >= cashe_limit) {
                    cookie_array.shift();
                }
                random_number = this.checkRandomNumber(number, cookie_array);

            } else {
                random_number = Math.ceil(Math.random() *number);
            }
            cookie_array.push(random_number);

            for(var i=0; i < cookie_array.length; i++) {
                cookie_string += cookie_array[i];
                if(i < cookie_array.length -1) {
                    cookie_string += '|';
                }
            }
            Cookie.set('_imgRandom_'+this.attr('id'), cookie_string);

            return random_number;
        };

        this.intialize = function() {
            // support MetaData plugin
            if(jQuery.meta) {
                options = jQuery.extend({}, options, this.data());
            }
            var random_number_id = this.getRandomNumber() -1;
            this.empty().append('<a href="'+options.images[random_number_id][0]+'" title="'+options.images[random_number_id][1]+'">'+'<img src="'+options.images_path+options.images[random_number_id][2]+'.jpg" alt="'+options.images[random_number_id][1]+'" width="'+options.image_width+'" height="'+options.image_height+'" /></a>');
        };

        this.getOptions = function() {
            return options;
        };

        // start the job
        return this.intialize();
    };

}(jQuery));
