InHomeCare = function() {

    this.initialize();
    this.appMap = null;
    this.marker = null;
}

$.extend(InHomeCare.prototype, {
    initialize: function() {
        this.setListeners();
        this.createHelpTip();
    },

    createHelpTip: function(){
        this.helpTip = $('#help').qtip({
            content: $('#helpTip'),
            position: {
                corner: {
                    target: 'bottomMiddle',
                    tooltip: 'topMiddle'
                }
            },
            show: {
                when: {
                    event: 'click'
                },
                delay: 0,
                effect: {
                    length: 0
                }
            },
            hide: {
                when: {
                    event: 'mouseout'
                },
                delay: 0,
                fixed:true,
                effect: {
                    length: 0
                }
            },
            style:{
                width: 400,
                //tip: 'topMiddle',
                border: {
                    width: 1,
                    radius: 3,
                    color: '#543C3C'
                }

            }
        });
        $('#featuredLogo').qtip({
            content: $('#featuredTip'),
            position: {
                corner: {
                    target: 'bottomMiddle',
                    tooltip: 'topMiddle'
                }
            },
            show: {
                when: {
                    event: 'mouseover'
                },
                delay: 0,
                effect: {
                    length: 0
                }
            },
            hide: {
                when: {
                    event: 'mouseout'
                },
                delay: 0,
                fixed:true,
                effect: {
                    length: 0
                }
            },
            style:{
                width: 400,
                //tip: 'topMiddle',
                border: {
                    width: 1,
                    radius: 3,
                    color: '#543C3C'
                }

            }
        });

    },

    initializeAppMap: function(lat, lng) {
        var self = this;

        this.appMap = new google.maps.Map(document.getElementById("mapContainer"), {
            zoom: 4,
            center: new google.maps.LatLng(lat, lng),
            mapTypeId: google.maps.MapTypeId.ROADMAP,
            navigationControlOptions: {
                style: google.maps.NavigationControlStyle.SMALL
            },
            streetViewControl: false,
            mapTypeControl: false,
            noClear: true
        });
        google.maps.event.addListener(this.appMap, 'bounds_changed', function() {self.updatePositionForActiveMapTip()});
        google.maps.event.addListener(this.appMap, 'idle', function() {self.updatePositionForActiveMapTip()});

        this.geocoder = new google.maps.Geocoder();
    },

    updatePositionForActiveMapTip: function() {
        if(this.marker && this.marker.tip){
            if(this.marker.visible()) {
                return this.marker.tip.qtip('api').updatePosition();
            }
            else {
                this.marker.tip.qtip('hide');
            }
        } else {
            //console.log('no marker');
        }
    },

    hideAllMapMarkerTips: function() {
        $.each(this.appMapMarkers, function(index, marker) {
            if(marker.active) {
                marker.tip.qtip('hide');
            }
        });
    },

    setListeners: function(){
        var self = this;
        $('.appButton').bind('click', function(event){
            event.stopPropagation();
            $('#draggableMarker').css({'backgroundPosition':'0 0px'});
            $('button.appButton img').attr('src', "/images/placed.gif");
            self.placeMarker();
        });
    },

    placeMarker: function() {
        var self = this;
        //Don't let them drag the map

        this.appMap.setOptions({
            draggable:false
        });
        //set the right cursor - A Map Marker
        $('body').css('cursor', "url(/images/ihcMarker.cur) 9 23, url(\"images/ihcMarker.png\") 9 23,  url(images/ihcMarker.cur) 9 23, crosshair");
        // if they click not on the map turn it all off
        $('body').click(function(event){
            google.maps.event.removeListener(placeMarker);
            self.appMap.setOptions({
                draggable:true
            });
            $('body').css('cursor', 'default');
        });


        // place a map marker using a click lisenter
        var placeMarker = google.maps.event.addListener(this.appMap, 'click', function(mouseEvent) {
            //console.log(mouseEvent.latLng);
            // get the geocode information
                if(self.marker != null){
                    self.marker.setMap(null);
                }
                

                self.marker = new InHomeCareMarker(mouseEvent.latLng, self.appMap, '<h3>Searching...</h3>', '<img src="/images/loading.gif" />');
            self.geocoder.geocode({
                latLng:mouseEvent.latLng
                } , function(response, status){
                if(!response[0].formatted_address.match(/USA/)){
                    
                    var tipTitle = '<h3>Uncovered Area</h3>';
                    var tipContent = '<div class="windowContent">Areas out of the United States are not currently covered by InHomeCare.com</div>';
                    $(self.marker.div_).qtip("api").updateTitle(tipTitle);
                    $(self.marker.div_).qtip("api").updateContent(tipContent);
                } else {
                    var zipcode = null;
                    var name = '';
                    //find the zip code - search all the responses
                    $.each(response, function(index, address){
                        //console.log(address.formatted_address);
                        //find the state and zip, to prevent street address matches
                        zipcode = address.formatted_address.match(/\b\w{2}\b\s(\b\d{5}\b)/)
                        if(zipcode != null && zipcode[1] != null){
                            zipcode = zipcode[1];
                        }
                        if (zipcode !== null){
                            name = address.formatted_address.match(/([\w+\s]+,)?\s?(\w{2}\s)?\d{5},(\sUSA)?/)[0];
                            return false;
                        } else {
                            return true;
                        }
                    });
                    if (name == undefined){
                        name = zipcode;
                    } else {
                        name = name.replace(', USA', '');
                    }
                    self.appMap.setOptions({
                        draggable:true
                    });
                    // search the database for the agencys
                    if(zipcode != null){
                        $.getJSON('/php/get_actions.php', {
                            zipcode:zipcode
                        } , function(json){

                            // send the data to make a new map marker using the information we gathered here
                            var tipTitle = '<h3>In-Home Care Agencies for '+name+'</h3>';
                            var tipContent = '<div class="windowContent">'+json.response+'</div>';

                            $(self.marker.div_).qtip("api").updateTitle(tipTitle);
                            $(self.marker.div_).qtip("api").updateContent(tipContent);
                            $(self.marker.div_).qtip("api").updateWidth();
                            
                        //self.marker = new InHomeCareMarker(mouseEvent.latLng, self.appMap, tipTitle, tipContent);
                        //newMapMarker(data);

                        });
                        
                    }
                    else {
                        tipTitle = '<h3>Oops, looks like something is amiss.</h3>';
                        tipContent = '<div class="windowContent error"><p>It looks like the marker is not on the right spot. Although you clicked this location:</p> <p><b>'+response[0].formatted_address+' </b></p> <p> The precise spot of the marker may be on a location without a zip code, or that area may be upopulated. Try zooming in on the map and and placing the marker again.</p> <p> If you keep receiving this error, please <a href="/contact/">Contact Us.</a></p></div>';
                        $(self.marker.div_).qtip("api").updateTitle(tipTitle);
                        $(self.marker.div_).qtip("api").updateContent(tipContent);
                    //self.marker = new InHomeCareMarker(mouseEvent.latLng, self.appMap, tipTitle, tipContent);
                    }
                    self.appMap.setCenter(mouseEvent.latLng);
                }
            });
            // remove the listener
            google.maps.event.removeListener(placeMarker);
        });
    },


    serverSideMarker: function(json){
        
        if(this.marker){
            inHomeCare.marker.setMap(null);
        }
        var position = new google.maps.LatLng(json.details[1], json.details[0]);
        var self = this;
        var tipTitle = ' <h3>In-Home Care Agencies for '+json.name.replace(', USA', '')+'</h3>';
        var tipContent ='<div class="windowContent">'+ json.html+'</div>';
        this.marker = new InHomeCareMarker(position, self.appMap, tipTitle, tipContent);
        if (json.box){
            var northEast = new google.maps.LatLng(json.box.north , json.box.east);
            var southWest = new google.maps.LatLng(json.box.south, json. box.west);
            var bounds = new google.maps.LatLngBounds(southWest, northEast);
            this.appMap.fitBounds(bounds);
        }
        
    }

});




