<?php

class Intense_Gallery extends Intense_Shortcode {

    function __construct() {
        parent::__construct();

        global $intense_visions_options;

        $this->title = __( 'Gallery', 'intense' );
        $this->category = __( 'Media', 'intense' );
        $this->show_preview = true;
    }

    function get_photos( $atts, $size ) {
        extract( shortcode_atts( $this->get_shortcode_defaults( null, $atts ), $atts ) );

        if ( $source == 'post_featured' ) {
            $ids = intense_get_post_thumbnail_ids( $id, null);
            $ids = implode(",", $ids);
        }

        if ( !empty( $ids ) ) {
            // 'ids' is explicitly ordered, unless you specify otherwise.
            if ( empty( $orderby ) ) {
                $orderby = 'post__in';
            }

            $include = $ids;
        }

        if ( 'RAND' == $order )
            $orderby = 'rand';

        // We're trusting author input, so let's at least make sure it looks like a valid orderby statement
        if ( isset( $orderby ) ) {
            $orderby = sanitize_sql_orderby( $orderby );

            if ( !$orderby ) unset( $orderby );
        }

        $id = intval( $id );        

        if ( !empty( $include ) ) {
            $_attachments = get_posts( array( 'include' => $include, 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => $order, 'orderby' => $orderby ) );

            $attachments = array();

            if ( 'NONE' == $order ) {
                $include_order = preg_split( '/[,]/', $include );
                $_new_attachments = array();

                //give the attachments keys that match the id of the attachment
                //prior to this, the key is just the item number in the array 0,1,2,3,...
                foreach ( $_attachments as $key => $val ) {
                    $_new_attachments[ $val->ID ] = $_attachments[ $key ];                    
                }

                $_attachments = $_new_attachments;
                $_new_attachments = null;

                //reorder the attachment array to match the include id order
                foreach ( $include_order as $key ) {
                    if ( !empty( $_attachments[ trim( $key ) ] ) ) {
                        $_new_attachments[ $key ] = $_attachments[ trim( $key ) ];
                    } else {
                        $_new_attachments[ $key ] = '-1';
                    }
                }

                $_attachments = $_new_attachments;
            }

            foreach ( $_attachments as $key => $val ) {
                if ( !empty( $_attachments[$key] ) && isset( $val->ID ) ) {
                    $attachments[$val->ID] = $_attachments[$key];
                } else {
                    $attachments[ 'x_' . rand() ] = '-1';
                }
            }
        } elseif ( !empty( $exclude ) ) {
            $attachments = get_children( array( 'post_parent' => $id, 'exclude' => $exclude, 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => $order, 'orderby' => $orderby ) );
        } else {
            $attachments = get_children( array( 'post_parent' => $id, 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => $order, 'orderby' => $orderby ) );
        }      

        if ( empty( $attachments ) && $source == 'wordpress' ) {
            return array( 'photos' => null );
        }

        $photo_source = new Intense_Photo_Source( $source, $attachments, $user, ( $groupid ? $groupid : $tag ), ( $setid ? $setid : $album ), $facebookpage );
        $photos = $photo_source->get_photos( $pagesize, $page );

        $wordpress_size = $photo_source->get_wordpress_size( $size );

        if ( !empty( $alternate_size ) ) {            
            $wordpress_alt_size = $photo_source->get_wordpress_size( $alternate_size );
        } else {
            $wordpress_alt_size = $wordpress_size;
        }

        if ( !empty( $first_image_size ) ) {            
            $wordpress_first_image_size = $photo_source->get_wordpress_size( $first_image_size );         
        } else {
            $wordpress_first_image_size = null;
        }

        $wordpress_full_size = $photo_source->get_wordpress_size( ( isset( $intense_visions_options['intense_photosource_full_size'] ) ? $intense_visions_options['intense_photosource_full_size'] : 'large' ) );

        return array(
            'photos' => $photos,
            'wordpress_size' => $wordpress_size,
            'wordpress_full_size' => $wordpress_full_size,
            'wordpress_alt_size' => $wordpress_alt_size,
            'wordpress_first_image_size' => $wordpress_first_image_size
        );
    }

