<?php

class Intense_Map_Marker extends Intense_Shortcode {
    function __construct() {
        parent::__construct();

        global $intense_visions_options;

        $this->title = __( 'Map Marker', 'intense' );
        $this->category = __( 'Media', 'intense' );
        $this->show_preview = true;
        $this->hidden = true;
        $this->parent = 'intense_map';
    }

    function shortcode( $atts, $content = null ) {
        global $intense_visions_options;
        extract( shortcode_atts( $this->get_shortcode_defaults( null, $atts ), $atts ) );

        $output = '';
        $random = $GLOBALS['map_number'];
        $bounds = $GLOBALS['fit_bounds'];
        $anchor = '16,32';
        $shadowanchor = '16,32';
        $iconurl = '';

        if ( is_numeric( $markerimage ) ) {
            $photo = Intense_Photo_Source::get_wordpress_photo( $markerimage, null );
            $markerimage = $photo['url'];
        }

        if ( is_numeric( $markershadow ) ) {
            $photo = Intense_Photo_Source::get_wordpress_photo( $markershadow, null );            
            $markershadow = $photo['url'];
        }

        if ( !empty( $markeranchor ) ) {
            $anchor = $markeranchor;
        }

        if ( !empty( $markershadow ) && !empty( $markershadowanchor ) ) {
            $shadowanchor = $markershadowanchor;
        }


        if ( !empty( $source ) && $source != 'custom' ) {
            $iscat_array = false;
            $cat_array = array();
            $blog_cat_array = array();

            $args = array(
                'post_type' => $source,
                'paged'=> 0,
                'nopaging' => true,
                'tax_query' => ''
            );

            if ( $categories != '' && isset( $taxonomy ) && $taxonomy != '' ) {
                $iscat_array = true;

                if ( strpos( $categories, ',' ) ) {
                    $cat_array = explode( ',', str_replace( ' ', '', $categories ) );

                    $args['tax_query'] = array(
                        array(
                            'taxonomy' => $taxonomy,
                            'field'  => 'slug',
                            'terms'  => $cat_array
                        )
                    );
                } else {
                    $cat_array = array( $categories );
                    $args['tax_query'] = array(
                        array(
                            'taxonomy' => $taxonomy,
                            'field'  => 'slug',
                            'terms'  => array( $categories )
                        )
                    );
                }
            }

            if ( $include_post_ids != '' ) {
                if ( strpos( $include_post_ids, ',' ) ) {
                    $id_array = explode( ',', $include_post_ids );
                    $args['post__in'] = $id_array;
                } else {
                    $args['post__in'] = array( $include_post_ids );
                }
            }

            if ( empty( $use_current_wpquery ) ) {
                $post_query = new WP_Query( $args );
            } else if ( $use_current_wpquery ) {
                if ( !empty( $posts_per_page ) ) {
                    $wp_query->set( 'posts_per_page', $posts_per_page );
                    $wp_query = new WP_Query($wp_query->query_vars);
                }

                $post_query = $wp_query;
            }

            while ( $post_query->have_posts() ) {
                $post_query->the_post();

                if ( $source == "intense_clients" ) {
                    $address = get_field( 'intense_client_address' );
                }

                if ( $source == "intense_events" ) {
                    $address = get_field( 'intense_event_address' );
                }

                if ( $source == "intense_jobs" ) {
                    $address = get_field( 'intense_job_location' );
                }

                if ( $source == "intense_locations" ) {
                    $address = get_field( 'intense_location_address' );
                }

                if ( $source == "intense_project" ) {
                    $address = get_field( 'intense_project_location_address' );
                }

                if ( $source == "intense_team" ) {
                    $address = get_field( 'intense_member_address' );
                }

                $title = get_the_title();

                $output .= $this->build_marker( $random, $bounds, $address, $latitude, $longitude, $animation, $markertype, $markertext, $markerimage, $markershadow, $anchor, $shadowanchor, $color, $iconsource, $icontype, $iconwidth, $iconheight, $title, $description );
            }

            if ( !empty( $use_current_wpquery ) && $use_current_wpquery ) {
                wp_reset_postdata();
            }
        } else {
            $output = $this->build_marker( $random, $bounds, $address, $latitude, $longitude, $animation, $markertype, $markertext, $markerimage, $markershadow, $anchor, $shadowanchor, $color, $iconsource, $icontype, $iconwidth, $iconheight, $title, $description );
        }
        
        return $output;
    }

