﻿(function($) {
    $(function(){
    
        // Namespace.
        var golfCourseFinder = {};
    
        /*
        * Maps related stuff.
        */

        golfCourseFinder.courseMap = null;
        golfCourseFinder.geocoder = null;
        golfCourseFinder.courses = [];
        golfCourseFinder.markers = [];
        golfCourseFinder.infoBubble = undefined;
        
        golfCourseFinder.initMap = function() {
            golfCourseFinder.geocoder = new google.maps.Geocoder();
            var myOptions = {
                zoom: 4,
                center: new google.maps.LatLng(54.6, -3.5),
                panControl: false,
                zoomControl: true,
                mapTypeControl: true,
                mapTypeControl: true,
                mapTypeControlOptions: {
                    style: google.maps.MapTypeControlStyle.DROPDOWN_MENU
                },
                scaleControl: false,
                streetViewControl: false,
                mapTypeId: google.maps.MapTypeId.ROADMAP,
                scrollwheel: false
            }
            golfCourseFinder.courseMap = new google.maps.Map(document.getElementById("golfCourseFinderMapCanvas"), myOptions); 
        };
        
		golfCourseFinder.populateCoursesArr = function() {
		    golfCourseFinder.courses = [];
	        $('tr.gcs', '.courseFinderTable').each(function(idx, item) { 
			    var course = [
				    $('.gc-name', this).text(),                                                                         // Course name
				    parseFloat($('.gc-name', this).attr('gc-lat')),                                                     // Lat
				    parseFloat($('.gc-name', this).attr('gc-lng')),                                                     // Lng
				    parseFloat($(this).attr('gc-id')),                                                                  // Result/Course number
				    golfCourseFinder.templateInfoBubble_v2($('.gc-name', this).text(), $('.gc-name', this).attr('href'), $('.c-adx', this).text(), $('.gc-name', this).attr('gc-lat'), $('.gc-name', this).attr('gc-lng')),  // Info bubble inner template
				    
				    // $('.gc-address', this).attr('c-adx')
				    // $('.c-adx', this).text(),
			    ]
			    golfCourseFinder.courses[idx] = course;  
	        });
		};
		
        golfCourseFinder.linkMapToResults = function() {
            // Populate global courses / markers.
            golfCourseFinder.populateCoursesArr();
            golfCourseFinder.setMarkers();
            
            // Add bounce effect to markers.
			$('table.courseFinderTable tr.gcs').bind('mouseenter mouseleave', function(event) {
                var markerIdx = $(this).index('tr.gcs');
                if (golfCourseFinder.markers[markerIdx].getAnimation() != null) {
                    golfCourseFinder.markers[markerIdx].setAnimation(null);
                } else {
                    golfCourseFinder.markers[markerIdx].setAnimation(google.maps.Animation.BOUNCE);
                }                
		    }); 
		    
        };		
		
		golfCourseFinder.setMarkers = function() {
            var bounds = new google.maps.LatLngBounds();
            
            for (var i = 0; i < golfCourseFinder.courses.length; i++) {
                var iconId = i + 1;                  
                var course = golfCourseFinder.courses[i];
                var myLatLng = new google.maps.LatLng(course[1], course[2]);
                var marker = golfCourseFinder.createMarker(myLatLng, course[0], course[3], course[4]);
                bounds.extend(myLatLng);
                golfCourseFinder.markers[i] = marker; // Populate global markers variable.
            }

            // For one course results, default bound causes big zoom.
            if (golfCourseFinder.courses.length == 1) {
                var course = golfCourseFinder.courses[0]
                var myLatLng = new google.maps.LatLng(course[1], course[2]);
                golfCourseFinder.courseMap.setZoom(10);
                golfCourseFinder.courseMap.setCenter(myLatLng);
            } else {
                golfCourseFinder.courseMap.fitBounds(bounds);
            };

        };	
                       
		golfCourseFinder.createMarker = function(myLatLng, title, iconId, infoBubbleText) {
		    // Marker settings.
		    // v1
			// var iconImageUrl = "http://gmaps-samples.googlecode.com/svn/trunk/markers/green/marker" + iconId + ".png";
			// var iconImageOverUrl = "http://gmaps-samples.googlecode.com/svn/trunk/markers/red/marker" + iconId + ".png";
			// v2
			
			var iconColour = "8ab470";
			var iconColourOver = "f5a430";
			
			var iconImageUrl = "http://chart.googleapis.com/chart?chst=d_map_spin&chld=0.5|0|" + iconColour + "|12|_|" + iconId + "";
			var iconImageOverUrl = "http://chart.googleapis.com/chart?chst=d_map_spin&chld=0.5|0|" + iconColourOver + "|12|_|" + iconId + "";
			
			if (iconId > 99) {
			    iconImageUrl = "http://chart.googleapis.com/chart?chst=d_map_spin&chld=0.5|0|" + iconColour + "|12|_|";
			    iconImageOverUrl = "http://chart.googleapis.com/chart?chst=d_map_spin&chld=0.5|0|" + iconColourOver + "|12|_|";
			};
			var iconShadowUrl = "http://www.google.com/mapfiles/shadow50.png";
			var iconSize = new google.maps.Size(20, 34);
			var iconPosition = new google.maps.Point(0, 0);
			var iconHotSpotOffset = new google.maps.Point(9, 34);
			var iconShadowSize = new google.maps.Size(37, 34);
			
			// Instantiate markers.
			var markerImage = new google.maps.MarkerImage(iconImageUrl, iconSize, iconPosition, iconHotSpotOffset);
			var markerImageOver = new google.maps.MarkerImage(iconImageOverUrl, iconSize, iconPosition, iconHotSpotOffset);
			var markerShadow = new google.maps.MarkerImage(iconShadowUrl, iconShadowSize, iconPosition, iconHotSpotOffset);
            var marker = new google.maps.Marker({
                position    : myLatLng, 
                map         : golfCourseFinder.courseMap, 
                title       : title,
                icon        : markerImage,
                shadow      : markerShadow
            });	
            
            // Mouseover / out events.
			google.maps.event.addListener(marker, "mouseover", function() {
				marker.setIcon(markerImageOver);
			});
			google.maps.event.addListener(marker, "mouseout", function() {
				marker.setIcon(markerImage);
			});
			
			// Show infoBubble on marker click.
			google.maps.event.addListener(marker, "click", function() {
				if (golfCourseFinder.infoBubble != undefined) {
					golfCourseFinder.infoBubble.close();
				}
				golfCourseFinder.infoBubble = golfCourseFinder.newInfoBubble(marker, infoBubbleText);
				golfCourseFinder.infoBubble.open();
			});
			return marker;
		}
		
		golfCourseFinder.newInfoBubble = function(marker, content){
		    var bubbleFill = '<div class="gc-info-bubble wi25 p1" style="height:45px"><div class="p2e">' + content + '</div></div>';
		    if (marker.title.length < 35) {
		        bubbleFill = '<div class="gc-info-bubble wi25 p1" style="height:30px"><div class="p2e">' + content + '</div></div>';
		    }
			myInfoBubble = new InfoBubble({
				map: golfCourseFinder.courseMap,
				content: bubbleFill,
				position: marker.getPosition(),
				shadowStyle: 1,
				padding: 0,
				backgroundColor: '#ffffff',
				borderRadius: 4,
				arrowSize: 10,
				borderWidth: 1,
				borderColor: '#aaaaaa',
				disableAutoPan: false,
				hideCloseButton: false,
				arrowPosition: 50,
				anchor: true,
				anchorPoint: {
				    y: -34
				},
				arrowStyle: 0
				});
			return myInfoBubble;
		};	
		
		golfCourseFinder.templateInfoBubble_v1 = function(courseName, courseLink, courseAddress){
			var drivingInstr = '<span class="small p0-5n">Driving directions: <a href="/a/" class="l" title="Google driving instruction ' + courseName + '">from</a>&nbsp;&nbsp;|&nbsp;&nbsp;<a href="/a/" class="l">to</a></span>'		
			return '<a href="' + courseLink + '" class="strong l">' + courseName + '&nbsp;Golf Course&nbsp;&raquo;</a><br><span class="small">' + courseAddress + '</span><br>' + drivingInstr;       
		};	
		
		golfCourseFinder.templateInfoBubble_v2 = function(courseName, courseLink, courseAddress, lat, lng){
			var saddrUrl = 'http://maps.google.co.uk/maps?saddr=' + courseName + ' Golf Course@(' + lat + ',' + lng + ')&daddr=&hl=en'
			var daddrUrl = 'http://maps.google.co.uk/maps?daddr=' + courseName + ' Golf Course@(' + lat + ',' + lng + ')&saddr=&hl=en'
			var drivingInstr = '<span class="small p0-5n">Directions: <a href="' + saddrUrl + '" class="l" target="_blank">From Here</a>&nbsp;&nbsp;|&nbsp;&nbsp;<a href="' + daddrUrl + '" class="l" target="_blank">To Here</a></span>'		
			return '<a href="' + courseLink + '" class="strong l">' + courseName + '</a><br>' + drivingInstr;       
		};	
		
        golfCourseFinder.displayContainer = $('.courseFinderTable');
					
		golfCourseFinder.init = function() {
            // Initialize the map.
            if ($(golfCourseFinder.displayContainer).length != 0) {
                golfCourseFinder.initMap();
                golfCourseFinder.linkMapToResults();
            };
            if ($('.hook_CourseSearchDrillDown').length != 0) {
                $('.hook_ExpandSwitch').click(function() {
                    if ($('.hook_CourseSearchDrillDown').is(':hidden')) {
                        $('.hook_CourseSearchDrillDown').slideDown();
                        $('.hook_ExpandSwitch').text('Show Less');
                        $('.hook_ExpandSwitch').removeClass('exps-down');
                        $('.hook_ExpandSwitch').addClass('exps-up');
                    } else {
                        $('.hook_CourseSearchDrillDown').slideUp();
                        $('.hook_ExpandSwitch').text('Show More');
                        $('.hook_ExpandSwitch').removeClass('exps-up');
                        $('.hook_ExpandSwitch').addClass('exps-down');                        
                    }
                });
            };
		};	

        // Initialize.       
        golfCourseFinder.init();
        
        $(".distance-sort-switch").gaflyoutmenu({
          Flyout: ".menu-sort-distance",
          FlyoutCloseButton: ".distance-sort-close",
          FlyoutPositionTop: 2,
          FlyoutPositionLeft: 0,  
          TriggerButton: ".distance-sort-switch",
          ShowHideSpeed: 120,
          GroupBy: "",
          linksWork: true          
        });   
        
        
        $(".txtCoursePicker").gaflyoutmenu({
          Flyout: ".menu-auto-helper-course",
          FlyoutCloseButton: ".menu-auto-helper-close",
          FlyoutPositionTop: 2,
          FlyoutPositionLeft: 0,  
          TriggerButton: ".txtCoursePicker",
          ShowHideSpeed: 120,
          GroupBy: "",
          linksWork: true          
        });   

  
	    
	    /*
	    * Autocomplete for courses and locations combined.
	    */
	    
	    $.widget("custom.courseslocationscomplete", $.ui.autocomplete, {
		    _renderMenu: function(ul, items) {
			    var self = this;
			    var currentCategory = "";
			    $.each(items, function(index, item) {
				    if (item.category != currentCategory) {
					    ul.append('<li class="ui-autocomplete-category wi29">' + convertToPlural(item.category) + '</li>');
					    currentCategory = item.category;
				    }
				    self._renderItem(ul, item);
			    });
		    }
	    });
	    
	    /*   
        $('input.txtCoursesLocationsPicker').keyup(function () {
            $('#varContainer').val('Null');
        });
        */
        
        $('input.txtCoursesLocationsPicker').keypress(function(e) {
            var keyCode;
            if (window.event) keyCode = window.event.keyCode;
            else if(e) keyCode = e.which;
            else return true;
            if (keyCode !== 13) {
                $('#varContainer').val('Null');
            }
        });
        	 
        $('input.txtCoursesLocationsPicker').click(function() { $(this).select(); } );
   
	   	
	    $('input.txtCoursesLocationsPicker').courseslocationscomplete({
		    minLength: 2,
		    select: function(event, data) {
			    if (data.item.category == 'Course') {
                    $('#varContainer').val('c|' + data.item.seed);	
			    } else {
                    $('#varContainer').val(data.item.seed);				        
			    }
		    },		    
            open: function(event, ui) {
                // console.log('test');
                $('.menu-auto-helper-course-location').hide();
            },
		    source: function(request, response) {
			    $.ajax({
                    type: 'POST',  
                    url: '/Resources/Golfalot2/Modules/GolfCourse/WS_CoursesLocations_Autocomplete.ashx',
				    dataType: "json",
				    data: {keyword: request.term},
                    success: function (data) {
                        response($.map(data, function (item) {
                            return {
                                label: item.ItemName, 
                                value: item.ItemName, 
                                country: item.Country,
                                term: request.term,
                                category: item.ItemType,
                                seed: item.Seed
                            }
                        }));
                    },
                    error: function (XMLHttpRequest, textStatus, errorThrown) {
                        // console.log(errorThrown);
                    }
			    });
		    }
	    })
	    .data("courseslocationscomplete")._renderItem = function(ul, item) {
		    return $("<li></li>")
			    .data("item.autocomplete", item)
			    .append("<a><div class=\"clearfix wi29\"><div class=\"wi24 ft\">" + highlightSearchTerm(item.label, item.term) + "</div><div class=\"wi05 ft right small faint\">" + renderCountryName(item.category, item.country) + "</div></div></a>")
			    .appendTo(ul);
	    };	
	    
        $(".txtCoursesLocationsPicker").gaflyoutmenu({
            Flyout: ".menu-auto-helper-course-location",
            FlyoutCloseButton: ".menu-auto-helper-close",
            FlyoutPositionTop: 2,
            FlyoutPositionLeft: 0,  
            TriggerButton: ".txtCoursesLocationsPicker",
            ShowHideSpeed: 120,
            GroupBy: "",
            linksWork: true          
        });  

	    function convertToPlural(singular) {
            var plural = '';
            switch (singular)
            {
                case 'City':
                    plural = 'Cities'; 
                    break
                case 'Course':
                    plural = 'Courses'; 
                    break
                case 'County':
                    plural = 'Counties'; 
                    break
                case 'Region':
                    plural = 'Regions'; 
                    break
                case 'Country':
                    plural = 'Countries'; 
                    break
            }
            return plural;
	    };
	    
	    function renderCountryName(category, country) {
            if (category == 'Country') {
                country = '&nbsp;';
            };
            return country;
	    };
	    
        highlightSearchTerm = function(data, search)
        {
             var regex = new RegExp('(' + search + ')', 'gi');
             return data.replace(regex, "<b>$1</b>");
        }
	    
	    

		/*
		* Recent searches reminder.
		*/
        $('div.cs-recent').click(function () {
            $('input.txtCoursesLocationsPicker').val($(this).text());
            $('#varContainer').val($(this).attr('seed'));
            $('.menu-auto-helper-course-location').hide();
        });	
	         	         
	    
		/*
		* Post code context menu handler.
		*/
        $('input.txtContextPostCode_hook').keyup(function () {
            var template = $('a.btnContextPostCode_hook').attr('tpl');
            var postCode = $(this).val().replace(/[^a-z0-9 ]/gi,'');
            postCode = $.trim(postCode).replace(/ +(?= )/g, '+')            
            $('a.btnContextPostCode_hook').attr('href', template.replace("PLACEHOLDER", postCode.toUpperCase()));
        });	 
                

		/*
		* Promos live tips.
		*/
        $('<div id="livetip"></div>').hide().appendTo('body');

        $(".button_2fore1, .button_2fore1Top, .button_openFairways, .button_openFairwaysTop, .button_ott, .button_ottTop").hover(
            function () {
            
                var adjHor = 0;
                var adjVer = 0;
            
                if ($(this).hasClass("button_2fore1")) {
                    var innerHtml =  '\
                    <div class="p2w p2s p1n"> \
                        <div class="clearfix"> \
                            <div class="p1s wi12 ft"><img style="padding:5px 0 0 0" width="65px" height="11px" src="/Resources/Golfalot2/Css/Images/logo-2-fore-1-golf-vourcher-v3.jpg"></div> \
                            <div class="wi16 ft right"><img class="ui-close ui-livetip-close" title="Close" alt="Close" src="/Resources/Golfalot2/Css/Images/blank.gif" width="11px" height="11px" /></div> \
                        </div> \
                        <div class="helper p2e">Use 2-FORE!-1 vouchers to get two rounds of golf for the price of one at over 1,000 UK golf courses.</div> \
                        <div class="p2n p2e"><a class="l" href="/Courses/2for1Discounts.aspx">Buy 2-FORE!-1 Vouchers</a></div> \
                    </div>'
                }
                
                if ($(this).hasClass("button_2fore1Top")) {
                    var innerHtml =  '\
                    <div class="p2w p1e p2s p1n"> \
                        <div class="clearfix"> \
                            <div class="p1s wi26 ft"><img style="padding:5px 0 0 0" width="65px" height="11px" src="/Resources/Golfalot2/Css/Images/logo-2-fore-1-golf-vourcher-v3.jpg"></div> \
                            <div class="wi02 ft right"><img class="ui-close ui-livetip-close" title="Close" alt="Close" src="/Resources/Golfalot2/Css/Images/blank.gif" width="11px" height="11px" /></div> \
                        </div> \
                        <div class="helper p0-5e">Use this option to search for golf courses that accept 2-FORE!-1 vouchers.</div> \
                        <div class="p1n helper p0-5e">With 2-FORE!-1 vouchers you can buy two rounds of golf for the price of one at over 1,000 UK golf courses.</div> \
                        <div class="p2n"><a class="l" href="/Courses/2for1Discounts.aspx">Buy 2-FORE!-1 Vouchers</a></div> \
                    </div>'
                    var adjHor = 31;
                    var adjVer = 0;
                }
            
                if ($(this).hasClass("button_openFairways")) {
                    var innerHtml =  '\
                    <div class="p2w p2s p1n"> \
                        <div class="clearfix"> \
                            <div class="p1s wi12 ft"><img style="padding:3px 0 0 0" width="104px" height="18px" src="/Resources/Golfalot2/Css/Images/logo-open-fairways.gif"></div> \
                            <div class="wi16 ft right"><img class="ui-close ui-livetip-close" title="Close" alt="Close" src="/Resources/Golfalot2/Css/Images/blank.gif" width="11px" height="11px" /></div> \
                        </div> \
                        <div class="helper p2e">Open Fairways card entitles both members and up to 7 guests to green fee offers such as \'2 for 1\' at 1600+ courses worldwide.</div> \
                        <div class="p2n"><a class="l" href="/Courses/2for1Discounts.aspx">Buy Open Fairways</a></div> \
                    </div>'
                }
            
                if ($(this).hasClass("button_openFairwaysTop")) {
                    var innerHtml =  '\
                    <div class="p2w p2s p1n"> \
                        <div class="clearfix"> \
                            <div class="p1s wi12 ft"><img style="padding:3px 0 0 0" width="104px" height="18px" src="/Resources/Golfalot2/Css/Images/logo-open-fairways.gif"></div> \
                            <div class="wi16 ft right"><img class="ui-close ui-livetip-close" title="Close" alt="Close" src="/Resources/Golfalot2/Css/Images/blank.gif" width="11px" height="11px" /></div> \
                        </div> \
                        <div class="helper p2e">Use this option to search for golf courses that accept Open Fairways membership.</div> \
                        <div class="p1n helper p2e">Open Fairways card entitles both members and up to 7 guests to green fee offers such as \'2 for 1\' at 1600+ courses worldwide.</div> \
                        <div class="p2n"><a class="l" href="/Courses/2for1Discounts.aspx">Buy Open Fairways</a></div> \
                    </div>'
                    var adjHor = 31;
                    var adjVer = 0;
                }
                
                if ($(this).hasClass("button_ott")) {
                    var innerHtml =  '\
                    <div class="p2w p2s p1n"> \
                        <div class="clearfix"> \
                            <div class="p1s wi12 ft"><img style="padding:3px 0 0 0" width="94px" height="14px" src="/Resources/Golfalot2/Css/Images/ott_large.gif"></div> \
                            <div class="wi16 ft right"><img class="ui-close ui-livetip-close" title="Close" alt="Close" src="/Resources/Golfalot2/Css/Images/blank.gif" width="11px" height="11px" /></div> \
                        </div> \
                        <div class="helper p2e">You can book tee times online at this course.  We search the major online tee time providers to find you the best online tee time deal.</div> \
                        <div class="p2n"><a class="l" href="/golf-courses/online-tee-times/">Book Online Tee Times</a></div> \
                    </div>'
                }
            
                if ($(this).hasClass("button_ottTop")) {
                    var innerHtml =  '\
                    <div class="p2w p2s p1n"> \
                        <div class="clearfix"> \
                            <div class="p1s wi12 ft"><img style="padding:3px 0 0 0" width="94px" height="14px" src="/Resources/Golfalot2/Css/Images/ott_large.gif"></div> \
                            <div class="wi16 ft right"><img class="ui-close ui-livetip-close" title="Close" alt="Close" src="/Resources/Golfalot2/Css/Images/blank.gif" width="11px" height="11px"  /></div> \
                        </div> \
                        <div class="helper p2e">Use this option to search for golf courses that allow booking tee times online.</div> \
                        <div class="helper p2e p1n">We search the major online tee time providers to find you the best online tee time deal.</div> \
                        <div class="p2n"><a class="l" href="/golf-courses/online-tee-times/">Book Online Tee Times</a></div> \
                    </div>'
                    var adjHor = 31;
                    var adjVer = 0;
                }
            
                var position = $(this).position();
                var anchorHeight = 0;
                var anchorWidth = $(this).width();
                $('#livetip').appendTo(this);
                $('#livetip').html('<div class="tip-content">' + innerHtml + '</div><div class="tip-footer"><img src="/Resources/Golfalot2/Css/Images/blank.gif" /></div>');
                var flyOutHeight = $('#livetip').innerHeight();
                var flyOutWidth = $('#livetip').width();
                $('#livetip').css({ "left": position.left + anchorWidth - flyOutWidth + adjHor + "px", "top": position.top + adjVer - flyOutHeight + "px" });;
                // $('#livetip').fadeIn(120);
                $('#livetip').show();
            }, 
            function () {
                hide_promoHelper();
            }
        );
	    
        $('.ui-livetip-close').live('click', function() {
            hide_promoHelper();
        });   
        
	    function hide_promoHelper() {
            $('#livetip').hide();
            return false;
	    };



		/*
		* Weather forecast search.
		*/
		
        // Weather textbox tip.
        /*
        if ($("#txt_WeatherSearch_hook").is('*')) {
            $.getScript('/Resources/Golfalot2/Modules/jQueryExample/jquery.example.min.js', function() {
                jQuery('#txt_WeatherSearch_hook').example('St. Andrews, Scotland', {
                    className: 'faint'
                });
            });  
        }
        */
        
        $("#txt_WeatherSearch_hook").click(function() { $(this).select(); } );

	    $('#btn_WeatherSearch_hook').click(function(){
            $('div.weatherForecastPlaceholder').fadeTo(200, 0.5, function() {
	            getWetherForecast();
            });
            return false;
	    });	    

        $('#txt_WeatherSearch_hook')
            .keypress(function(e) {
                var keyCode;
                if (window.event) keyCode = window.event.keyCode;
                else if(e) keyCode = e.which;
                else return true;
                if (keyCode == 13) {
                    $('div.weatherForecastPlaceholder').fadeTo(200, 0.5, function() {
	                    getWetherForecast();
                    });
                    return false;
                } else return true;
        });
	    
        function getWetherForecast() {
            $.ajax({
                type: 'POST',  
                url: '/Resources/Golfalot2/Modules/Weather/WS_WeatherForecast_Handler.ashx',
                dataType: "html",
                data: {locationText: $('#txt_WeatherSearch_hook').val()},
                success: function (resultData) {
                    if (resultData === 'noResponse') {
                        renderWeatherFetchError();
                    } else {
                        clearWeatherFetchError()
                        $('div.weatherForecastPlaceholder').html(resultData);
                    }
                    $('div.weatherForecastPlaceholder').fadeTo(20, 1);
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    // console.log('error ocurred');
                    $('div.weatherForecastPlaceholder').fadeTo(20, 1);
                    renderWeatherFetchError();
                }
            });	
            return false;
        };
        
        function renderWeatherFetchError() {
            $('.txt_WeatherFetchError').html('<div class=\"error\">This location could not be found.<br />Try different location.<div>');
            $("#txt_WeatherSearch_hook").addClass('ga_text_error');
        }
        
        function clearWeatherFetchError() {
            $('.txt_WeatherFetchError').html('');
            $("#txt_WeatherSearch_hook").removeClass('ga_text_error');
        }
        
    });             
})(jQuery);