    function shortcode( $atts, $content = null ) {        
        require_once INTENSE_PLUGIN_FOLDER . '/inc/Intense-photosource.php';
        require_once INTENSE_PLUGIN_FOLDER . '/shortcodes/gallery/gallery-types.php';
        
        global $intense_visions_options;
        extract( shortcode_atts( $this->get_shortcode_defaults( null, $atts ), $atts ) );

        intense_add_script( 'intense.gallery' );
        intense_add_script( 'jquery.appear' );

        static $instance = 0;

        $additionalscript = '';
        $output = '';
        $gallery_style = '';
        $float = is_rtl() ? 'right' : 'left';
        $lazy_load = isset( $lazy_load ) ? $lazy_load : isset( $intense_visions_options['intense_lazy_load'] ) ? $intense_visions_options['intense_lazy_load'] : true ;
        
        $instance++;

        $selector = "gallery-{$instance}";

        $gallery_type = 'Intense_Gallery_Type_' . ucfirst( $type );
        $gallery_type = new $gallery_type( $selector );
        
    	if ( empty( $grouping ) ) $grouping = $instance;
        if ( !empty( $show_animation ) ) intense_load_animation_CSS( $show_animation );

        //jquery method used to determine how the items should show: 
        //  appear will be when they come in to view, each will be when they are loaded
        $show_loop_method = "appear";        
        
        switch ( $layout ) {
            case 'circle':
                $size = "square150";
                $columns = 4;
                $starteffect = '';
                $hovereffect = '';
                break;
            case 'square':
                $size = "square150";
                $columns = 4;
                break;
            case 'smallsquare':
            case 'squaresmall':
                $size = "square75";
                $columns = 8;
                break; 
            case 'masonry':
                $class = ( !empty( $class ) ? 'masonry ' . $class : 'masonry' );
                $masonry_style = ' #' . $selector . ' .effeckt-caption { float: none; }';
                break;          
            default:
                break;
        }

        $columns = intval( $columns );
        $itemwidth = $columns > 0 ? floor( 100 / $columns ) : 100;
        $itemwidth = $itemwidth - ( $marginpercent * 2 ); //remove margin for right/left

        //if we are doing columns we have to remove the margin on the right most item
        //and adjust for the extra space freed up by not having the margin on the right
        //most item
        if ( $columns > 0 ) $itemwidth += ( $marginpercent * 2 ) / ( $columns );        
                
        $gallery_style = "
            #{$selector} .gallery-item {                
                " . ( !empty( $show_animation ) ? 'opacity: 0;' : '' ) . "
                " . ( $layout != 'masonry' ? 'max-width: ' . $itemwidth . '%; text-align: center; float:' . $float . ';' : "" ) . "
                margin: 0 " . $marginpercent * 2 . "% " . $marginpercent * 2 . "% 0;
            } " . ( isset( $masonry_style ) ? $masonry_style : "" );

