/*  A to Z Scroll
 *  (c) 2010 Vinh Do <vdo@esolutionsgroup.ca>
 *
 *  09/22/2010
 *
 *  _height: height of container
 *  _width: width of container
 *  _speed: the scrolling speed
 *  _margin: not really margin, just use for calculating edge and stuff
 *  _padding: padding for trigger anchor tags
 *  _trigger: enable and disable trigger
 *  _location: location of trigger (top or bottom)
 *  _id: the id for creating classes (probably will never change)
 *  _url: the url to use for the all tag in trigger (all only show up when there's a url)
 *  _reverse: reverse the direction of the scroll (some say the scrolling is wrong, LOL)
 *  _source: JSON data source (primary source of data, will override _data)
 *  _data: array data source (secondary source of data)
 *  _itemPerColumn: number of items per unorder list
 */
(function($){
    $.fn.atoz_index = function(p) {

		var p=p||{};

		var _source = p && p.source ? p.source : "",
			_headerTag = p && p.headerTag ? p.headerTag : "h3",
			_anchorId = p && p.anchorId ? p.anchorId : "anchor",
			_scrollClass = p && p.scrollClass ? p.scrollClass : "scroll",
			_pageTitle = p && p.pageTitle ? p.pageTitle : "A to Z Index",
			_animateScroll = p && p.animateScroll ? p.animateScroll : false,
			_scrollSpeed = p && p.scrollSpeed ? p.scrollSpeed : 500;

        var container = $(this);

        $.ajax({
            url: _source,
            async: false,
            dataType: 'json',
            success: function (data) {
                LoadContent(data);
                if (_animateScroll) {
                    AnimateScroll();
                }
            }
        });

        function LoadContent(data) {
            var item = $(document.createElement("a")),
                list = $(document.createElement("ul")).addClass("azItemContent"),
                listClone = list.clone(),
                header = "";

            container.empty();
            container.append($(document.createElement("h1")).append(_pageTitle).addClass("azListHeader"));

            var trigger = $(document.createElement("h2")).addClass("azListTriggers");
            var alphaArray = [ "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z" ];
            $.each(alphaArray, function() {
                trigger.append(item.clone().attr("href", "#" + _anchorId + this).addClass(_scrollClass).append(this.toString()));
            });
            trigger.children("a:first").addClass("first");
            trigger.children("a:last").addClass("last");
            container.append(trigger);

            $.each(data, function() {
                var itemClone = item.clone();

                itemClone.attr("href", this.url != "" ? this.url : "#").attr("title", this.alt != "" ? this.alt : this.title).append(this.title);
                if (this.newWindow) {
                    itemClone.attr("target", "_blank");
                }

                if (header != (this.title.substring(0, 1)).toUpperCase()) {
                    if (header != "") {
                        container.append($(document.createElement(_headerTag)).addClass("azItemHeader").append($(document.createElement("a")).attr("id", _anchorId + header).attr("title", _anchorId + header).attr("href", "#" + _anchorId + header).addClass(_scrollClass).append(header)));
                        listClone.children("li:first").addClass("first");
                        listClone.children("li:last").addClass("last");
                        container.append(listClone);
                        listClone = list.clone();
                    }
                    header = this.title.substring(0, 1).toUpperCase();                    
                }
                listClone.append($(document.createElement("li")).append(itemClone));
            });
            container.append($(document.createElement(_headerTag)).append($(document.createElement("a")).attr("id", _anchorId + header).attr("title", _anchorId + header).attr("href", "#" + _anchorId + header).addClass(_scrollClass).append(header)));
            listClone.children("li:first").addClass("first");
            listClone.children("li:last").addClass("last");
            container.append(listClone);
        }
        
        function AnimateScroll() {
            $("." + _scrollClass).click(function(event){
                //prevent the default action for the click event
                event.preventDefault(); 

                //get the full url - like mysitecom/index.htm#home
                var full_url = this.href;

                //split the url by # and get the anchor target name - home in mysitecom/index.htm#home
                var parts = full_url.split("#");
                var trgt = parts[1];

                //get the top offset of the target anchor
                var target_offset = jQuery("#" + trgt).offset();
                var target_top = target_offset.top;

                //goto that anchor by setting the body scroll top to anchor top
                $('html, body').animate({scrollTop:target_top}, _scrollSpeed);
            });
        }
    };

	$.fn.atoz_scroll = function(p) {

		var p=p||{};

		var _height = p && p.height ? p.height : 100,
		    _width = p && p.width ? p.width : 200,
		    _speed = p && p.speed ? p.speed : 3000,
		    _margin = p && p.margin ? p.margin : 5,
		    _padding = p && p.padding ? p.padding : 5,
		    _trigger = p && p.trigger ? p.trigger : false,
		    _location = p && p.location ? p.location : "top",
		    _id = p && p.id ? p.id : "ui-atoz-scroll",
		    _url = p && p.url ? p.url : "",
		    _reverse = p && p.reverse ? p.reverse : true,
		    _source = p && p.source ? p.source : "",
			_data = p && p.data ? p.data : [],
			_itemPerColumn = p && p.itemPerColumn ? p.itemPerColumn : 5;

		var id = $(this).attr("id");

		var container = $(this).addClass(_id + "-container").css("height", _height + "px").css("width", _width + "px"),
		    navleft = $(document.createElement("div")).addClass(_id + "-navleft").append('<a href="#"></a>').hide(),
		    navright = $(document.createElement("div")).addClass(_id + "-navright").append('<a href="#"></a>').hide(),
		    content = container.children("div:first").addClass(_id + "-content").css("height", (_height - 4 * _margin) - (_trigger ? 25 : 0) + "px").css("width", (_width - 4 * _margin) + "px"),
		    wrapper = content.children('div:first').addClass(_id + "-wrapper"),
		    trigger = $(document.createElement("div")).addClass(_id + "-trigger");

        navleft.find("a").css("top",  (_height / 2) - 8 + "px");
        navright.find("a").css("top",  (_height / 2) - 8 + "px");
        
        if (_source != "") {
            $.ajax({
                url: _source,
                async: false,
                dataType: 'json',
                success: function (data) {
                    LoadContent(data);
                }
            });
        }
        else if (_data.length > 0) {
            LoadContent(_data);
        }
        
        function LoadContent(data) {
            wrapper.empty();
            var item = $(document.createElement("a")),
                itemTemplate = $(document.createElement("ul")),
                itemTemplateClone = itemTemplate.clone(),
                count = 1,
                itemId = "";

            $.each(data, function() {
                var itemClone = item.clone();
                itemClone.attr("href", this.url != "" ? this.url : "#").attr("title", this.alt != "" ? this.alt : this.title).append(this.title);
                if (this.newWindow) {
                    itemClone.attr("target", "_blank");
                }
                itemTemplateClone.append($(document.createElement("li")).append(itemClone));

                if (itemId != (this.title.substring(0, 1).toUpperCase())) {
                    itemId = this.title.substring(0, 1).toUpperCase();
                    itemTemplateClone.addClass(_id + '-item-' + itemId)
                }
                if ((count % _itemPerColumn == 0) || (count == data.length)) {
                    wrapper.append(itemTemplateClone);
                    itemTemplateClone = itemTemplate.clone();
                }
                count = count + 1;
            });
        }
		    
		navleft.find("a").css("height", _height + "px");
		navright.find("a").css("height", _height + "px");

        var alphaArray = [ "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z" ];
        if (_url != "") {
            trigger.append($(document.createElement("a")).attr("id", "ALL").attr("href", _url).attr("target", "_blank").append("ALL"));
        }
        $.each(alphaArray, function() {
            trigger.append($(document.createElement("a")).attr("id", this.toString()).attr("href", "#").append(this.toString()));
        });

        if (_trigger) {
            trigger.find("a").css("padding", "0 " + _padding + "px").css("text-decoration", "none");
            if (_location == "bottom") {
                container.append(trigger.css("margin", "0 25px 5px 25px"));
            }
            else {
                container.prepend(trigger.css("margin", "5px 25px 0 25px"));
            }
        }

        container.prepend(navleft);
        container.prepend(navright);
        
        if(!wrapper.is(":empty")) {

		    var length = _width;
		    wrapper.children().each(function(){
		        $(this).addClass(_id + "-item");
		        length = length + $(this).width();
		    });
		    wrapper.children(":last").addClass("last");
		    wrapper.css("width", length);

		    var maxPosition = wrapper.children(":last").position().left + wrapper.children(":last").width() - content.width();
		    if (maxPosition > 0) {
		        navleft.show();
		        navright.show();
		    }
		    maxPosition = maxPosition + (2 * _margin); // account for padding if there is any
		    $(trigger).find("a").each(function() {
                if (($("." + _id + '-item-' + $(this).attr('id')).length) > 0) {
                    $(this).click(function() {
                        var position = $("." + _id + '-item-' + $(this).attr('id')).position().left;
                        if (position > maxPosition) {
                            position = maxPosition;
                        }
                        $(wrapper).animate({ "left": "-" + position + "px" }, "slow");
                    })
                }
		    });

		    navleft.mouseover(function() {
		        navleft.addClass("active");
		        if (_reverse) {
		            wrapper.animate({"left": "+0px"}, _speed, "linear");
		        }
		        else {
		            wrapper.animate({"left": "-" + maxPosition  + "px"}, _speed, "linear");
		        }
		    });
		    navleft.mouseout(function() {
		        navleft.removeClass("active");
		        wrapper.stop();
		    });
		    navright.mouseover(function() {
		        navright.addClass("active");
		        if (_reverse) {
		            wrapper.animate({"left": "-" + maxPosition  + "px"}, _speed, "linear");
		        }
		        else {
		            wrapper.animate({"left": "+0px"}, _speed, "linear");
		        }
		    });
		    navright.mouseout(function() {
		        navright.removeClass("active");
		        wrapper.stop();
		    });

		}

	};

})(jQuery);