function InHomeCareMarker(latlng, map, title, content) {
    var self = this;

    this.latlng_ = latlng;
    this.active = true;
    this.img = null;
    this.image = '/images/ihcMapMarker.png'
    this.tip = null;
    this.tipContent = content;
    this.tipOptions = {
        content: {
          title: {text: title, button:'Close'},
          text:  content
        },
        position: {
            corner: {
                target: 'topMiddle',
                tooltip: 'bottomMiddle'
            },
            adjust: {
                x:-5
            }
        },
        show: {
            //ready: true,
            when: {event: 'click'},
            delay: 0,
            effect: {
                length: 0
            }
        },
        hide: {
            when: {event: 'click'},
            delay: 0,
            effect: {
                length: 0
            }
        },
        style: {
            width:{'min' : '585px'},
            border: {
                    width: 1,
                    radius: 3,
                    color: '#543C3C'
            },
            tip:'bottomMiddle',
            title: {
                'background': '#FFF',
                'font-size' : '1em',
                'border-bottom': 'thin solid #373737',
                'margin':'0.25em .5em 0',
                'padding': '0.25em .5em .15em'
            }
        }
    };
    // Once the LatLng and text are set, add the overlay to the map.  This will
    // trigger a call to panes_changed which should in turn call draw.
    this.setMap(map);
    
    if(this.tip){
        
    }
    
}

