﻿/*
    Russell Gallery
    Featured ad gallery for home page

*/
(function($) {

    $.fn.russellGallery = function(options) {
        // Global vars
        var cookie = null;
        var topBuckets = new Array();
        var finalArray = new Array();
        var allBuckets = new Array();
        var catchAll = null;
        var imgPathPrefix = './_ui/img/gallery/';
        var userBucketInvalid = false;
        var tmpArray = new Array();

        // User controlled options
        var o = jQuery.extend({
            bucketPriority: "",      /* Bucket to be shown first - use value of <ul> id in RussellGallery.html*/
            singleBucket: ""         /* Show only this bucket - use value of <ul> id in RussellGallery.html.  Takes priority over other options */

        }, options);

        return this.each(function() {
            //FUNCTIONS LIST
            /*
            1.  Determine if cookie is set
            2.  Display cookie items
            3.  Check for only Bucket
            4.  Check for bucket priority
            5.  Randomize top folders
            6.  Randomize catch all bucket folders
            */

            function init() {
                cookie = checkCookie();
                if (cookie) {
                    itemsToDisplay = processCookie(cookie);
                    constructView(itemsToDisplay);
                }
                else {
                    if (o.singleBucket) {
                        itemsToDisplay = randomizeBucketSingle();
                        if (userBucketInvalid) {// if user option is not availble default to all
                            itemsToDisplay = randomizeBucketsAll();
                        }
                        constructView(itemsToDisplay);
                        set_cookie("userVisit", itemsToDisplay);
                    }
                    else {
                        if (o.bucketPriority) {
                            itemsToDisplay = randomizeBucketsPriority();
                            if (userBucketInvalid) {// if user option is not availble default to all
                                itemsToDisplay = randomizeBucketsAll();
                            }
                            constructView(itemsToDisplay);
                            set_cookie("userVisit", itemsToDisplay);

                        }
                        else {
                            itemsToDisplay = randomizeBucketsAll();
                            constructView(itemsToDisplay);
                            set_cookie("userVisit", itemsToDisplay);
                        }
                    }
                }
            }
            // Build the HTML to display the items
            function constructView(items) {
                target = '';

                for (i = 0; i < items.length; i++) {
                    selector = "#" + items[i];
                    img = $(selector).children('a').children('img').attr('src');
                    link = $(selector).children('a').attr('href');
                    alt = $(selector).children('a').children('img').attr('alt');
                    target = $(selector).children('a').attr('target');
                    $("#galleryDisplay").append('<a href="' + link + '" target="' + target + '"><img src="' + imgPathPrefix + img + '" alt="' + alt + '"  /></a>');
                }
                // if only 1 item or less, hide the prev and next arrows
                if (items.length <= 1) {
                    $("#prev,#next").hide();
                }
            }
            function set_cookie(name, items) {
                cookieValue = '';
                for (i = 0; i < items.length; i++) {
                    if (i == 0) {
                        cookieValue += items[i];
                    }
                    else {//separate item ids with comma
                        cookieValue += "," + items[i];
                    }
                }
                var cookie_string = name + "=" + escape(cookieValue);
                document.cookie = cookie_string;
            }

            function getCookie(c_name) {

                if (document.cookie.length > 0) {

                    c_start = document.cookie.indexOf(c_name + "=");
                    if (c_start != -1) {
                        c_start = c_start + c_name.length + 1;
                        c_end = document.cookie.indexOf(";", c_start);
                        if (c_end == -1) c_end = document.cookie.length;

                        return unescape(document.cookie.substring(c_start, c_end));
                    }
                }
                else {
                    return false;
                }
            }
            function checkCookie() {
                galleryCookie = getCookie('userVisit');
                return galleryCookie;
            }

            function processCookie(cookie) {
                cookieArray = new Array();
                cookieArray = cookie.split(",");
                return cookieArray;
            }

            //  Randomization 
            function randOrder() {
                return (Math.round(Math.random()) - 0.5);
            }

            //  User selected option to display only a single bucket
            function randomizeBucketSingle() {

                $("#" + o.singleBucket).find('li').each(function() {
                    tmpArray.push($(this).attr("id"));
                });
                if (tmpArray == '') {
                    userBucketInvalid = true;
                }
                // randomly sort the items from each bucket
                tmpArray.sort(randOrder);

                for (i = 0; i < tmpArray.length; i++) {
                    if (i == 4) {// stop after 4 items
                        break;
                    }
                    else {
                        finalArray.push(tmpArray[i]);
                    }
                }
                return finalArray;
            }

            // User selected option to display one bucket as a priority (show first).
            function randomizeBucketsPriority() {
                // Find the buckets and get the id's into a list to be sorted
                $("#russellGallery > ul").each(function() {
                    allBuckets.push($(this).attr('id'));
                });

                // Since priority, loop through all top buckets to see if it's in the top level.  Possibly in second level.
                for (i = 0; i < allBuckets.length; i++) {
                    b = $.trim(allBuckets[i].toLowerCase());
                    bp = $.trim(o.bucketPriority.toLowerCase());
                    if (b == bp) {
                        catchAll = false;
                        break;
                    }
                    else {
                        catchAll = true;
                    }
                }

                // Get an array of all but the priority bucket to be randomized
                $("#russellGallery > ul").each(function() {

                    if (catchAll) {  // if priority bucket is a bucket inside catchAll bucket
                        if ($(this).attr('id') != "catchall-bucket") {
                            topBuckets.push($(this).attr('id'));
                        }
                    }
                    else if ($(this).attr('id') != o.bucketPriority) {
                        topBuckets.push($(this).attr('id'));
                    }
                });
                // Sort the buckets by randomization
                topBuckets.sort(randOrder);

                //Add priority bucket to beginning of array
                if (catchAll) {
                    topBuckets.unshift("catchAll");
                }
                else {
                    topBuckets.unshift(o.bucketPriority);
                }

                // Now we have array with topBuckets in random order except priority bucket is first
                // Go through the new bucket order to get id for item from each
                for (i = 0; i < topBuckets.length; i++) {

                    // Find again, but this time with the new random order we created
                    $("#russellGallery > ul[id='" + topBuckets[i] + "']").each(function() {
                        tmpArray = [];
                        // need to go a level down to sort the priority bucket in catchAll if true
                        if (topBuckets[i] == 'catchall-bucket' && catchAll) {
                            $("#" + o.bucketPriority).find('li').each(function() {
                                tmpArray.push($(this).attr("id"));
                            });
                            if (tmpArray == '') {
                                userBucketInvalid = true;
                                return false;
                            }
                            // randomly sort the items from each bucket
                            tmpArray.sort(randOrder);
                        }
                        else {
                            $(this).find('li').each(function() {
                                tmpArray.push($(this).attr("id"));
                            });
                            // randomly sort the items from each bucket
                            tmpArray.sort(randOrder);
                        }
                        // add the first item to the final array
                        finalArray.push(tmpArray[0]);
                    });
                }
                return finalArray;
            }
            function randomizeBucketsAll() {
                // clear arrays if coming from another function via error path
                topBuckets = [];
                tmpArray = [];
                finalArray = [];

                // Find the buckets and get the id's into a list to be sorted
                $("#russellGallery > ul").each(function() {
                    topBuckets.push($(this).attr('id'));
                });

                // Sort the buckets by randomization
                topBuckets.sort(randOrder);

                // Go through the new bucket order
                for (i = 0; i < topBuckets.length; i++) {
                    // Find again, but this time with the new random order
                    $("#russellGallery > ul[id='" + topBuckets[i] + "']").each(function() {
                        tmpArray = [];
                        $(this).find('li').each(function() {
                            tmpArray.push($(this).attr("id"));
                        });
                        tmpArray.sort(randOrder);
                        finalArray.push(tmpArray[0]);
                    });
                }
                return finalArray;
            }

            // Initialization
            init();
        });

    }; //end plugin
})(jQuery);
