// Quick feature detection
function isTouchEnabled() {
    return (('ontouchstart' in window)
        || (navigator.MaxTouchPoints > 0)
        || (navigator.msMaxTouchPoints > 0));
}

jQuery(function(){
    addEvent('st_1');addEvent('st_2');addEvent('st_3');addEvent('st_4');addEvent('st_5');addEvent('st_6');addEvent('st_7');addEvent('st_8');addEvent('st_9');addEvent('st_10');addEvent('st_11');addEvent('st_12');addEvent('st_13');addEvent('st_14');addEvent('st_15');addEvent('st_16');addEvent('st_17');addEvent('st_18');addEvent('st_19');addEvent('st_20');addEvent('st_21');addEvent('st_22');addEvent('st_23');addEvent('st_24');addEvent('st_25');addEvent('st_26');addEvent('st_27');addEvent('st_28');addEvent('st_29');addEvent('st_30');addEvent('st_31');addEvent('st_32');addEvent('st_33');addEvent('st_34');addEvent('st_35');addEvent('st_36');addEvent('st_37');addEvent('st_38');addEvent('st_39');addEvent('st_40');addEvent('st_41');addEvent('st_42');addEvent('st_43');addEvent('st_44');addEvent('st_45');addEvent('st_46');addEvent('st_47');addEvent('st_48');addEvent('st_49');addEvent('st_50');addEvent('st_51');addEvent('st_52');addEvent('st_53');addEvent('st_54');addEvent('st_55');
})
jQuery(function(){
    jQuery('#lakes').find('path').attr({'fill':map_config['default']['lakesFill']}).css({'stroke':map_config['default']['lakesOutline']});
    jQuery('#mapshadow').find('path').attr({'fill':map_config['default']['mapShadow']});
})

var fields_basic = {
    'field_program_logo' : 'Logo',
    'field_program_card' : 'Card',
    'field_snap_program_name' : 'Program Name',
    'field_name_of_state_s_ebt_card' : 'EBT Card Name'
};

var fields_snapinfo = {
    'field_program_web_site' : 'State SNAP Website',
    'field_state_hotline_phone_number' : 'Hotline',
    'field_state_list_of_local_office' : 'Local Offices',
    'field_benefit_issuance_schedules' : 'Issuance Schedule',
    'field_employment_and_training_e_' : 'Employment/Training',
};

var fields_applications = {
//    'field_state_pre_screening_tool' : 'Pre-Screeing Tool',
    'field_state_online_application' : 'Online Application',
    'field_paper_applications' : 'Paper Applications',
    'field_other_applications' : 'Other Applications'
};

var fields_ebtinfo = {
    'field_program_card' : 'EBT Card',
    'field_state_ebt_web_site' : 'EBT Website',
    'field_ebt_hotline_number' : 'EBT Hotline'
};

