// Setup Variables and Defaults

var locObj = {},
    elevObj = {},
    elevation_marker,
    last_point,
    first_point,
    zoom_overlay_exists,
    routeID,
    num_tries = 0,


    map_display = null,
    map = null,
    watching_video = false;

function displayMap(routeID) {
	map_display = new MapDisplay(null, routeID, "map");
	map_display.displayMap();
	map = map_display.map;
}

function addStartElevation() {
    // Get First Item Elevation and Put on Page
    var first_xid = locObj[first_point].xid;
    start_elevation = elevObj[first_xid].elevation;
    $("#start_elevation").html(start_elevation);
    $("#start_elevation_climb").html(start_elevation);
}

function addElevationMarker(){
    var elevationPoint = new google.maps.LatLng(locObj[first_point].lat, locObj[first_point].lng);

    // Create default elevation marker
    // Layered below start icon, unseen until elevation mouseover

    elevation_marker = new google.maps.Marker({
        position: elevationPoint,
        map: map,
        icon: _MMF_GLOBAL.rd.elevation_icon,
        zIndex: 5,
        streetViewControl: true,
        title: 'Elevation'
    });
}

function addZoomOverlay(zoom_line){

    // When chart is zoomed add overlay of zoomed path
    // Slightly off from path due to point reduction on elevation
    zoom_overlay_exists = true;

    var polyOptions = {
        path: zoom_line,
        strokeColor: '#70dd74',
        strokeOpacity: 1.0,
        strokeWeight: 3
    };

    poly = new google.maps.Polyline(polyOptions);
    poly.setMap(map);
}

function removeZoomOverlay(){
    // When zoomed out this will remove the overlay
    zoom_overlay_exists = false;
    poly.setMap(null);
}

function amGetZoom(chart_id, from, to) {

    // Listener for zoom on chart

    if (zoom_overlay_exists) {
        // Zoom overlay needs gone before a new overlay is added
        removeZoomOverlay();
    }

    if (from == first_point && to == last_point) {
        // Don't zoom is full route don't show overlay of elevation
        removeZoomOverlay();
    } else {

        var x;
        x = parseFloat(x);
        from = parseFloat(from);
        to = parseFloat(to);
        zoom_path = [];

        for (x in locObj) {
            if (x >= from && x <= to) {
                zoom_path.push(new google.maps.LatLng(locObj[x].lat, locObj[x].lng));
            }
        }

        // Add the overlay to the map
        addZoomOverlay(zoom_path);
    }
}



// Used for Compare Routes Page
function displayMaps(routes) {

    // Get Location Center Point - Center on Route Start Points
    // Map recenters on kml file after load, but this keeps from crazy panning
    var myLatlng = new google.maps.LatLng(_MMF_GLOBAL.rd.route_center_lat, _MMF_GLOBAL.rd.route_center_lng);
	
    // Set Map Options and Defaults
    var myOptions = {
        zoom: 12,
        center: myLatlng,
        mapTypeControl: true,
        streetViewControl: true,
        scrollwheel: false,
        mapTypeControlOptions: {
          style: google.maps.MapTypeControlStyle.DROPDOWN_MENU
        },
        scaleControl: true,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };

    // Build the Map
    map = new google.maps.Map(document.getElementById("map"), myOptions);
        
    // Set Defaults
    var marker_interval = 8046;
	var colors = ['ff00ff00', 'ffff0000', 'ff0000ff'];
	var count = routes.length;
	var bounds = null;
	var kmls = [];
	
	var interval = setInterval(function() {
		if (count === 0) {
			clearInterval(interval);			
			for (var i = 0; i < kmls.length; i++) {
				var kml = kmls[i];
				if (bounds === null) {
					bounds = kml.getDefaultViewport();
				} else {
					bounds.union(kml.getDefaultViewport());
				}
			}
			map.fitBounds(bounds);			
		}
	}, 100);

        // Overlay KML File for Route
	for (var i = 0; i < routes.length; i++) {
		var route_id = routes[i];
		var kml_url = _MMF_GLOBAL.api.server + _MMF_GLOBAL.api.url4 + "routes/get_route_kml?consumer_key=" + _MMF_GLOBAL.api.key + "&route_id=" + route_id + "&display_distance_marker_flag=0&display_marker_interval=" + marker_interval + "&line_color=" + (colors[i] ? colors[i] : '7f0000ff');
		routeLayer = new google.maps.KmlLayer(kml_url, {
			map: map,
			suppressInfoWindows: true,
			preserveViewport: false
		});
		
		kmls.push(routeLayer);
		
		google.maps.event.addListener(routeLayer, 'metadata_changed', function() {
                count--;
		});				
	}
		
// End of Map Display
}

