﻿(function($) {
    var window = this,
		controller,
		view = {},
		model;
    var searchstring;
    var googlePoint;
    var closestClinic;

    controller = {
        addSearchButtonEvent: function() {
            $('#ctl00_FullRegion_ucSearchText').keydown(function(e) {

            });

            $('#ctl00_FullRegion_ucSearch').click(function(e) {
                e.preventDefault();
                $.view.map.map2.closeExtInfoWindow();
                $.view.map.searchMarkers(encodeURIComponent($('#ctl00_FullRegion_ucSearchText').val()));
            });
        }
    }


    view.map = {
        sensitive: parseFloat(0.25),
        sensitiveZoom: 10,
        whatId: $('body').attr('id'),
        addSearchEvents: function() {
            controller.addSearchButtonEvent();
        },

        addMarkerEvent: function(marker, url) {
            GEvent.addListener(marker, 'click', function() {
                var mLatLng = marker.getLatLng(),
					currentMarker = marker,
					listner;

                $.view.map.map2.panTo(mLatLng);

                listner = GEvent.addListener($.view.map.map2, 'moveend', function() {
                    GEvent.removeListener(listner);
                    var fixPictureBug,
						testBug;

                    currentMarker.openExtInfoWindow(
						$.view.map.map2,
						"custom_info_window_red",
						"<p id='loadingAjax'>Loading...</p>",
						{ beakOffset: 3, ajaxUrl: url }
					);

                    jQuery.view.map.url = url;

                    testBug = setTimeout(function() {
                        if ($("#popPics img").length) {
                            $("#popPics").addClass("visible");
                            if ((jQuery.browser.msie && parseInt(jQuery.browser.version, 10) === 6)) {
                                setTimeout(function() {
                                    $("#popPics").css({
                                        display: 'block',
                                        height: '90px'
                                    });
                                    jQuery.view.map.map2.getExtInfoWindow().resize();
                                }, 200);
                            }
                        }

                        jQuery.view.map.map2.getExtInfoWindow().resize();
                    }, 300);
                });

                if (mLatLng.equals($.view.map.map2.getCenter())) {
                    GEvent.trigger($.view.map.map2, 'moveend');
                }
            });
        },

        addGroupMarkerEvent: function(marker) {
            GEvent.addListener(marker, 'click', function() {
                var mLatLng = marker.getLatLng();
                $.view.map.map2.setCenter(mLatLng);
                $.view.map.map2.setZoom(($.view.map.sensitiveZoom + 1));

            });
        },

        createMarker: function(point, img, big, title) {
            var poi = new GIcon(),
				settings,
				marker,
				checkImg = function() {
				    var result = "restylane";
				    if (img == "macrolane") {
				        result = "macrolane";
				    }
				    return result;
				}

            if (big) {
                settings = {
                    img: '/UI/Images/' + checkImg() + '_big_poi.png',
                    size: [38, 65],
                    iconAnchor: [18, 64]
                }
            } else {
                settings = {
                    img: '/UI/Images/' + checkImg() + '/poi.png',
                    size: [26, 60],
                    iconAnchor: [6, 60]
                };
            }

            poi = new GIcon(G_DEFAULT_ICON);
            poi.image = settings.img;
            poi.shadow = "/UI/images/poi.shadow.png";
            poi.iconSize = new GSize(settings.size[0], settings.size[1]);
            poi.shadowSize = new GSize(59, 60);
            poi.iconAnchor = new GPoint(settings.iconAnchor[0], settings.iconAnchor[1]);
            poi.infoWindowAnchor = new GPoint(9, 2);

            if (big) {
                marker = new GMarker(point, { icon: poi });
            } else {
                marker = new GMarker(point, { icon: poi });
            }

            return marker;

        },

        basicMarker: function(m, big, title) {
            point = new GLatLng(m.lat, m.lng);
            marker = this.createMarker(point, this.whatId, big, title);
            this.bounds.extend(point);

            if (big) {
                this.addGroupMarkerEvent(marker);
            } else {
                this.addMarkerEvent(marker, m.url);
            }

            return marker;
        },

        makeJSON: function(data) {
            var json = {},
				i,
				l = data.length;

            for (i = 0; i < l; (i += 1)) {
                if (typeof data[i].Latitude !== 'undefined') {
                    json[i] = {
                        lng: parseFloat(data[i].Longitude),
                        lat: parseFloat(data[i].Latitude),
                        url: data[i].Url.replace(/&amp;/g, '&'),
                        id: parseInt(data[i].Id)
                    }
                }
            }
            return json;
        },

        setGroupNumbers: function(ary) {
            var i,
				l = ary.length,
				marker;

            for (i = 0; i < l; (i += 1)) {
                marker = ary[i];
            }
        },

        GetClosetClinic: function() {
            closestClinic = this.makeJSON(arguments[0]);
            var payload = { ListClinic: { containerPageID: parseInt($('#ctl00_FullRegion_CountrySelector').val(), 10), siteID: $('body').attr('id')} };
            model.doJsonPost('view.map.addMarkers', payload, '/ui/xml/listclinic.ashx?containerpageid=' + $('#ctl00_FullRegion_CountrySelector').val() + '&siteid=' + $('body').attr('id'));
        },

        addMarkers: function() {
            if (arguments[0][1] === false) {
                $('#noMatches').show();
                return;

                // do a new search on google
                //                var geocoder = new GClientGeocoder();
                //                //ddlcountry is set in findpractioner.aspx
                //                var countrytext = ddlcountry.options[ddlcountry.selectedIndex].text;

                //                // add selected country
                //                searchstring = searchstring + ", " + countrytext;
                //                geocoder.getLatLng(
                //                searchstring,
                //                function(point) {
                //                    if (!point) {
                //                        $('#noMatches').show();
                //                        return;
                //                    } else {
                //                        googlePoint = point; // save the point for later setCenter use
                //                        // Got a point, now need to fetch some markers to render
                //                        var payload = {};
                //                        model.doJsonPost('view.map.GetClosetClinic', payload, '/ui/xml/GetGoogleMarkers.ashx?containerpageid=' + $('#ctl00_FullRegion_CountrySelector').val() + '&siteid=' + $('body').attr('id') + '&text=' + searchstring);
                //                    }
                //                }
                //            );
            }
            else {
                $('#noMatches').hide();
            }

            this.coordinatesJSON = this.makeJSON(arguments[0]);

            var markerCollection = this.calcSensitiveMarkers(),
				singleArray = [],
				groupArray = [],
				groupIdArray = [],
				markerArray = [],
				index = 0,
				noMatch = jQuery.view.map.noMatch;

            this.bounds = new GLatLngBounds();
            this.mgr.clearMarkers();

            for (i in markerCollection) {
                m = markerCollection[i];
                /**index += m.length;**/
                if (typeof m !== 'undefined') {
                    if (m.length === 1) {
                        marker = this.basicMarker(m[0], false);
                        singleArray.push(marker);
                    } else if (m.length !== 0) {
                        for (i = 0, l = m.length; i < l; (i += 1)) {
                            ma = m[i];

                            marker = this.basicMarker(ma, false);
                            markerArray.push(marker);
                        }

                        marker = this.basicMarker(m[0], true, m.length);
                        marker.id = 'markerId_' + m[0].id;
                        groupIdArray.push('markerId_' + m[0].id);
                        groupArray.push(marker);
                    }
                }
            }

            this.mgr.addMarkers(singleArray, 1);
            this.mgr.addMarkers(markerArray, this.sensitiveZoom);
            this.mgr.addMarkers(groupArray, 1, (this.sensitiveZoom - 1));
            this.mgr.refresh();

            if (googlePoint) {
                if (closestClinic) {
                    var ne = new GLatLng(closestClinic[1].lat, closestClinic[1].lng);
                    var sw = new GLatLng(googlePoint.lat(), googlePoint.lng());

                    // Create a bounding box
                    this.bounds = new GLatLngBounds();
                    this.bounds.extend(ne);
                    this.bounds.extend(sw);

                    var m = this.map2;
                    //var z = this.map2.getZoom();
                    var z = this.map2.getBoundsZoomLevel(this.bounds)
                    var nePoint = m.getCurrentMapType().getProjection().fromLatLngToPixel(this.bounds.getNorthEast(), z);

                    var _y = parseInt(nePoint.y - 95);
                    var _x = parseInt(nePoint.x + 95);
                    var point = m.getCurrentMapType().getProjection().fromPixelToLatLng(new GPoint(_x, _y), z);

                    var swPoint = m.getCurrentMapType().getProjection().fromLatLngToPixel(this.bounds.getSouthWest(), z);

                    var _y2 = parseInt(swPoint.y + 95);
                    var _x2 = parseInt(swPoint.x - 95);
                    var point2 = m.getCurrentMapType().getProjection().fromPixelToLatLng(new GPoint(_x2, _y2), z);

                    this.bounds.extend(point);
                    this.bounds.extend(point2);
                    //add a marker for the search point
                    //                    var searchPointMarker = new GMarker(googlePoint);
                    //                    this.map2.clearOverlays();
                    //                    this.map2.addOverlay(searchPointMarker);
                    this.mgr.refresh();
                }
                closestClinic = null;
                googlePoint = null;
            }

            if (singleArray.length !== 0 || groupArray.length !== 0 || markerArray.length !== 0) {
                if (this.map2.getBoundsZoomLevel(this.bounds) > 12) {
                    this.map2.setZoom(12);
                } else {
                    this.map2.setZoom(this.map2.getBoundsZoomLevel(this.bounds));
                }
                this.map2.setCenter(this.bounds.getCenter());
            }

            if (singleArray.length === 1 && groupArray.length === 0 && markerArray.length === 0) {
                setTimeout(function() {
                    GEvent.trigger(singleArray[0], 'click');
                }, 500);
            }

            /** this.setGroupNumbers(groupArray); **/
        },

        searchMarkers: function(searchWord) {

            searchstring = searchWord;

            // do a new search on google
            var geocoder = new GClientGeocoder();

            //ddlcountry is set in findpractioner.aspx
            var countrytext = ddlcountry.options[ddlcountry.selectedIndex].text;
            // add selected country
            searchstring = searchstring + ", " + countrytext;

            if (countrytext == "United Kingdom") {
                geocoder.getLatLng(
                            searchstring,
                            function(point) {
                                if (!point) {
                                    $('#noMatches').show();
                                    return;
                                } else {
                                    googlePoint = point; // save the point for later setCenter use
                                    // Got a point, now need to fetch some markers to render
                                    var payload = {};
                                    model.doJsonPost('view.map.GetClosetClinic', payload, '/ui/xml/GetGoogleMarkers.ashx?containerpageid=' + $('#ctl00_FullRegion_CountrySelector').val() + '&siteid=' + $('body').attr('id') + '&text=' + searchstring);
                                }
                            }
                        );
            } else {
                var payload = {};
                model.doJsonPost('view.map.addMarkers', payload, '/ui/xml/searchclinic.ashx?containerpageid=' + $('#ctl00_FullRegion_CountrySelector').val() + '&siteid=' + $('body').attr('id') + '&text=' + searchWord);
            }
        },

        loadMarkers: function() {
            var payload = { ListClinic: { containerPageID: parseInt($('#ctl00_FullRegion_CountrySelector').val(), 10), siteID: $('body').attr('id')} };
            model.doJsonPost('view.map.addMarkers', payload, '/ui/xml/listclinic.ashx?containerpageid=' + $('#ctl00_FullRegion_CountrySelector').val() + '&siteid=' + $('body').attr('id'));
        },

        loadMap: function() {
            if (GBrowserIsCompatible() && $("#gMap").length) {
                var urlParam = '',
					whatId = $("body").attr("id"),
					mainCords = $("#firstView").val(),
					theCords = mainCords.split(","),
					setMapLat = theCords[0],
					setMapLong = theCords[1],
					topRight = new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(10, 8)),
					nextToRight = new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(85, 12)),
					mapControl = new GMapTypeControl(),
					marker,
					x,
					i,
					j,
					show,
					hide,
					markerArray = [],
					bounds = null;

                this.setMapZoom = theCords[2];

                this.map2 = new GMap2(document.getElementById('gMap'));

                GEvent.addListener(this.map2, "load", function() {
                    var query = jQuery("#ctl00_FullRegion_ucSearchText").val();
                    $.view.map.mgr = new MarkerManager($.view.map.map2);

                    if (query.length > 0) {
                        $.view.map.searchMarkers(query);
                    } else {
                        $.view.map.loadMarkers();
                    }
                });

                GEvent.addListener(this.map2, 'zoomend', function() {
                    $.view.map.map2.closeExtInfoWindow();
                });

                this.map2.setCenter(new GLatLng(setMapLat, setMapLong), parseInt(this.setMapZoom));
                this.map2.addControl(new GLargeMapControl3D(), topRight);
                this.map2.addControl(mapControl, nextToRight);

                this.map2.removeMapType(G_HYBRID_MAP);

                GEvent.addDomListener(this.map2, 'extinfowindowupdate', function() {

                    var windowContent = document.getElementById("custom_info_window_red_contents"),
						bookButtons = new Array(document.getElementById("bookingButton1"), document.getElementById("bookingButton2"), document.getElementById("bookingButton3")),
						tabs = new Array(document.getElementById("tab0"), document.getElementById("tab1"), document.getElementById("tab2"), document.getElementById("tab3")),
						cancelRequest = document.getElementById('cancelRequest');

                    if (tabs.length > 0) {
                        var tabContentsArray = new Array(tabs.length);
                        for (i = 0; i < tabs.length; i++) {
                            tabContentsArray[i] = document.getElementById("tab" + i + "_content");
                            if (i > 0) {
                                hide(tabContentsArray[i]);
                            }
                            tabs[i].setAttribute("name", i.toString());

                            GEvent.addDomListener(tabs[i], "click", function() {
                                var tabIndex = this.getAttribute("name");

                                for (tabContentIndex = 0; tabContentIndex < tabs.length; tabContentIndex++) {
                                    if (tabContentIndex == tabIndex) {
                                        $("#custom_info_window_red_contents div").removeClass("active");
                                        $(this).addClass("active");
                                        show(tabContentsArray[tabContentIndex]);

                                    } else {
                                        $("#custom_info_window_red_contents div").removeClass("active");
                                        $(this).addClass("active");
                                        hide(tabContentsArray[tabContentIndex]);

                                    }
                                }

                                $.view.map.map2.getExtInfoWindow().resize();
                            });
                        }

                        if (document.getElementById("bookingButton1") !== null && document.getElementById("bookingButton2") !== null && document.getElementById("bookingButton3") !== null) {
                            for (i = 0; i < bookButtons.length; i++) {
                                GEvent.addDomListener(bookButtons[i], "click", function() {

                                    for (i = 0; i < 3; i++) {
                                        hide(tabContentsArray[i]);
                                        $("#custom_info_window_red_contents div").removeClass("active");
                                    }

                                    //
                                    if ((jQuery.browser.msie && parseInt(jQuery.browser.version, 10) === 6)) {
                                        setTimeout(function() {

                                            $(".tab_contents input").css({
                                                display: 'inline'
                                            });

                                            $(".tab_contents input").css({
                                                display: 'inline-block'
                                            });

                                            $(".buttonWrap").css({
                                                height: '25px'
                                            });

                                            $("#cancelRequest").css({
                                                clear: 'both',
                                                display: 'inline-block',
                                                zoom: '1.0'
                                            });

                                        }, 400);
                                    }
                                    show(tabContentsArray[3]);

                                    $.view.map.map2.getExtInfoWindow().resize();
                                });
                            }
                        }

                        if (document.getElementById('cancelRequest') !== null) {

                            GEvent.addDomListener(cancelRequest, "click", function() {

                                for (i = 0; i < 3; i++) {
                                    hide(tabContentsArray[i]);
                                    $("#tab0").addClass("active");
                                }

                                hide(tabContentsArray[3]);
                                show(tabContentsArray[0]);
                                $('#miniForm input[type=text]').val('');

                                $.view.map.map2.getExtInfoWindow().resize();
                            });
                        }

                        $("#sendRequest").click(function() {
                            var referringPage = $('#mapPageId').val(),
                                lang = $('#lang').val(),
                                winUrl = jQuery.view.map.url.replace(/practitionerinfo/g, "practitionerbooking"),
                                newUrl = winUrl + '&mapPageId=' + referringPage + '&epslanguage=' + lang,
                                values = "";

                            $("#miniForm input").each(function() {
                                values += $(this).attr("id") + "=" + $(this).val() + "&";

                                if ($(this).val() === "" || null) {
                                    $(this).addClass("labelError");
                                }
                                else {
                                    $(this).removeClass("labelError");
                                }
                            });

                            if (!($(".labelError").length)) {
                                $.post(newUrl, values, function(data) {

                                    if (data.Response.Status == true) {
                                        $("#response").addClass("error").html(data.Response.Text)
                                        $.view.map.map2.getExtInfoWindow().resize();
                                    }
                                    else if (data.Response.Status == false) {
                                        $("#response").removeClass("error")
                                        $("#response").html(data.Response.Text)
                                        $("#miniForm input").val("");
                                        $.view.map.map2.getExtInfoWindow().resize();
                                    }
                                }, "json");
                            }
                        });

                    }
                });

                hide = function(element) {
                    element.style.display = "none";
                    element.style.position = "absolute";
                }

                show = function(element) {
                    element.style.display = "block";
                    element.style.position = "relative";
                }
            }
        },

        //We want to place the marker so the widget is displayed xxx pixels to the left
        calculateMarkerOffset: function(lat, lng, z, pixels_off) {
            var m = broken.visitSite.map.map;
            var pixels = m.getCurrentMapType().getProjection().fromLatLngToPixel(new GLatLng(lat, lng), z);

            var _y = pixels.y;
            var _x = parseInt(pixels.x - pixels_off);
            var point = m.getCurrentMapType().getProjection().fromPixelToLatLng(new GPoint(_x, _y), z);

            return point;
        },

        calcSensitiveMarkers: function() {
            var ary = [],
				i,
				j = 0,
				x,
				cord,
				jsonCord,
				added = false,
				collectionId = 0,
				collection = {},
				ashift,
				al;

            for (i in this.coordinatesJSON) {
                ary.push(this.coordinatesJSON[i]);
            }

            al = ary.length;

            while (al >= j) {
                cord = ary[0];
                added = false;
                collection[collectionId] = [];
                for (x = 1; x < ary.length; (x += 1)) {
                    jsonCord = ary[x];
                    if (typeof jsonCord === 'undefined' || jsonCord === null || cord === null) {
                    } else if (((cord.lng - jsonCord.lng <= this.sensitive && cord.lng - jsonCord.lng > 0) || (jsonCord.lng - cord.lng <= this.sensitive && jsonCord.lng - cord.lng > 0)) && ((cord.lat - jsonCord.lat <= this.sensitive && cord.lat - jsonCord.lat > 0) || (jsonCord.lat - cord.lat <= this.sensitive && jsonCord.lat - cord.lat > 0))) {
                        added = true;
                        collection[collectionId].push(jsonCord);
                        ary[x] = null;
                    }
                }

                ashift = ary.shift();

                if (ashift !== null && ashift !== '') {
                    if (typeof ashift !== 'undefined') {
                        collection[collectionId].push(ashift)
                        collectionId += 1;
                    }
                    j += 1;
                }
            }

            return collection;
        }
    }

    $.extend({ view: view });

    model = {
        handle: function() {
            /**if (arguments[0].d.ResponseStatus === 200) {
            $(window).trigger(this.callback, arguments[0].d.Response);
            } else {
            model.handleError(arguments[0].d.ResponseStatus + ' => ' + arguments[0].d.ResponseMessage);
            }**/
            if (arguments[0] === null) {
                $(window).trigger(this.callback, false);
            } else {
                $(window).trigger(this.callback, arguments[0]);
            }
        },

        doJsonPost: function(callbackEvent, payload, url) {
            $.ajax({
                url: url,
                type: 'post',
                dataType: 'json',
                contentType: 'application/json',
                data: $.toJSON({ complexCommands: $.toJSON(payload) }),
                callback: callbackEvent,
                success: model.handle
            });
        },

        handleError: function(err) {
            throw new Error(err);
        }
    };

    $(window).bindEvent({
        event: 'dom:ready',
        callback: [
        	{ n: '$.view.map', f: 'loadMap' },
			{ n: '$.view.map', f: 'addSearchEvents' }
    	]
    });

    $(window).bindEvent({
        event: 'view.map.addMarkers',
        callback: [
        	{ n: '$.view.map', f: 'addMarkers' }
    	]
    });

    $(window).bindEvent({
        event: 'view.map.GetClosetClinic',
        callback: [
        	{ n: '$.view.map', f: 'GetClosetClinic' }
    	]
    });

    $(document).ready(function() {
        $(window).trigger('dom:ready');
    });

})(jQuery);