function addEvent(id,relationId){
    var _obj = jQuery('#'+id);
    var _Textobj = jQuery('#'+id+','+'#'+map_config[id]['iso']);

    jQuery('#'+['text-abb']).attr({'fill':map_config['default']['namesColor']});

    _obj.attr({'fill':map_config[id]['upColor'],'stroke':map_config['default']['borderColor']});
    _Textobj.attr({'cursor':'default'});
    if(map_config[id]['enable'] == true){
        if (isTouchEnabled()) {
            //clicking effect
            _Textobj.on('touchstart', function(e){
                var touch = e.originalEvent.touches[0];
                var x=touch.pageX+10, y=touch.pageY+15;
                var tipw=jQuery('#map-tip-us').outerWidth(), tiph=jQuery('#map-tip-us').outerHeight(),
                    x=(x+tipw>jQuery(document).scrollLeft()+jQuery(window).width())? x-tipw-(20*2) : x
                    y=(y+tiph>jQuery(document).scrollTop()+jQuery(window).height())? jQuery(document).scrollTop()+jQuery(window).height()-tiph-10 : y
                    jQuery('#'+id).css({'fill':map_config[id]['downColor']});
//                    jQuery('#map-tip-us').show().html(map_config[id]['hover']);
//                    jQuery('#map-tip-us').css({left:x, top:y})
            })
            _Textobj.on('touchend', function(){
                jQuery('#'+id).css({'fill':map_config[id]['upColor']});
                jQuery.getJSON(map_config[id]['url'] + '?_format=json', function(data){
                var items = [];
                var snapInfoItems = [];
                var snapApplicationItems = [];
                var snapEBTItems = [];
                var title = '';
                var infotitle = '';
                var applicationtitle = '';
                var ebttitle = '';
                jQuery.each(data, function(index, details) {
                    if (details.hasOwnProperty('title')) {
                        title = '<h3>' + details['title'][0]['value'] + '</h3>';
                    }
                    jQuery.each(fields_basic, function(fieldname, fieldlabel) {
                        if (details.hasOwnProperty(fieldname) && null != details[fieldname][0]) {
                            if (fieldname == "field_snap_program_name") {
                                items.push("<h4>Program Name</h4>");
                            }
                            if (details[fieldname][0]['value'] != null) {
                                items.push("<li id='" + fieldname + "'>" + details[fieldname][0]['value'] + "</li>");
                            }
                            if (details[fieldname][0]['uri'] != null) {
                                items.push("<li id='" + fieldname + "'><a target='_blank' href='" + details[fieldname][0]['uri'] + "'>" + details[fieldname][0]['title'] + "</a></li>")
                            }
                        }
                    });
                    jQuery.each(fields_snapinfo, function(fieldname, fieldlabel) {
                        if (details.hasOwnProperty(fieldname) && null != details[fieldname][0]) {
                            if (details[fieldname][0]['value'] != null) {
                                snapInfoItems.push("<li id='" + fieldname + "'>" + details[fieldname][0]['value'] + "</li>");
                            }
                            if (details[fieldname][0]['uri'] != null) {
                                snapInfoItems.push("<li id='" + fieldname + "'><a target='_blank' href='" + details[fieldname][0]['uri'] + "'>" + details[fieldname][0]['title'] + "</a></li>")
                            }
                            if (details[fieldname][0]['url'] != null) {
                                items.push("<li id='" + fieldname + "' style='display:inline-block; margin-right:10px;'><img src='" + details[fieldname][0]['url'] + "' alt='" + details[fieldname][0]['url'] + "' style='max-width: 200px; float:none;'/></li>");
                            }
                        }
                    });
                    jQuery.each(fields_applications, function(fieldname, fieldlabel) {
                      if (details.hasOwnProperty(fieldname) && null != details[fieldname][0]) {
                        for (var application in details[fieldname]) {
                          const hasProp = details[fieldname].hasOwnProperty(application);
                          if (hasProp && details[fieldname][application]['value'] != null) {
                            snapApplicationItems.push("<li id='" + fieldname + '_' + application +"'>" + details[fieldname][application]['value'] + "</li>");
                          }
                          if (hasProp && details[fieldname][application]['uri'] != null) {
                            snapApplicationItems.push("<li id='" + fieldname + '_' + application + "'><a target='_blank' href='" + details[fieldname][application]['uri'] + "'>" + details[fieldname][application]['title'] + "</a></li>")
                          }
                          if (hasProp && details[fieldname][application]['url'] != null) {
                            items.push("<li id='" + fieldname + '_' + application + "'><img src='" + details[fieldname][application]['url'] + "' alt='" + details[fieldname][application]['url'] + "' style='max-width: 200px; float:none;'/></li>");
                          }
                        }
                      }
                    });
                    jQuery.each(fields_ebtinfo, function(fieldname, fieldlabel) {
                        if (details.hasOwnProperty(fieldname) && null != details[fieldname][0]) {
                            if (details[fieldname][0]['value'] != null) {
                                snapEBTItems.push("<li id='" + fieldname + "'>" + details[fieldname][0]['value'] + "</li>");
                            }
                            if (details[fieldname][0]['uri'] != null) {
                                snapEBTItems.push("<li id='" + fieldname + "'><a target='_blank' href='" + details[fieldname][0]['uri'] + "'>" + details[fieldname][0]['title'] + "</a></li>")
                            }
                            if (details[fieldname][0]['url'] != null) {
                                items.push("<li id='" + fieldname + "' style='display:inline-block; margin-right:10px;'><img src='" + details[fieldname][0]['url'] + "' alt='" + details[fieldname][0]['url'] + "' style='max-width: 200px; float:none;'/></li>");
                            }
                        }
                    });
                });
                if (snapInfoItems.length > 0) {
                  infotitle = '<h4>State SNAP Information</h4>';
                }
                if (snapApplicationItems.length > 0) {
                  applicationtitle = '<h4>State Applications</h4>';
                }
                if (snapEBTItems.length > 0) {
                  ebttitle = '<h4>State EBT Information</h4>';
                }
                jQuery('#map-tip-us').show().html(title + "<ul>" + items.join("") + "</ul>"
                        + infotitle + "<ul>" + snapInfoItems.join("") + "</ul>"
                        + applicationtitle + "<ul>" + snapApplicationItems.join("") + "</ul>"
                        + ebttitle + "<ul>" + snapEBTItems.join("") + "</ul>");
            });
            if (map_config[id]['target'] == 'new_window'){
//                window.open(map_config[id]['url']);
            } else if (map_config[id]['target'] == 'same_window'){
//                window.parent.location.href=map_config[id]['url'];
            }
        })
    }
        _Textobj.attr({'cursor':'pointer'});
        _Textobj.hover(function(){
            //moving in/out effect
            //jQuery('#map-tip-us').show().html(map_config[id]['hover']);
            _obj.css({'fill':map_config[id]['overColor']});
        },function(){
            //jQuery('#map-tip-us').hide();
            jQuery('#'+id).css({'fill':map_config[id]['upColor']});
        });
        //clicking effect
        _Textobj.mouseup(function(){
            jQuery('#'+id).css({'fill':map_config[id]['overColor']});
        });
        _Textobj.mousedown(function(e){
            jQuery('#'+id).css({'fill':map_config[id]['downColor']});
            jQuery.getJSON(map_config[id]['url'] + '?_format=json', function(data){
                var items = [];
                var snapInfoItems = [];
                var snapApplicationItems = [];
                var snapEBTItems = [];
                var title = '';
                var infotitle = '';
                var applicationtitle = '';
                var ebttitle = '';
                jQuery.each(data, function(index, details) {
                    if (details.hasOwnProperty('title')) {
                        title = '<h3>' + details['title'][0]['value'] + '</h3>';
                    }
                    jQuery.each(fields_basic, function(fieldname, fieldlabel) {
                        if (details.hasOwnProperty(fieldname) && null != details[fieldname][0]) {
                            if (fieldname == "field_snap_program_name") {
                                items.push("<h4>Program Name</h4>");
                            }
                            if (details[fieldname][0]['value'] != null) {
                                items.push("<li id='" + fieldname + "'>" + details[fieldname][0]['value'] + "</li>");
                            }
                            if (details[fieldname][0]['uri'] != null) {
                                items.push("<li id='" + fieldname + "'><a target='_blank' href='" + details[fieldname][0]['uri'] + "'>" + details[fieldname][0]['title'] + "</a></li>")
                            }
                            if (details[fieldname][0]['url'] != null) {
                                items.push("<li id='" + fieldname + "' style='display:inline-block; margin-right:10px;'><img src='" + details[fieldname][0]['url'] + "' alt='" + details[fieldname][0]['url'] + "' style='max-width: 200px; float:none;'/></li>");
                            }
                        }
                    });
                    jQuery.each(fields_snapinfo, function(fieldname, fieldlabel) {
                        if (details.hasOwnProperty(fieldname) && null != details[fieldname][0]) {
                            if (details[fieldname][0]['value'] != null) {
                                snapInfoItems.push("<li id='" + fieldname + "'>" + details[fieldname][0]['value'] + "</li>");
                            }
                            if (details[fieldname][0]['uri'] != null) {
                                snapInfoItems.push("<li id='" + fieldname + "'><a target='_blank' href='" + details[fieldname][0]['uri'] + "'>" + details[fieldname][0]['title'] + "</a></li>")
                            }
                            if (details[fieldname][0]['url'] != null) {
                                items.push("<li id='" + fieldname + " style='display:inline-block; margin-right:10px;'><img src='" + details[fieldname][0]['url'] + "' alt='" + details[fieldname][0]['url'] + "' style='max-width: 200px; float:none;'/></li>");
                            }
                        }
                    });
                    jQuery.each(fields_applications, function(fieldname, fieldlabel) {
                      if (details.hasOwnProperty(fieldname) && null != details[fieldname][0]) {
                        for (var application in details[fieldname]) {
                          const hasProp = details[fieldname].hasOwnProperty(application);
                          if (hasProp && details[fieldname][application]['value'] != null) {
                            snapApplicationItems.push("<li id='" + fieldname + '_' + application +"'>" + details[fieldname][application]['value'] + "</li>");
                          }
                          if (hasProp && details[fieldname][application]['uri'] != null) {
                            snapApplicationItems.push("<li id='" + fieldname + '_' + application + "'><a target='_blank' href='" + details[fieldname][application]['uri'] + "'>" + details[fieldname][application]['title'] + "</a></li>")
                          }
                          if (hasProp && details[fieldname][application]['url'] != null) {
                            items.push("<li id='" + fieldname + '_' + application + "'><img src='" + details[fieldname][application]['url'] + "' alt='" + details[fieldname][application]['url'] + "' style='max-width: 200px; float:none;'/></li>");
                          }
                        }
                      }
                    });
                    jQuery.each(fields_ebtinfo, function(fieldname, fieldlabel) {
                        if (details.hasOwnProperty(fieldname) && null != details[fieldname][0]) {
                            if (details[fieldname][0]['value'] != null) {
                                snapEBTItems.push("<li id='" + fieldname + "'>" + details[fieldname][0]['value'] + "</li>");
                            }
                            if (details[fieldname][0]['uri'] != null) {
                                snapEBTItems.push("<li id='" + fieldname + "'><a target='_blank' href='" + details[fieldname][0]['uri'] + "'>" + details[fieldname][0]['title'] + "</a></li>")
                            }
                        }
                    });
                });
                if (snapInfoItems.length > 0) {
                  infotitle = '<h4>State SNAP Information</h4>';
                }
                if (snapApplicationItems.length > 0) {
                  applicationtitle = '<h4>State Applications</h4>';
                }
                if (snapEBTItems.length > 0) {
                  ebttitle = '<h4>State EBT Information</h4>';
                }

                var offset = jQuery('#mapwrapper').offset();
                var x = ((e.pageX - offset.left) > (jQuery('#mapwrapper').innerWidth()-400))? (jQuery('#mapwrapper').innerWidth()-400) : (e.pageX - offset.left)
                var y = ((e.pageY - offset.top) > (jQuery('#mapwrapper').innerHeight()-300))? (jQuery('#mapwrapper').innerHeight()-300) : (e.pageY - offset.top)
                jQuery('#map-tip-us').show().html("<span id='close-info'>x</span>" + title + "<ul>" + items.join("") + "</ul>"
                        + infotitle + "<ul>" + snapInfoItems.join("") + "</ul>"
                        + applicationtitle + "<ul>" + snapApplicationItems.join("") + "</ul>"
                        + ebttitle + "<ul>" + snapEBTItems.join("") + "</ul>");

                var stys = {};
                if (x > 0) {
                  jQuery('#map-tip-us').css({'left': x});
                }

                jQuery('#close-info').mousedown(function(){
                    jQuery('#map-tip-us').hide();
                })
            });
            if (map_config[id]['target'] == 'new_window') {
//                window.open(map_config[id]['url']);
            } else if(map_config[id]['target'] == 'same_window') {
//                window.parent.location.href=map_config[id]['url'];
            }
        })
//        _Textobj.mousemove(function(e){
//            var x=e.pageX+10, y=e.pageY+15;
//            var tipw=jQuery('#map-tip-us').outerWidth(), tiph=jQuery('#map-tip-us').outerHeight(),
//            x=(x+tipw>jQuery(document).scrollLeft()+jQuery(window).width())? x-tipw-(20*2) : x,
//            y=(y+tiph>jQuery(document).scrollTop()+jQuery(window).height())? jQuery(document).scrollTop()+jQuery(window).height()-tiph-10 : y
//            jQuery('#map-tip-us').css({left:x, top:y})
//        })
    }
}