// Similar Routes
function get_similar_routes() {

    var route_list,
        html_output = "",
        route_list,
        unit = _MMF_GLOBAL.units.distance,
        route_distance = _MMF_GLOBAL.rd.route_distance,
        min_distance = parseFloat(route_distance - (0.2 * route_distance)),
        max_distance = parseFloat(route_distance + (0.2 * route_distance)),
        route_name = "",
        route_type;

    if (_MMF_GLOBAL.rd.type !== 'None') {
        route_type = _MMF_GLOBAL.rd.type;
    }
    var distance_unit = 'mile';
    if (unit === 'km') {
        distance_unit = 'kilometer';
    }

    var jsonSimilarSearch = {
        "min_distance": min_distance,
        "max_distance": max_distance,
        "route_type": "",
        "sort_by": "view_count desc",
        "center_latitude": _MMF_GLOBAL.rd.route_center_lat,
        "center_longitude": _MMF_GLOBAL.rd.route_center_lng,
        "radius": "30",
        "result_limit": 4,
        "result_offset": 0,
        "consumer_key": _MMF_GLOBAL.api.key
    };

    if (route_type !== '') {
        jsonSimilarSearch.route_type = route_type;
    }
    
    // Get the html template for the route widget list
    $.get("/routes/widget_template/", function(data){
        _ROUTE_WIDGET_TEMPLATE = data;

        // Try and get some routes that are similar
        $.ajax({
            type: 'GET',
            // Add _MMF_GLOBAL.api.server in for local testing
            url: _MMF_GLOBAL.api.url4 + "routes/search_routes",
            data: apiParameters(jsonSimilarSearch),
            success: function(data) {
                route_list = data;

                // Loop through results and put on page
                if (route_list.result.output.count > 0) {

                    var route_output = "";

                    for ( var i in route_list.result.output.routes ) {
                        var route = route_list.result.output.routes[i];
                        var r = _ROUTE_WIDGET_TEMPLATE;

                        if (route.route_name !== '') {
                            route_name = route.route_name;
                            route_name = route_name.substring(0,36);
                        } else {
                            route_name = "No Route Name Available";
                        }
                        var route_thumb = _MMF_GLOBAL.api.url3 + "routes/view_route_image.php?line_color=0x0000000&line_width=160&route_id=" +  route.route_id + "&thumbnail_flag=0&width=165&distance_markers_flag=0&signed_token=1283369728%2A5d005a9f75291f27696b2de4793d912d8befc5be&height=90&width=90&consumer_key=" + _MMF_GLOBAL.api.key + "&dpi=18";
                        var r_distance = route.total_distance;
                        // If unit is km then conver to km
                        if (unit === 'km') {
                            r_distance = r_distance * 1.609344;
                        }
                        r_distance = Math.round(r_distance*100)/100;
                        r = r.replace(/%ROUTE_NAME%/gi, route_name);
                        r = r.replace(/%ROUTE_DISTANCE%/gi, r_distance);
                        r = r.replace(/%DISTANCE_UNIT%/gi, distance_unit);
                        r = r.replace(/%ROUTE_IMAGE%/gi, route_thumb);
                        r = r.replace(/%ROUTE_CITY%/gi, route.city);
                        r = r.replace(/%ROUTE_STATE%/gi, route.state);
                        r = r.replace(/%ROUTE_URL%/gi, '/routes/view/' + route.route_id);
                        route_output = route_output + r;
                    }
                    html_output = html_output + route_output;
                } else {
                    html_output = '<div style="text-align:center; margin-top:8px;">Could not find any similar routes.</div>';
                }

                $("#similar_route_list").html(html_output);

            },
            error: function(XMLHttpRequest, textStatus, errorThrown) {
              log(_MMF_GLOBAL.text.search_error_api_fail = " - error retrieving similar routes");
            },
            dataType: "json"
        });
    });

    
}