InHomeCareMarker.prototype = new google.maps.OverlayView();

InHomeCareMarker.prototype.visible = function() {
    var self = this;
    return this.map.getBounds().contains(self.latlng_);
}

InHomeCareMarker.prototype.draw = function() {
    var self = this;

    // Check if the div has been created.
    var div = this.div_;

    if(!div) {
        // Create a overlay text DIV
        div = this.div_ = document.createElement('div');
        
        // Create the DIV representing our CustomMarker
        var border = 'border:0 solid none;';
        var position = 'position:absolute;';
        var paddingLeft = 'padding:0px;';
        var cursor = 'cursor:pointer;';
        var width = 'width:28px;';
        var height = 'height:24px;';
        div.setAttribute('style', border+position+paddingLeft+cursor+width+height);

        this.img = document.createElement("img");
        this.img.src = this.image;
        div.appendChild(this.img);

        google.maps.event.addDomListener(div, "click", function(event) {
            google.maps.event.trigger(self, "click");
        });

        // Then add the overlay to the DOM
        var panes = this.getPanes();
        panes.overlayImage.appendChild(div);

        // If there is supposed to be a tooltip
        if(this.tipContent != '') {
            //this.tipOptions.content = this.tipContent;
            this.tip = $(div).qtip(self.tipOptions);
            $(div).trigger('click');
            $(div).qtip('api').updateWidth();
        }
    }

    // Position the overlay
    var point = this.getProjection().fromLatLngToDivPixel(this.latlng_);
    //console.log(point.x,', ', point.y);
    if(point) {
        //div.style.position = 'absolute';
        div.style.left = point.x - 6 + 'px';
        div.style.top = point.y - 24 + 'px';
    }
};

InHomeCareMarker.prototype.onRemove = function() {
    // Check if the overlay was on the map and needs to be removed.
        inHomeCare.marker.tip.qtip('destroy');
        this.div_.parentNode.removeChild(this.div_);
        this.div_ = null;
        inHomeCare.marker = null;
};

InHomeCareMarker.prototype.getPosition = function() {
    return this.latlng_;
};

function profileTips(){
    $('.agencyRankings img').each(function(index, element){
        $(element).qtip({
            content: $('#'+$(element).attr('id')+'Tip'),
            container:$(element).parent(),
            position: {
                corner: {
                    target: 'bottomMiddle',
                    tooltip: 'topMiddle'
                }
            },
            show: {
                when: {
                    event: 'mouseover'
                },
                solo: true,
                delay: 0,
                effect: {
                    length: 250
                }
            },
            hide: {
                when: {
                    event: 'mouseout'
                },
                delay: 500,
                fixed:true,
                effect: {
                    length: 0
                }
            },
            style:{
                width: 400,
                tip:'topMiddle',
                //tip: 'topMiddle',
                border: {
                    width: 1,
                    radius: 3,
                    color: '#543C3C'
                }

            }

        });
    });
}