        if ( $columns > 0 && $marginpercent > 0 ) {
            $gallery_style .= "#{$selector} .gallery-item:nth-of-type(" . $columns . "n" . ( !empty( $first_image_size ) ? "+" . ( $columns + 1 ) : '+0' ) . ") {
                margin-right: 0;
            }";
        }

        if ( $first_image_size ) {
            $gallery_style .= "#{$selector} .gallery-item:first-child {
                margin-right: 0;
                max-width: 100%;            
            }";
        }

        $size_class = sanitize_html_class( $size );
        
        $init_script = " 
            var isOldIE = $('#intense-browser-check').hasClass('oldie');
            $('#{$selector} .gallery-overlay').remove();";

        // Add CSS/JS for different gallery types and add JavaScript setup code
        if ( !empty( $effeckt ) ) {
            intense_add_style( 'effeckt_caption' );
        } else if ( $show_tooltip == 1 && $type != 'galleria' ) {
            intense_add_style( 'qtip2' );
            intense_add_script( 'qtip2' );
            intense_add_script( 'imagesloaded' );
            $init_script .= "                
                $('.$grouping').qtip({
                    position: {
                        at: 'top center',
                        my: 'bottom center',
                        target: 'mouse',
                        " . ( current_user_can( 'manage_options' ) ? 'adjust: { x: 0, y: -32 },' : '' ) . "
                    },
                    show: { delay: 1500 }               
                });
            $('.$grouping img').removeAttr('title');";
        }

        $lightbox = null;

        $gallery_init = $gallery_type->init();

        $init_script .= $gallery_init['script'];
        $gallery_style .= $gallery_init['style'];
        $additionalscript .= $gallery_init['additional_script'];

        if ( $type == 'galleria' ) {
            $size = ( $size != '' ? $size : 'medium640' );
        }

        // Add JS/CSS for Adipoli
        if ( $starteffect != '' && $hovereffect != '' ) {
            $lazy_load = false;
            intense_add_style( 'adipoli' );
            intense_add_script( 'adipoli' );
            $init_script .= "
            if (!isOldIE) {                
                $('.$grouping img').adipoli({
                    'startEffect' : '$starteffect',
                    'hoverEffect' : '$hovereffect'
                });
            }";
        }

        if ( isset( $subtleeffect ) && $subtleeffect != '' ) {
            intense_load_subtle_effect_CSS( $subtleeffect );
            intense_add_script( 'intense.subtle.effect' );
        }

        $output = "<div id='$selector' class='intense gallery galleryid-{$id} gallery-columns-{$columns} gallery-size-{$size_class}" . ( !empty( $class ) ? ' ' . $class : '' ) . "'>";

        if ( !$lazy_load ) {
            $output .= "<div class='gallery-overlay'><img src='" . INTENSE_PLUGIN_URL . "/assets/img/loader.gif' /></div>";
        } else {
            intense_add_script( 'lazyloadxt' );            
            intense_add_script( 'intense.lazyload' );
            intense_add_style( 'lazyloadxt.spinner' );
        }

        switch ( $layout ) {
            case 'circle':
                $init_script .= "$('.$grouping img').addClass('img-circle');";
                break;
            case 'masonry':
                $masonry_shortcode = '[intense_masonry gutter="' . $gutter . '"]';                
                $show_loop_method = "each";
                break;
            default:
                break;
        }

        if ( !$lazy_load && !empty( $show_animation ) ) {
            $init_script .= "
            $('#{$selector} .gallery-item')." . $show_loop_method  . "(function() {
                var el = $(this);
                var delay = Math.floor((Math.random() * " . $maximum_show_delay . ")+1);
                var isIE9 = $('#intense-browser-check').hasClass('ie9');

                setTimeout(function() {
                    el.addClass('animated').addClass('" . $show_animation . "');
                }, delay);
                
                if(isIE9) {
                    el.show();
                    el.css('opacity', '1');
                }
            });";
        }
        
        $atts['size'] = $size; //override so predefined layouts will work
        $atts['columns'] = $columns; //override so predefined layouts will work

        extract( $this->get_photos( $atts, $size ) );
        
        if ( ! isset( $photos ) ) {
            echo "<div class='alert'>Unable to load photos</div>";
        }

        if ( $effeckt != '' && isset( $effeckt_opacity ) && isset( $effeckt_color ) ) {
            $hex = str_replace( "#", "", $effeckt_color );
            $a = $effeckt_opacity / 100;

            if ( strlen( $hex ) == 3 ) {
                $r = hexdec( substr( $hex, 0, 1 ).substr( $hex, 0, 1 ) );
                $g = hexdec( substr( $hex, 1, 1 ).substr( $hex, 1, 1 ) );
                $b = hexdec( substr( $hex, 2, 1 ).substr( $hex, 2, 1 ) );
            } else {
                $r = hexdec( substr( $hex, 0, 2 ) );
                $g = hexdec( substr( $hex, 2, 2 ) );
                $b = hexdec( substr( $hex, 4, 2 ) );
            }

            $effeckt_style = "background: rgba(" . $r . "," . $g . "," . $b . "," . $a . ") !important; rgb(" . $r . "," . $g . "," . $b . ")\9 !important;";
        } else {
            $effeckt_style = "";
        }

        $radius = '';

        if ( isset( $border_radius ) && $type != 'galleria' && $type != 'supersized' ) {
            $radius = ' border-radius:' . $border_radius . ';';
        }

        if ( isset( $wordpress_size['height'] ) ) {
            $subtleheight = 'max-height:' . ( intval( $wordpress_size['height'] ) - ( intval( $wordpress_size['height'] ) / 10 ) ) . 'px;';
        }

        $i = 0;

        foreach ( $photos as $photo ) {                        
            $alternate = ( !empty( $masonry_alternate_count ) && $i % $masonry_alternate_count == 0 );

            if ( !empty( $wordpress_first_image_size ) && $i == 0 ) {
                $requested_size = $photo->get_closest_size( $wordpress_first_image_size["width"], $wordpress_first_image_size["height"] );
            } else if ( $alternate ) {                
                $requested_size = $photo->get_closest_size( $wordpress_alt_size["width"], $wordpress_alt_size["height"] );
            } else {
                $requested_size = $photo->get_closest_size( $wordpress_size["width"], $wordpress_size["height"] );   
            }

            $original_size = $photo->get_closest_size( $wordpress_full_size["width"], $wordpress_full_size["height"] );

            $title = $photo->title;
            $description = $photo->description;
            $link = $photo->link;

            $width = $requested_size['width'];
            $height = $requested_size['height'];
            if ( isset( $width ) ) { $width = " width='" . $width . "' "; }
            if ( isset( $height ) ) { $height = " height='" . $height . "' "; }

            $original_photo_url = $original_size['sourceurl'];
            $sized_photo_url = $requested_size['sourceurl'];            

            if ( !empty( $effeckt ) ) {
                $individual_photo_markup = intense_get_template( '/gallery/effeckt/' . $effeckt_template . '.php', array(
                    'radius' => $radius,
                    'url' => $sized_photo_url,
                    'title' => ( $show_tooltip == 1 ? $title : '' ),
                    'description' => $description,
                    'effeckt' => $effeckt,
                    'effect_style' => $effeckt_style,
                    'effeckt_template' => $effeckt_template,
                    'subtle_template' => $subtle_template,
                    'standard_template' => $standard_template,
                    'galleria_template' => $galleria_template,
                    'photo' => $photo,
                    'width' => $width,
                    'height' => $height,
                    'animation' => $show_animation,
                    'lazy_load' => $lazy_load
                ) );            
            }  else if ( $hover_effect == 'subtle' ) {
                $individual_photo_markup = intense_get_template( '/gallery/subtle/' . $subtle_template . '.php', array(
                    'radius' => $radius,
                    'url' => $sized_photo_url,
                    'title' => ( $show_tooltip == 1 ? $title : '' ),
                    'description' => $description,
                    'subtleeffect' => $subtleeffect,
                    'subtleheight' => ( !empty( $subtleheight ) ? $subtleheight : '' ),
                    'width' => $width,
                    'height' => $height,
                    'effeckt_template' => $effeckt_template,
                    'subtle_template' => $subtle_template,
                    'standard_template' => $standard_template,
                    'galleria_template' => $galleria_template,
                    'photo' => $photo,
                    'animation' => $show_animation,
                    'lazy_load' => $lazy_load
                ) );
            } else {
                $individual_photo_markup = intense_get_template( '/gallery/standard/' . $standard_template . '.php', array(
                    'width' => $width,
                    'height' => $height,
                    'radius' => $radius,
                    'url' => $sized_photo_url,
                    'title' => ( $show_tooltip == 1 ? $title : '' ),
                    'description' => $description,
                    'style' => 'width: 100%;',
                    'effeckt_template' => $effeckt_template,
                    'subtle_template' => $subtle_template,
                    'standard_template' => $standard_template,
                    'galleria_template' => $galleria_template,
                    'photo' => $photo,
                    'animation' => $show_animation,
                    'lazy_load' => $lazy_load
                ) );
            }

            $item = $gallery_type->item( array(
                'sized_photo_url' => $sized_photo_url,
                'original_photo_url' => $original_photo_url,
                'title' => ( $show_tooltip == 1 ? $title : '' ),
                'description' => $description,
                'grouping' => $grouping,
                'individual_photo_markup' => $individual_photo_markup,
                'no_link' => $no_link,
                'type' => $type,
                'grouping' => $grouping,
                'link' => $link,
                'effeckt_template' => $effeckt_template,
                'subtle_template' => $subtle_template,
                'standard_template' => $standard_template,
                'galleria_template' => $galleria_template,
                'photo' => $photo
            ) );

            $photo_markup = $item['markup'];
            $photo_script = $item['script'];

            switch ( $layout ) {
                case 'masonry':
                    if ( $alternate ) { 
                        $masonry_shortcode .= '[intense_masonry_item width="' . $masonry_alternate_width . '"]';
                    } else {
                        $masonry_shortcode .= '[intense_masonry_item width="' . $masonry_item_width . '"]';
                    }
                    $masonry_shortcode .= $photo_markup;
                    $masonry_shortcode .= '[/intense_masonry_item]';
                    break;
                default:
                    $output .= $photo_markup;
                    $additionalscript .= $photo_script;                        
                    
                    $clearfix_item_count = $i;

                    if ( !empty( $first_image_size ) ) {
                        $clearfix_item_count = $i - 1;
                    }

                    if ( $columns > 0 && $i > 0 && ( $clearfix_item_count + 1 ) % $columns == 0 )
                        $output .= "<div class='clearfix'></div>";
                    break;
            }

            $i++;
        }

        if ( !empty( $effeckt ) ) {
            $additionalscript .= ' $(".preload").removeClass("preload"); ';
            $additionalscript .= ' if ($("#intense-browser-check").hasClass("ie8")) {
                $(".effeckt-caption").find("figcaption").fadeTo("fast", 0);
                $(".effeckt-caption").hover(
                    function() { $(this).find("figcaption").fadeTo("fast", ' . $effeckt_opacity / 100 . '); },
                    function() { $(this).find("figcaption").fadeTo("fast", 0); } );
            } ';
        }

        if ( !empty( $additionalscript ) ) {
            switch ( $type ) {
                case 'supersized':
                    $additionalscript = rtrim( $additionalscript, "," );
                    $additionalscript .= "]});";
                    break;
                default:
                    break;
            }

            $init_script .= $additionalscript;
        }

        switch ( $layout ) {
            case 'masonry':
                $masonry_shortcode .= '[/intense_masonry]';
                $output .= do_shortcode( $masonry_shortcode );
                break;
            default:
                $output .= "<div class='clearfix'></div>";
                break;
        }

        $output .= "</div>\n";
        $output .= '<script> var intenseGalleryFunctions = intenseGalleryFunctions || []; intenseGalleryFunctions.push(function() { var $ = jQuery; ' . $init_script . ' });</script>';
        $output .= '<style type="text/css">' . $gallery_style . '</style>';

        if ( $type == 'supersized' && $supersized_position == 'Top Left' ) {
            $output .= '<div id="supersizedcontrols" class="top">';
            $output .= intense_get_template( '/gallery/supersized/' . $supersized_template . '.php' );
            $output .= '</div>';
        } else if ( $type == 'supersized' && $supersized_position == 'Bottom Left' ) {
            $output .= '<div id="supersizedcontrols" class="bottom">';
            $output .= intense_get_template( '/gallery/supersized/' . $supersized_template . '.php' );
            $output .= '</div>';
        }

        return $output;    
    }       
}