function pollElevation(route_id, elevation_exists, element, elevation_url) {
    
    if (elevation_url === undefined) {
       elevation_url = 'route_elevation_html';
    }
	
    if (elevation_exists === true) {
        load_elevation_data(route_id, element, elevation_url);
        return;
    }

    var d = Date();
    var url = _MMF_GLOBAL.page_urls.route_elevation_polling + '?_=' + d;

    num_tries = num_tries + 1;

    if (num_tries > 7) {
		
        element.html(_MMF_GLOBAL.text.loading_error_msg);

    } else {

        $.ajax({
            url: url,
            dataType: 'json',
            success: function(data) {
                if (data.status == 'processing') {
                    $("#elevation_status").prepend(".");
                    num_tries = num_tries + 1;
                    setTimeout(function() { pollElevation(route_id, elevation_exists, element, elevation_url); }, 7000); // wait 15 seconds than call ajax request again
                } else {
                    if (data.status == 'error') {
                        element.html(_MMF_GLOBAL.text.loading_error_msg + ' (timeout).');
                    } else {
                        // We have a go on elevation launch
                        // Get the elevation from the elevation url
                        load_elevation_data(route_id, element, elevation_url);
                    }
                }

            },
            error: function(data) {
                element.html(_MMF_GLOBAL.text.loading_error_msg);
            }
        });
    }

}

function load_elevation_data(route_id, element, key) {

    var url = _MMF_GLOBAL.page_urls[key];

    $.ajax({
        url: url,
        success: function(data) {
            element.replaceWith(data);
			if (key == 'route_elevation_html') {
				parse_elevation();
			}
                         // Get Start Elevation from First Tab
                        $("#start_elevation_climb").html($("#start_elevation").html());

        },
        error: function() {
            element.html(_MMF_GLOBAL.text.loading_error_msg + '(load_error).');
        }
    });


}


function parse_elevation() {
    // Chart Functions
    var graph_url = _MMF_GLOBAL.page_urls.route_elevation;

    // Get Chart XML File and Parse it
    $.ajax({type:"GET", url: graph_url,
            success: function(data){
				if ($(data).find("series > value").length === 0) {
					$("#flashcontent, .elevation_details").hide();
				}
				else {
					var first_point_added = false;
					$(data).find("series > value").each(function(){
						var jEle = $(this);
						if (first_point_added === false) {
							first_point = jEle.text();
							first_point_added = true;
						}
						
						locObj[jEle.text()] = {
							lat: jEle.attr('lat'),
							lng: jEle.attr('lng'),
							xid: jEle.attr('xid')
						};
						last_point = jEle.text();
					});
					
					// Get elevation points
					$(data).find("graph > value").each(function(){
						var jEle = $(this);
						elevObj[jEle.attr('xid')] = {
							elevation: jEle.text()
						};
					});
					
					addStartElevation();
					addElevationMarker();
				}
            }
    });
}



function addStartElevation() {
    // Get First Item Elevation and Put on Page
    var first_xid = locObj[first_point].xid;
    start_elevation = elevObj[first_xid].elevation;
    $("#start_elevation").html(start_elevation);
}

function addElevationMarker(){
    var elevationPoint = new google.maps.LatLng(locObj[first_point].lat, locObj[first_point].lng);

    // Create default elevation marker
    // Layered below start icon, unseen until elevation mouseover

    elevation_marker = new google.maps.Marker({
        position: elevationPoint,
        map: map,
        icon: _MMF_GLOBAL.rd.elevation_icon,
        zIndex: 5,
        streetViewControl: true,
        title: 'Elevation'
    });
}

