/*
File: plugins.js

About: Version
	0.1

Description:
	custom jQuery plugins for maybelline.com

Requires:
	- jQuery 1.4.2+ <jquery.js> <http://jquery.com>

*/

//private functions

function sortAlpha(a, b) {
 
    return $(a).find('a').text() > $(b).find('a').text() ? 1 : -1;
};


// create a closure
(function ($) {

    $.fn.randomizeBackground = function (options){
        var imageHolder = $(this),
            defaults = {
                backgroundImages:"",
                fadeIn:false,
                speed:750
            };

        // Extend our default options with those provided.
        var opts = $.extend(defaults, options);

        var backgroundArr = opts.backgroundImages.split(","),
            i = Math.floor(Math.random() * backgroundArr.length),
            image = $("<img src='' id='bg-image'/>");

            image.attr("src", backgroundArr[i]).load(function () {

                if (opts.fadeIn){
                    imageHolder.css({"background-image": "url(" + backgroundArr[i] + ")" }).animate({ "opacity": 1 }, opts.speed);
                }else{
                    imageHolder.css({"background-image": "url(" + backgroundArr[i] + ")","opacity":1});
                }
            });
    };


    /**
    Scroll to Top

    When called it will scroll the user to the top (or given ID) instead of jumping back up
    */
    $.fn.scrollToPosition = function (options) {
        var defaults = {
            position:"#header" // scroll to the top of the page;
        };

        // Extend our default options with those provided.
        var opts = $.extend(defaults, options);

        $(this).live("click", function(e){
            e.preventDefault();
            var offset =  $(opts.position).offset();
            $("html, body").animate({scrollTop:offset.top}, "slow")
        });
    };

    /**
    Clear Default
        
    When applied to a form element, it removes the default content when the user focus and returns it
    if the user doesn't change the default.
    */
    
    $.fn.clearDefault = function () {
        $(this).each(function() {
            $(this).focus(function(){
                if($(this).val() == this.defaultValue || $(this).val() == "")
                    $(this).val('');
            });

            $(this).blur(function() {
                if($(this).val() == this.defaultValue || $(this).val() == "")
                    $(this).val(this.defaultValue);
            });
        });
    };

    /**
    Beautify Select
        
    When applied to a select form element, it clones the elememt into a UL and beautifies
    it in line with the design on the site.
    */
    $.fn.beautifySelect = function () {
        $(this).each(function () {

            // get each select based on its id
            var selectID = $(this).attr('id')
            var select = $("#" + selectID);
            var options = select.children("option");

            // add a class to the parent fieldset to give it explicit height
            $(this).parent("fieldset").addClass("beautified");

            // create markup for the replacement UL
            var ulText = "<ul class='dropdown dropdown-closed' id='beautified-" + selectID + "'>";
            options.each(function (i) {

                // parse the values to create an ID for the original select options and new li elements.
                var optionID = utilities.valueToID($(this).attr("value"));

                if (i == 0) {
                    ulText += "<li class='option default selected'>" + $(this).text() + " </li>";
                } else {
                    ulText += "<li class='option' id='" + optionID + "'>" + $(this).text() + " </li>";
                }

                // add the id to each select option
                $(this).attr("id", optionID);

            }); // end each
            ulText += "</ul>"

            // insert the newly created markup
            $(select).after(ulText);

            var ul = $("ul#beautified-" + selectID);
            ul.wrap('<div class="dropdown-wrapper"></div>');
            var ul_parent = $(this).parent(),
            listItems = ul.find('li');

            // Add default and selected classes on first item in dropdown.
            var selected_item = listItems.filter(':eq(0)').addClass('selected'),
            selectedTitle = selected_item.text(),
            selectedID = selected_item.attr('id');

            // Drop in additional first item - this will be the selected state
            var currentLi = $('<li rel="' + selectedID + '">' + selectedTitle + '</li>')
                .addClass('current')
                .prependTo(ul);

            // Remove the default from the list - it doesn't need to appear twice
            listItems.filter(':first').remove();

            // Update list items with new currentLI
            listItems = ul.find('li');

            // attach click events to the ul and each li
            ul.click(function () {
                $(this).toggleClass("dropdown-closed");
                ul_parent.toggleClass('dropdown-active');
            });

            $(document).bind('click', function (e) {
                var $clicked = $(e.target);
                if (!$clicked.parents().hasClass("dropdown")) {
                    $("ul.dropdown").addClass("dropdown-closed");
                    $('.dropdown-active').removeClass('dropdown-active');
                }
            });

            listItems.click(function (e) {
                listItems.filter('.selected').removeClass("selected");
                $(this).addClass("selected");
                if (!$(this).hasClass('current')) {
                    currentLi.attr('rel', $(this).attr('id'));
                    currentLi.text($(this).text());
                    var selected = $(this).attr('id');
                    options.each(function () {
                        if ($(this).attr("id") === selected) {
                            $(this).attr("selected", true);
                        }
                    });
                }
            }); // end click
        });

        // Add rounded corners for IE
        //DD_roundies.addRule('.dropdown', '13px');

    }; // end plugin


    /**
    Selectify Unordered Lists
        
    When applied to an unordered list element, it makes list function like a form select.
    This plugin attaches simplied versions of the event from beautifySelect

    */
    $.fn.selectifyUnorderedList = function () {
        $(this).each(function () {
            var ul = $(this),
            ul_parent = $(this).parent(),
            listItems = ul.find('li');

            ul.click(function () {
                $(this).toggleClass("dropdown-closed");
                ul_parent.toggleClass('dropdown-active');
            });

            $(document).bind('click', function (e) {
                var $clicked = $(e.target);
                if (!$clicked.parents().hasClass("dropdown")) {
                    $("ul.dropdown").addClass("dropdown-closed");
                    $('div.dropdown-active').removeClass('dropdown-active');
                }
            });

            // Add default and selected classes on first item in dropdown.
            var selected_item = listItems.filter(':eq(0)').addClass('selected'),
            selectedTitle = selected_item.text(),
            selectedID = selected_item.attr('id');

            // Drop in additional first item - this will be the selected state
            var currentLi = $('<li rel="' + selectedID + '">' + selectedTitle + '</li>')
                .addClass('current')
                .prependTo(ul);

            listItems = ul.find('li');

            listItems.click(function (e) {
                listItems.filter('.selected').removeClass("selected");
                $(this).addClass("selected");
                if (!$(this).hasClass('current')) {
                    currentLi.attr('rel', $(this).attr('id'));
                    currentLi.text($(this).text());
                }
            }); // end click

        }); // end each

        // Add rounded corners for IE
        //DD_roundies.addRule('.dropdown', '13px');

    } // end plugin


    /*
    This function loops through the result set and for each result,
    it loops through immediate children, finds the largest height,
    and applies it to the others.
    If you'd like to apply the plugin only to visible children, use
    $(".my_selector").equalizeChildHeights({only_visible_children: true})
    */
    $.fn.equalizeChildHeights = function (options) {
        settings = $.extend({ only_visible_children: false }, options);
      
        var result = $(this);
        if ($.browser.msie && $.browser.version == '6.0') {
            result.children().css("height", "auto");
        }
        else {
            result.children().css("min-height", "0px");
        }
        result.each(function () {
            if (settings.only_visible_children) {
                var childs = $(this).children(":visible")
            }
            else {
                var childs = $(this).children();
            }
            var tallest = 0;
            childs.each(function () {
                var height = $(this).outerHeight();
                if (height > tallest) tallest = height;
            });



            childs.each(function () {
                var elem = $(this);
                var remainder = elem.outerHeight() - elem.height();
                var new_height = tallest - remainder;
                if ($.browser.msie && $.browser.version == '6.0') {
                    elem.css("height", new_height + "px");
                }
                else {
                    elem.css("min-height", new_height + "px");
                }
            });
        });
    };

    //function that uses the private method at the top of the page sortAlpha
    //to sort the list of countries in the mobile dropdown (can be extended to main location selector as well)
    $.fn.sort = function () {
        return this.pushStack([].sort.apply(this, arguments), []);
    };


    // private utilities object
    var utilities = {
        valueToID: function (str) {
            str = str.toLowerCase();
            str = str.replace(" ", "-");
            return str;
        }
    }
})(jQuery);
// end closure


// Paul Irish's duck punching  to extend the jquery unique method
(function($){
    var _old = $.unique;
 
    $.unique = function(arr){
 
        // do the default behavior only if we got an array of elements
        if (!!arr[0].nodeType){
            return _old.apply(this,arguments);
        } else {
            // reduce the array to contain no dupes via grep/inArray
            return $.grep(arr,function(v,k){
                return $.inArray(v,arr) === k;
            });
        }
    };
})(jQuery);