//The pins code
jQuery(function(){
    if('undefined' != typeof pins_config){
        if(jQuery('#pin-shadow').find('path').eq(0).attr('fill') != 'undefined'){
            var pinShadowOpacity = pins_config['default']['pinShadowOpacity'];
            var pinShadowOpacity = parseInt(pinShadowOpacity);
            if (pinShadowOpacity >=100){pinShadowOpacity = 1;}else if(pinShadowOpacity <=0){pinShadowOpacity =0;}else{pinShadowOpacity = pinShadowOpacity/100;}

            jQuery('#pin-shadow').find('path').attr({'fill':pins_config['default']['pinShadow']}).css({'fill-opacity':pinShadowOpacity})
        };

        var points_len = pins_config['points'].length;
        if( points_len > 0){
            var xmlns = "http://www.w3.org/2000/svg";
            var tsvg_obj = document.getElementById("map_points");
            var svg_circle,svg_rect;
            for(var i=0;i<points_len;i++){
                if (pins_config['points'][i]['shape']=="circle"){
                    svg_circle = document.createElementNS(xmlns, "circle");
                    svg_circle.setAttributeNS(null, "cx", pins_config['points'][i]['pos_X']+1);
                    svg_circle.setAttributeNS(null, "cy", pins_config['points'][i]['pos_Y']+1);
                    svg_circle.setAttributeNS(null, "r", pins_config['points'][i]['diameter']/2);
                    svg_circle.setAttributeNS(null, "fill", pins_config['default']['pinShadow']);
                    svg_circle.setAttributeNS(null, "style",'fill-opacity:'+pinShadowOpacity);
                    svg_circle.setAttributeNS(null, "id",'map_points_shadow_'+i);
                    tsvg_obj.appendChild(svg_circle);
                    svg_circle = document.createElementNS(xmlns, "circle");
                    svg_circle.setAttributeNS(null, "cx", pins_config['points'][i]['pos_X']);
                    svg_circle.setAttributeNS(null, "cy", pins_config['points'][i]['pos_Y']);
                    svg_circle.setAttributeNS(null, "r", pins_config['points'][i]['diameter']/2);
                    svg_circle.setAttributeNS(null, "fill", pins_config['points'][i]['upColor']);
                    svg_circle.setAttributeNS(null, "stroke",pins_config['points'][i]['outline']);
                    svg_circle.setAttributeNS(null, "stroke-width",pins_config['points'][i]['thickness']);
                    svg_circle.setAttributeNS(null, "id",'map_points_'+i);
                    tsvg_obj.appendChild(svg_circle);
                    dynamicAddEvent(i);
                }
                else if(pins_config['points'][i]['shape']=="rectangle"){
                    svg_rect = document.createElementNS(xmlns, "rect");
                    svg_rect.setAttributeNS(null, "x", pins_config['points'][i]['pos_X']- pins_config['points'][i]['width']/2+1);
                    svg_rect.setAttributeNS(null, "y", pins_config['points'][i]['pos_Y']- pins_config['points'][i]['height']/2+1);
                    svg_rect.setAttributeNS(null, "width", pins_config['points'][i]['width']);
                    svg_rect.setAttributeNS(null, "height", pins_config['points'][i]['height']);
                    svg_rect.setAttributeNS(null, "fill", pins_config['default']['pinShadow']);
                    svg_rect.setAttributeNS(null, "style",'fill-opacity:'+pinShadowOpacity);
                    svg_rect.setAttributeNS(null, "id",'map_points_shadow_'+i);
                    tsvg_obj.appendChild(svg_rect);
                    svg_rect = document.createElementNS(xmlns, "rect");
                    svg_rect.setAttributeNS(null, "x", pins_config['points'][i]['pos_X']- pins_config['points'][i]['width']/2);
                    svg_rect.setAttributeNS(null, "y", pins_config['points'][i]['pos_Y']- pins_config['points'][i]['height']/2);
                    svg_rect.setAttributeNS(null, "width", pins_config['points'][i]['width']);
                    svg_rect.setAttributeNS(null, "height", pins_config['points'][i]['height']);
                    svg_rect.setAttributeNS(null, "fill", pins_config['points'][i]['upColor']);
                    svg_rect.setAttributeNS(null, "stroke",pins_config['points'][i]['outline']);
                    svg_rect.setAttributeNS(null, "stroke-width",pins_config['points'][i]['thickness']);
                    svg_rect.setAttributeNS(null, "id",'map_points_'+i);
                    tsvg_obj.appendChild(svg_rect);
                    dynamicAddEvent(i);
                }
            }
        }
    }
});