function watchRouteVideo(route){

    if (watching_video !== true) {
        watching_video = true;
        
        $('.ad_bg_300x250').hide();
        $('#header_banner_ad').hide();
        var dialog_loaded = false;

        // Google Earth Video player
        var $dialog = $('<div id="watch_route_video_dialog"></div>')
                .dialog({
                    autoOpen: false,
                    modal: true,
                    height:600,
                    width:640,
                    zIndex: 9999,
                    title: 'Course Fly-By Video',
                    close: function(){
                        $(this).remove();
                        watching_video = false;
                        $('.ad_bg_300x250').show();
                        $('#header_banner_ad').show();
                    }
                });
                $dialog.load("/routes/video/"+route, function(){
                    $dialog.dialog('open');
                });
    }

}

function load_video(url) {
    $("#player_api").hide();
    $("#advert_video").hide();
    $("#video_iframe").show();
    $("#video_iframe").attr("src", url);
}

function amRolledOverSeries(chart_id, series) {
    // Show marker on current mouseover of elevation
    var first_xid = locObj[series].xid;
    var cur_elevation = elevObj[first_xid].elevation;


    var locpoint = new google.maps.LatLng(locObj[series].lat, locObj[series].lng);
    elevation_marker.setPosition(locpoint);
    elevation_marker.setTitle('Elevation ' + cur_elevation + ' ft at ' + series + ' mi' );
}

function addZoomOverlay(zoom_line){

    // When chart is zoomed add overlay of zoomed path
    // Slightly off from path due to point reduction on elevation
    zoom_overlay_exists = true;

    var polyOptions = {
        path: zoom_line,
        strokeColor: '#70dd74',
        strokeOpacity: 1.0,
        strokeWeight: 3
    };

    poly = new google.maps.Polyline(polyOptions);
    poly.setMap(map);
}

function removeZoomOverlay(){
    // When zoomed out this will remove the overlay
    zoom_overlay_exists = false;
    poly.setMap(null);
}

function amGetZoom(chart_id, from, to) {

    // Listener for zoom on chart

    if (zoom_overlay_exists) {
        // Zoom overlay needs gone before a new overlay is added
        removeZoomOverlay();
    }

    if (from == first_point && to == last_point) {
        // Don't zoom is full route don't show overlay of elevation
        removeZoomOverlay();
    } else {

        var x;
        x = parseFloat(x);
        from = parseFloat(from);
        to = parseFloat(to);
        zoom_path = [];

        for (x in locObj) {
            if (x >= from && x <= to) {
                zoom_path.push(new google.maps.LatLng(locObj[x].lat, locObj[x].lng));
            }
        }

        // Add the overlay to the map
        addZoomOverlay(zoom_path);
    }
}

function send_to_phone() {
    var $container = $('#send_to_phone_dialog'),
        toggle_selector = '.content_toggle';
    
    $container.dialog({
        title: 'Send this route to my smartphone',
        modal: true,
        zIndex: 9999,
        height: 300,
        width: 550,
        close: function(event, ui) {
            toggle_content(true);
        }
    });

    $('#send_to_phone_btn').bind('click', function (e) {
        e.preventDefault();

        $.ajax({
                type: 'POST',
                url: _MMF_GLOBAL.page_urls.send_route_to_phone, 
                success: function (data) {
                    if (data.status === 1) {
                        toggle_content();
                        $('#send_to_phone_btn').text('Send It').attr('disabled', false);
                    } else {
                        $('#send_to_phone_btn').text('Try Again').attr('disabled', false);
                    }
                },
                error: function () {
                    $('#send_to_phone_btn').text('Try Again').attr('disabled', false);
                }
        });
        $('#send_to_phone_btn').text('Sending...').attr('disabled', true);
    });

    $('#send_to_phone_cancel, #send_to_phone_close').bind('click', function (e) {

        e.preventDefault();

        $('#send_to_phone_dialog').dialog('close');
    });

    function toggle_content(reset) {
        var show_index = reset ? 0 : 1;
        $container
            .find(toggle_selector)
            .hide()
                .eq(show_index)
                .show();
    }

}

