/*!
 * @package		YJ News Pop
 * @author		Youjoomla LLC
 * @website     Youjoomla.com
 * @copyright	Copyright (c) 2007 - 2011 Youjoomla LLC.
 * @license     http://www.opensource.org/licenses/mit-license.php
 */
jQuery.noConflict();;
(function ($, window, document, undefined) {

    // undefined is used here as the undefined global variable in ECMAScript 3 is
    // mutable (ie. it can be changed by someone else). undefined isn't really being
    // passed in so we can ensure the value of it is truly undefined. In ES5, undefined
    // can no longer be modified.

    // window and document are passed through as local variable rather than global
    // as this (slightly) quickens the resolution process and can be more efficiently
    // minified (especially when both are regularly referenced in your plugin).

    // Create the defaults once
    var pluginName = "yjnewsPop",
        defaults = {
            container: ".yjNewsPopContainer",
            layout: ".yjnewspopLayout",
            maxpopnews: 4,
            getmore: ".getmore",
            modpath: "",
            sqlstart: 4,
            itemload: 4,
            jitemid: 101,
            jmodid: 119,
            loadtxt: "Get more posts",
            loadingtxt: "Loading the next set of posts...",
            donetxt: "That\'s all folks!",
            loadaction: "click", // 1 = click 2 = scroll
            popwidth: "70%",
            popheight: "600px",
            popvwidth: "640px",
            popvheight: "390px",
            popiwidth: "70%",
            popiheight: "600px",
			popboxbgcolor:"#ffffff",
			popboxbgcolorv:"#000000",
			popboxbgcolori:"#ffffff",
            popboxpacity: 0.8,
			touchbehavior: false,
			cursorcolor:"#000000",
            callback: function () {}
        };

    // The actual plugin constructor

    function Plugin(element, options) {
        this.element = element;
        // jQuery has an extend method which merges the contents of two or
        // more objects, storing the result in the first object. The first object
        // is generally empty as we don't want to alter the default options for
        // future instances of the plugin
        this.settings = $.extend({}, defaults, options);
        this._defaults = defaults;
        this._name = pluginName;
        this.init();
    }

    Plugin.prototype = {
        init: function () {
            // Place initialization logic here
            // You already have access to the DOM element and
            // the options via the instance, e.g. this.element
            // and this.settings
            // you can add more functions like the one below and
            // call them like so: this.yourOtherFunction(this.element, this.settings).
            //console.log($(this.settings.container).attr("id"));
            //$(this.settings.container).css({opacity:0});
            this.newspopIsotope();
            this.newspopFilter();
            this.newspopLoadmore();
            $(this.settings.container).animate({
                opacity: 1
            }, 1000);

        },
        newspopIsotope: function () {

            var self = this;

            var newspopsHolder = $(this.settings.layout);



            $(window).smartresize(function () {
                newspopsHolder.imagesLoaded(function () {
                    newspopsHolder.isotope({
                        itemSelector: ' .yjnewspopItem'
                    }).isotope('reLayout');


                });

                self.newspopWidth();
                self.newspopMoveintros();
                self.newspopHover();
                self.yjnewspopColorbox();
                self.newspopaddTips();
                $.fancybox.update();
            }).smartresize();

            // load tips
            $('.showtips').tipr({
                'speed': 700,
                'mode': 'bottom'
            });

            // fix hovers




        },
        newspopWidth: function () {

            var self = this;


            var containerWidth = $(this.settings.container).width();
            var newspopItems = $(this.settings.container).find('.yjnewspopItem');
            var newspopItemsWidth = newspopItems.width();


            if ($(window).width() < 980) {
                var maxItemsperRow = Math.round(containerWidth / newspopItemsWidth);
            } else {
                maxItemsperRow = this.settings.maxpopnews;
            }

            var newItemsWidth = (containerWidth / maxItemsperRow) - 1;
            newspopItems.width(newItemsWidth);



        },
        newspopaddTips: function () {

            var self = this;

            var catsArray = $(this.settings.container).data('catsarray').split(",");
            var yjNewsPopFilter = $(this.settings.container).find('.yjnewspopFilter');
            $(this.settings.layout + ' .yjnewspop').each(function (index, element) {

                $(yjNewsPopFilter).find('li[data-iscat=".' + $(this).data('catname') + '"]').removeClass('hide').addClass('show');

                // count items per category
                var $elements = $(yjNewsPopFilter).find('li[data-iscat=".' + $(this).data('catname') + '"]').find('a');
                var $countItems = $('.' + $(this).data('catname') + '').length;
                $realCatName = $(this).data('relacatname');
                if ($countItems > 1) {
                    var $textItems = ' items';
                } else {
                    $textItems = ' item';
                }
                //add tips
                $elements.attr('data-tip', '' + $realCatName + ' category on this page contains ' + $countItems + $textItems + '');



            });
        },
        newspopFilter: function () {


            var self = this;
            var filters = {};
            var newspopsHolder = $(this.settings.layout);


            // when everything loads, make the "all" options selected
            $(this.settings.container + ' .yjnewspopFilter a[data-filter-value=""]').addClass('selected');

            // filter buttons
            $(this.settings.container + ' .yjnewspopFilter a').click(
                function (e) {
                    e.preventDefault();
                    var clicked_filter = $(this);

                    // if the clicked link is already selected, don't do anything
                    if (clicked_filter.hasClass('selected')) {
                        return;
                    }
                    var optionSet = clicked_filter.parents('.option-set');

                    // get rid of the ".selected" class on any links in this group and put it on the clicked link
                    optionSet.find('.selected').removeClass('selected');
                    clicked_filter.addClass('selected');

                    // store the filters in the filters object, indexed by the group they're in
                    // i.e. filters.category = 'animal'
                    var group = optionSet.attr('data-filter-group');
                    filters[group] = clicked_filter.attr('data-filter-value');

                    // convert the filters object into an array of strings which are CSS class selectors
                    var filters_to_use = [];
                    for (var group in filters) {
                        filters_to_use.push(filters[group])
                    }

                    // smash the array together to get a big selector which will filter all elements with the filter classes
                    var selector = filters_to_use.join('');

                    // run the filter on the isotope element
                    newspopsHolder.isotope({
                        filter: selector
                    });
                }
            );


        },
        newspopHover: function () {
            var self = this;
            $(this.settings.layout + ' .yjnewspop').each(function () {
                $(this).hoverdir({
                    hoverDelay: 75
                });
            });
        },
        newspopMoveintros: function () {
            var self = this;
            var newspopsHolder = $(this.settings.layout);
            newspopsHolder.imagesLoaded(function () {
                $('.yjnewspopIntro').each(function () {

                    var getmyHeight = $(this).height();
                    var getInfoBox = $(this).find('.yjnewspopInfo');
                    var getInfoBoxHeight = getInfoBox.height();
                    var moveItro = (getmyHeight - getInfoBoxHeight) / 2;
                    getInfoBox.css('margin-top', moveItro);

                });
            });

        },


        newspopAjax: function () {

            var self = this;
            var $container = $(this.settings.layout);
            desturl = self.settings.modpath + "src/ajax/get_new_content.php?sql_start=" + self.settings.sqlstart + "&Itemid=" + self.settings.jitemid + "&modid=" + self.settings.jmodid;
            self.settings.sqlstart += self.settings.itemload;


            return $.ajax({
                cache: false,
                url: desturl,
                dataType: "html",


                beforeSend: function (html) {

                    var itemsleft = $(self.settings.container).attr('data-items');
                    $(self.settings.container).find(".loading").remove();
                    if (itemsleft > 0) {

                        $(self.settings.container).append('<div class="loading"><div class="loadingtxt">' + self.settings.loadingtxt + '</div></div>');
                        var load_poz = ($(window).width() - $(".loading").width()) / 2;
                        $(self.settings.container).find(".loading").css({
                            left: load_poz
                        }).animate({
                            opacity: 0.8
                        });
                    }
                },
                success: function (html) {

                    var items = $('.yjnewspopItem', $(html));

                    if (items.length > 0) {
                        $container.imagesLoaded(function () {
                            $container.append(items).isotope('appended', items).smartresize();
                            items.animate({
                                opacity: 1
                            });

                            if (self.settings.loadaction == "click") {
                                $('html, body').animate({
                                    scrollTop: $(self.settings.container).find(".getmore").offset().top + $(self.settings.container).find(".getmore").height() / 2 - $(window).height() / 2
                                }, 1000);
                            }

                        });
                        $(self.settings.container).attr('data-items', items.length);
                    } else {

                        $(self.settings.container).find(".loadingtxt").html(self.settings.donetxt)
                        $(self.settings.getmore).unbind("click");
                        $(window).unbind("scroll");
                        $(self.settings.container).attr('data-items', '0');
                    }

                },
                complete: function (xhr) {

                    setTimeout(function () {
                        $(self.settings.container).find(".loading").fadeOut("normal");
                    }, 800);



                }
            });

        },

        newspopLoadmore: function () {
            var self = this;


            if (this.settings.loadaction == "click") {
                $(this.settings.getmore).click(function (event) {

                    self.newspopAjax();

                });
            }
            if (this.settings.loadaction == "scroll") {
                var delay = 50;
                var timeout = null;
                $(window).bind('scroll', function () {
                    clearTimeout(timeout);
                    timeout = setTimeout(function () {
                        self.newspopAjax();
                        clearTimeout(timeout)
                    }, delay);
                });

            }
        },
		newspoHexToRgb: function(hex) {
			
			  var self = this;
                var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
                return result ? {
                    r: parseInt(result[1], 16),
                    g: parseInt(result[2], 16),
                    b: parseInt(result[3], 16),
                    rgb: parseInt(result[1], 16) + ", " + parseInt(result[2], 16) + ", " + parseInt(result[3], 16)
                } : null;
            },
        yjnewspopColorbox: function () {

            var self = this;
			var bgColor = this.newspoHexToRgb(this.settings.popboxbgcolor).rgb;
			var bgColorv = this.newspoHexToRgb(this.settings.popboxbgcolorv).rgb;
			var bgColori = this.newspoHexToRgb(this.settings.popboxbgcolori).rgb;

            $('.group' + this.settings.jmodid).attr('rel', 'gallery').fancybox({
                openEffect: 'elastic',
                closeEffect: 'elastic',
                nextEffect: 'elastic',
                prevEffect: 'elastic',
                maxWidth:self.settings.popwidth,
                maxHeight:self.settings.popheight,
                afterLoad: function () {
                    this.title = this.element.data('nptitle');
                },
                margin: [20, 60, 20, 60],
                helpers: {
                    overlay: {
                        css: {
                            'background': 'rgba('+bgColor+','+self.settings.popboxpacity+')'
                        }
                    }
                }
            });

            $('.newspopmedia').attr('rel', 'media').fancybox({
                afterLoad: function () {
                    this.title = this.element.data('nptitle');
                },
                openEffect: 'none',
                closeEffect: 'elastic',
                nextEffect: 'none',
                prevEffect: 'none',
                padding: 0,
                maxWidth: self.settings.popvwidth,
                maxHeight: self.settings.popvheight,
                margin: [20, 60, 20, 60],
                helpers: {
                    overlay: {
                        css: {
                            'background': 'rgba('+bgColorv+','+self.settings.popboxpacity+')'
                        }
                    },
                    media: {}
                }
            });
            $(".popnewsLoad" + this.settings.jmodid).attr('rel', 'popnewsajax').fancybox({
                nextEffect: 'none',
                prevEffect: 'none',
                closeEffect: 'elastic',
                type: 'iframe',
                autoSize: true,
                maxWidth: self.settings.popiwidth,
                maxHeight: self.settings.popiheight,
                beforeLoad: function () {
                    this.href = this.element.data('getlink');
                },
                afterLoad: function () {
                    this.title = this.element.data('nptitle');
                    $('.fancybox-iframe').load(function () {
                        $(this).contents().find('head').append('<base target="_parent" />');
                    });
                },
                iframe: {
                    preload: false,
                    scrolling: "no"
                },
                helpers: {
                    overlay: {
                        locked: true,
                        css: {
                            'background': 'rgba('+bgColori+','+self.settings.popboxpacity+')'
                        }
                    }
                },
                scrolling: "no",
                afterShow: function () {
                    $(".fancybox-inner").niceScroll(".fancybox-inner iframe", {
                        boxzoom: false,
                        autohidemode: "false",
                        cursorwidth: "8px",
                        scrollspeed: 50,
                        touchbehavior: self.settings.touchbehavior, 
                        bouncescroll: true,
                        cursorcolor:self.settings.cursorcolor 

                    });
                    $("body").css("overflow-y", "hidden");
                },
                beforeClose: function () {
                    $("body").css("overflow-y", "");
                }
            });
            $('.newspopmaps').attr('rel', 'maps').fancybox({
                afterLoad: function () {
                    this.title = this.element.data('nptitle');
                },
                openEffect: 'none',
                closeEffect: 'elastic',
                nextEffect: 'none',
                prevEffect: 'none',
                padding: 0,
                maxWidth: self.settings.popvwidth,
                maxHeight: self.settings.popvheight,
                margin: [20, 60, 20, 60],
                helpers: {
                    overlay: {
                        css: {
                            'background': 'rgba('+bgColorv+','+self.settings.popboxpacity+')'
                        }
                    },
                    media: {}
                }
            });



        },
        //



    };

    // A really lightweight plugin wrapper around the constructor,
    // preventing against multiple instantiations
    $.fn[pluginName] = function (options) {
        return this.each(function () {
            if (!$.data(this, "plugin_" + pluginName)) {
                $.data(this, "plugin_" + pluginName, new Plugin(this, options));
            }
        });
    };

})(jQuery, window, document);