    function build_marker( $random, $bounds, $address, $latitude, $longitude, $animation, $markertype, $markertext, $markerimage, $markershadow, $anchor, $shadowanchor, $color, $iconsource, $icontype, $iconwidth, $iconheight, $title, $description ) {
        $output = '';
        $random_marker = rand();

        $output .= 'var infowindow' . $random_marker . ' = null;';

        //SETUP MARKER
        if ( !empty( $markerimage ) ) {
            $output .= '    image' . $random_marker . ' = {';
            $output .= '        url: "' . $markerimage . '",';
            //$output .= '      size: new google.maps.Size(32, 32),';
            //$output .= '      origin: new google.maps.Point(0, 0),';
            $output .= '        anchor: new google.maps.Point(' . $anchor . ')';
            $output .= '    };';

            if ( !empty( $markershadow ) ) {
                $output .= '    shadow' . $random_marker . ' = {';
                $output .= '        url: "' . $markershadow . '",';
                $output .= '        anchor: new google.maps.Point(' . $shadowanchor . ')';
                $output .= '    };';
            }

            $output .= '    marker' . $random_marker . ' = new google.maps.Marker({';

            if ( !empty( $latitude ) && !empty( $longitude ) ) {
                $output .= '      position: new google.maps.LatLng(' . $latitude . ', ' . $longitude . '),';
            }

            if ( !empty( $animation ) ) {
                $output .= '      animation: google.maps.Animation.' . strtoupper( $animation ) . ',';
            }

            $output .= '        icon: image' . $random_marker . ',';

            if ( !empty( $markershadow ) ) {
                $output .= '        shadow: shadow' . $random_marker . ',';
            }

            $output .= '        map: map' . $random . '';
            $output .= '    });';
        } elseif ( strtoupper( $markertype ) == 'ICON' && $markerimage == '' ) {
            if ( !empty( $iconsource ) && !empty( $icontype ) ) {
                $width = '32';
                $height = '32';
                //$fill = '';
                $intense_icon = new Intense_Icon();
                $iconurl = $intense_icon->get_svg_url( $iconsource, $icontype );

                // //Icon using SVG URL
                $output .= '    image' . $random_marker . ' = {';
                $output .= '        url: "' . $iconurl . '",';

                // //Icon using path
                // $output .= '    var xml=\'' . preg_replace( "/\r|\n/", "", $intense_icon->get_svg( $iconsource, $icontype, 'svg', $height, $width, $fill ) ) . '\';';
                // $output .= '    var icon_path = "";';
                // $output .= '    jQuery(xml).find("path").each(function(i,j)';
                // $output .= '    {';
                // $output .= '     icon_path += jQuery(j).attr("d");';
                // //$output .= '     return false;';
                // $output .= '    });';
                // $output .= '    image' . $random_marker . ' = {';
                // $output .= '        path: icon_path,';
                // $output .= '        fillColor: "' . $color . '",';
                // $output .= '        fillOpacity: 0.8,';
                // $output .= '        strokeWeight: 1,';
                // $output .= '        strokeColor: "#333",';
                // $output .= '        scale: 1,';

                if ( !empty( $iconwidth ) ) {
                    $width = $iconwidth;
                }

                if ( !empty( $iconheight ) ) {
                    $height = $iconheight;
                }

                $output .= '        size: new google.maps.Size(' . $height . ', ' . $width . '),';
                $output .= '        scaledSize: new google.maps.Size(' . $height . ', ' . $width . '),';
                //$output .= '      origin: new google.maps.Point(0, 0),';
                $output .= '        anchor: new google.maps.Point(' . $anchor . ')';
                $output .= '    };';

                $output .= '    marker' . $random_marker . ' = new google.maps.Marker({';

                if ( !empty( $animation ) ) {
                    $output .= '      animation: google.maps.Animation.' . strtoupper( $animation ) . ',';
                }

                $output .= '        icon: image' . $random_marker . ',';
                $output .= '        map: map' . $random . ',';
                $output .= '        optimized: false';
                $output .= '    });';
            }
        } else {
            $output .= '    marker' . $random_marker . ' = new StyledMarker({';

            if ( strtoupper( $markertype ) == 'MARKER' ) {
                if ( !empty( $markertext ) ) {
                    $output .= '      styleIcon: new StyledIcon(StyledIconTypes.MARKER,{color:"' . ( !empty( $color ) ? $color : $intense_visions_options['intense_icon_color'] ) . '", text:"' . $markertext . '"}),';
                } else {
                    $output .= '      styleIcon: new StyledIcon(StyledIconTypes.MARKER,{color:"' . ( !empty( $color ) ? $color : $intense_visions_options['intense_icon_color'] ) . '"}),';
                }
            } elseif ( strtoupper( $markertype ) == 'BUBBLE' && $markerimage == '' ) {
                $output .= '      styleIcon: new StyledIcon(StyledIconTypes.BUBBLE,{color:"' . ( !empty( $color ) ? $color : $intense_visions_options['intense_icon_color'] ) . '", text:"' . $markertext . '"}),';
            }

            $output .= '        draggable: false,';

            if ( !empty( $latitude ) && !empty( $longitude ) ) {
                $output .= '      position: new google.maps.LatLng(' . $latitude . ', ' . $longitude . '),';
            }

            if ( !empty( $animation ) ) {
                $output .= '      animation: google.maps.Animation.' . strtoupper( $animation ) . ',';
            }

            $output .= '        map: map' . $random . '';
            $output .= '    });';
        }
        //END MARKER

        if ( !empty( $address ) ) {
            $output .= 'var geocoder' . $random_marker . ' = new google.maps.Geocoder();';
            $output .= 'geocoder' . $random_marker . '.geocode({ "address": "' . $address . '" }, function (results, status) {';
            $output .= '  if (status == google.maps.GeocoderStatus.OK) {';
            $output .= '    marker' . $random_marker . '.setPosition(new google.maps.LatLng(results[0].geometry.location.lat(), results[0].geometry.location.lng()));';

            if ( $bounds == 1 ) {
                $output .= '    bounds' . $random . '.extend(new google.maps.LatLng(results[0].geometry.location.lat(), results[0].geometry.location.lng()));';
                $output .= '    map' . $random . '.fitBounds(bounds' . $random . ');';
            } else {
                $output .= '    map' . $random . '.setCenter(new google.maps.LatLng(results[0].geometry.location.lat(), results[0].geometry.location.lng()));';
            }
            $output .= '  }';
            $output .= '});';
        }

        $output .= 'infowindow = new google.maps.InfoWindow({';
        $output .= 'content: "loading..."';
        $output .= '});';

        if ( $animation == 'BOUNCE' ) {
            $output .= 'google.maps.event.addListener(marker' . $random_marker . ', "click", function() {';
            $output .= '  infowindow.setContent("<b>' . $title . '</b><br />' . $address . '<br />' . $description . '");';
            $output .= '  infowindow.open(map' . $random . ', this);';
            $output .= '  toggleBounce("' . $random_marker . '")';
            $output .= '});';
        } else {
            $output .= 'google.maps.event.addListener(marker' . $random_marker . ', "click", function () {';
            $output .= '  infowindow.setContent("<b>' . $title . '</b><br />' . $address . '<br />' . $description . '");';
            $output .= '  infowindow.open(map' . $random . ', this);';
            $output .= '});';
        }

        return $output;
    }

}
