jQuery(document).ready(function($) {

    // Initialize Prettyphoto
    $("div[rel^='prettyPhoto']").prettyPhoto();

    // Remove description and title from PrettyPhoto
    $('p.pp_description, div.ppt').remove();

    // Set minimum width of container to the size of the browser window
    var windowWidth = $(window).width();
    var windowHeight = $(window).height();
    $('ul#magazine_roll').css('min-width', windowWidth + 'px');

    // Trackball scrolling addition
    var element = $('.scroll-pane').jScrollPane();
    var api = element.data('jsp');
    element.bind(
    'mousewheel',
    function(event, delta, deltaX, deltaY)
    {
        api.scrollByX(deltaY * 30);
        api.scrollByX(deltaX * 30);
        return false;
    }
    );

	// Magazine Overlay
	$(".magazine_issue").map(function(){
		// Set main variables
		var flipped = $(this).next('.magazine_flipped');
		var cover = $(this);
		var information = $(this).find('.information');
		var close = $(flipped).find('.close');
		var video = $(flipped).find('.magazine_video');

		// Hover Functions
		$(cover).hover(
		  function () {
		    $(cover).fadeTo("fast", 1);
			$(information).show();

			// Click information to show flipped
			$(information).click(function(){
				$(flipped).show();
				$(cover).fadeTo("fast", 0.25);
			});
		  },
		  function () {
		    $(cover).fadeTo("fast", 0.25);
			$(information).hide();
		  }
		);

		$(video).map(function(){

			var videoSection = $(this);
			var credits = $(videoSection).find('.video_credits');
			var videoData = $(videoSection).find('.video_data_field');
			
			// Video Hover Effect
		    $(videoSection).hover(function() {
		        $(this).fadeTo("fast", 1.0);
		    },
		    function() {
		        $(this).fadeTo("fast", 0.50);
		    });

		});

		// Close Functions
		$(close).click(function(){
			$(flipped).hide();
			$(cover).clearQueue();
			$(cover).fadeTo("fast", 1);
			$(information).show();
		});

	});
	// END Magazine Overlay
	


    // Top navigation drop down
    $('#nav li').hover(
    function() {
        //show its submenu
        $('ul', this).slideDown(100);
        $(this).addClass('selected');
    },
    function() {
        //hide its submenu
        $('ul', this).slideUp(100);
        $(this).removeClass('selected');
    }
    );

    // No hashmark if they accidentally click the nav
    $('ul#nav li > a').click(function() {
        return false;
    });

	// SEARCH PAGE

    // Check if there are no search results
    if ($('body.search').is(':visible')) {
        var findResults = $('ul#magazine_roll').find('li.magazine_container').length;
        if (findResults === 0) {
            $('ul#magazine_roll').prepend('<h1 class="notice">There were no results in your search.</h1>');
        }
    }

    // get and assign the ourHolder element to the
    // $holder varible for use later
    var $holder = $('ul#magazine_roll');

    // clone all items within the pre-assigned $holder element
    var $data = $holder.clone();

    // hide everything but the featured category on the home page
    $('body.home ul#magazine_roll > li.magazine_container').map(function() {
        if ($(this).attr('id') === "featured") {
            } else {
            $(this).hide();
        }
    });

    $('body.search ul#magazine_roll > li').map(function() {
        if ($(this).attr('id') == 'search-result') {
            } else {
            $(this).hide();
        }
    });
   
    // attempt to call Quicksand when a filter option
    // item is clicked
    $('#filterOptions li a, #logo p a#home').click(function(e) {
	
        // reset the active class on all the buttons
        $('#filterOptions li').removeClass('active');

        // assign the class of the clicked filter option
        // element to our $filterType variable
        var $filterType = $(this).attr('class');
        $(this).parent().addClass('active');

        // find all li elements that have our required $filterType
        // values for the data-type element
        var $filteredData = $data.find('li[data-type=' + $filterType + ']');

        // call quicksand and assign transition parameters
        $holder.quicksand($filteredData, {
            duration: 800,
            adjustHeight: false,
            useScaling: false,
        },
        function() {

			if ($('body').hasClass('search')) {
				$('li#'+$filterType).show();
				$('li#search-result').hide();
				searchMags($filterType);
			} else {
				countMags($filterType);
			}
            api.reinitialise();
            $("div[rel^='prettyPhoto']").prettyPhoto();

			// Magazine Overlay
			$(".magazine_issue").map(function(){
				// Set main variables
				var flipped = $(this).next('.magazine_flipped');
				var cover = $(this);
				var information = $(this).find('.information');
				var close = $(flipped).find('.close');
				var video = $(flipped).find('.magazine_video');

				// Hover Functions
				$(cover).hover(
				  function () {
				    $(cover).fadeTo("fast", 1);
					$(information).show();

					// Click information to show flipped
					$(information).click(function(){
						$(flipped).show();
						$(cover).fadeTo("fast", 0.25);
					});
				  },
				  function () {
				    $(cover).fadeTo("fast", 0.25);
					$(information).hide();
				  }
				);

				$(video).map(function(){

					var videoSection = $(this);
					var credits = $(videoSection).find('.video_credits');
					var videoData = $(videoSection).find('.video_data_field');
					
					// Video Hover Effect
				    $(videoSection).hover(function() {
				        $(this).fadeTo("fast", 1.0);
				    },
				    function() {
				        $(this).fadeTo("fast", 0.50);
				    });

				});

				// Close Functions
				$(close).click(function(){
					$(flipped).hide();
					$(cover).clearQueue();
					$(cover).fadeTo("fast", 1);
					$(information).show();
				});

			});
			// END Magazine Overlay
			
            // If their are no values for a magazine video, don't show it
            $('.magazine_video').map(function() {
                var removeIfEmpty = $(this).find('.magazine_link').attr('href').length;
                if (removeIfEmpty === 0) {
                    $(this).remove();
                }
            });

            // If their are no values for a magazine description, don't show it
            $('.magazine_description').map(function() {
                var removeIfEmpty = $(this).html().length;
                if (removeIfEmpty === 0) {
                    $(this).remove();
                }
            });
            return false;
        });
        return false;
    });
    // END CLONE

    // Custome scroll bar function
    $(function()
    {
        $('.scroll-pane').each(
        function()
        {
            $(this).jScrollPane(
            {
                horizontalDragMinWidth: 84,
                horizontalDragMaxWidth: 84
            }
            );
            var api = $(this).data('jsp');
            var throttleTimeout;
            $(window).bind(
            'resize',
            function()
            {
                if ($.browser.msie) {
                    // IE fires multiple resize events while you are dragging the browser window which
                    // causes it to crash if you try to update the scrollpane on every one. So we need
                    // to throttle it to fire a maximum of once every 50 milliseconds...
                    if (!throttleTimeout) {
                        throttleTimeout = setTimeout(
                        function()
                        {
                            api.reinitialise();
                            throttleTimeout = null;
                        },
                        50
                        );
                    }
                } else {
                    api.reinitialise();
                }
            }
            );
        }
        )

    });

	// Check for a duplicate post on search page in a different category and hide it
    if ($('body.search-results').is(":visible")) {
        var seen = {};
        $('ul#magazine_roll > li').each(function() {
            var txt = $(this).attr('data-id');
            if (seen[txt])
            $(this).hide();
            else
            seen[txt] = true;
        });
    }

    // First initialization of featured images
	if ($('body').hasClass('search')) {
		searchMags();
	} else {
		countMags('featured');
	}

    // If their are no values for a magazine video, don't show it
    $('.magazine_video').map(function() {
        var removeIfEmpty = $(this).find('.magazine_link').attr('href').length;
        if (removeIfEmpty === 0) {
            $(this).remove();
        }
    });

    // If their are no values for a magazine description, don't show it
    $('.magazine_description').map(function() {
        var removeIfEmpty = $(this).html().length;
        if (removeIfEmpty === 0) {
            $(this).remove();
        }
    });

    // Adjusting width function on filter
    function countMags(e) {
        var counter = $('ul#magazine_roll li[data-type="' + e + '"]').length;
        var calculateWidth = counter * 359;
        var totalWidth = calculateWidth + 'px';
        $('ul#magazine_roll').css('width', totalWidth);
    }

	function searchMags() {
        var counter = $('ul#magazine_roll li.magazine_container').length;
		var hidden = $('li.magazine_container:hidden').length;
		var totalMags = (counter - hidden);
        var calculateWidth = (totalMags) * 359;
        var totalWidth = calculateWidth + 'px';
		if (calculateWidth < windowWidth) {
			$('ul#magazine_roll').css('width', (windowWidth + 1) + 'px');
		} else {
			$('ul#magazine_roll').css('width', totalWidth);
		}
    }
});