function dynamicAddEvent(id){
    var obj = jQuery('#map_points_'+id);

    if(pins_config['points'][id]['enable'] == true){
        if (isTouchEnabled()) {
            obj.on('touchstart', function(e){
                var touch = e.originalEvent.touches[0];
                var x=touch.pageX+10, y=touch.pageY+15;
                var tipw=jQuery('#map-tip-us').outerWidth(), tiph=jQuery('#map-tip-us').outerHeight(),
                x=(x+tipw>jQuery(document).scrollLeft()+jQuery(window).width())? x-tipw-(20*2) : x
                y=(y+tiph>jQuery(document).scrollTop()+jQuery(window).height())? jQuery(document).scrollTop()+jQuery(window).height()-tiph-10 : y
                jQuery('#'+id).css({'fill':pins_config['points'][id]['downColor']});
                //jQuery('#map-tip-us').show().html(pins_config['points'][id]['hover']);
                //jQuery('#map-tip-us').css({left:x, top:y})
            })
            obj.on('touchend', function(){
                jQuery('#'+id).css({'fill':pins_config['points'][id]['upColor']});
                if(pins_config['points'][id]['target'] == 'new_window'){
                    window.open(pins_config['points'][id]['url']);
                }else if(pins_config['points'][id]['target'] == 'same_window'){
                    window.parent.location.href=pins_config['points'][id]['url'];
                }
            })
        }
        obj.attr({'cursor':'pointer'});
        obj.hover(function(){
            //jQuery('#map-tip-us').show().html(pins_config['points'][id]['hover']);
            obj.css({'fill':pins_config['points'][id]['overColor']});
        },function(){
            //jQuery('#map-tip-us').hide();
            obj.css({'fill':pins_config['points'][id]['upColor']});
        })
        //clicking effect
        obj.mousedown(function(){
            obj.css({'fill':pins_config['points'][id]['downColor']});
        })
        obj.mouseup(function(){
            obj.css({'fill':pins_config['points'][id]['overColor']});
            if(pins_config['points'][id]['target'] == 'new_window'){
                window.open(pins_config['points'][id]['url']);
            }else if(pins_config['points'][id]['target'] == 'same_window'){
                window.parent.location.href=pins_config['points'][id]['url'];
            }
        })
        obj.mousemove(function(e){
            var x=e.pageX+10, y=e.pageY+15;
            var tipw=jQuery('#map-tip-us').outerWidth(), tiph=jQuery('#map-tip-us').outerHeight(),
            x=(x+tipw>jQuery(document).scrollLeft()+jQuery(window).width())? x-tipw-(20*2) : x
            y=(y+tiph>jQuery(document).scrollTop()+jQuery(window).height())? jQuery(document).scrollTop()+jQuery(window).height()-tiph-10 : y
            jQuery('#map-tip-us').css({left:x})
        })
    }
}