function reg() {
    if(Element.visible('map')) {
        Effect.BlindUp('map', { queue: 'front'});
        Effect.BlindDown('home', { queue: 'end'});
        Element.hide('homeContent');
        Element.show('reg');
        Element.hide('postcodeSearch');
        Element.hide('totalDistance');
        Element.hide('undo');
        Element.hide('clear');
        rememberRoute = true;
    }
    else {
        Element.hide('homeContent');
        Element.show('reg');
    }
}

function showLogin() {
    if(Element.visible('map')) {
        Effect.BlindUp('map', { queue: 'front'});
        Effect.BlindDown('home', { queue: 'end'});
        Element.show('homeContent');
        Element.hide('reg');
        Element.hide('postcodeSearch');
        Element.hide('totalDistance');
        Element.hide('undo');
        Element.hide('clear');
        rememberRoute = true;
    }
}

function regCancel() {
    if(rememberRoute == true)
        begin();
    else {
        Element.hide('reg');
        Element.show('homeContent');
    }
}

function startUsersearch() {
        window.setTimeout('checkUsername()', 100);
}

function checkUsername() {
    var username = $F('reguname');
    var myAjax = new Ajax.Request(ajaxUrl, {
        method: 'get',
        parameters: 'checkUsername=' + escape(username),
        onComplete: function(returnData) {
            if(returnData.responseText == 'fail') {
                usernameExist = true;
                Element.update('regUserError', '&nbsp;Sorry, that username already exists!&nbsp;');
            }
            else {
                usernameExist = false;
                Element.update('regUserError', '');
            }
        }
    });
}

function checkPasswordMatch() {
    var pass = $('regpwrd').value;
    var conf = $('regpwrdconf').value;
    if((pass && conf) && (pass != conf)) {
        passMatch = false;
        Element.update('regPassError', '&nbsp;Passwords do not match!&nbsp;');
    }
    else {
        passMatch = true;
        Element.update('regPassError', '');
    }
}

function regDetails() {
    var err = false;
    if(usernameExist || !passMatch)
        err = true;
    var username = $F('reguname');
    var password = $F('regpwrd');
    var passwordConfirm = $F('regpwrdconf');
    var userEmail = $F('regemail');
    if(!username) {
        Element.update('regUserError', '&nbsp;Please enter a username!&nbsp;');
        err = true;
    }
    if(!password || !passwordConfirm) {
        Element.update('regPassError', '&nbsp;Please enter and confirm password!&nbsp;');
        err = true;
    }
    if(err)
        return false;
    var myAjax = new Ajax.Request(ajaxUrl, {
        method: 'get',
        parameters: 'addUser=' + escape(username) + '&pass=' + escape(password) + '&userEmail=' + escape(userEmail),
        onComplete: function(returnData) {
            if(returnData.responseText == 'fail')
                alert('error adding');
            else {
                loadJs('js/user.php');
                urId = returnData.responseText;
                begin();
            }
        }
    });
}

function login() {
    var lgnuname = escape($F('lgnuname'));
    var lgnpwrd = escape($F('lgnpwrd'));
    var myAjax = new Ajax.Request(ajaxUrl, {
        method: 'get',
        parameters: 'lgn&lgnuname=' + lgnuname + '&lgnpwrd=' + lgnpwrd,
        onComplete: function(returnData) {
            if(returnData.responseText > 0) {
                loadJs('js/user.php');
                urId = returnData.responseText;
                begin();
            } else {
                showConfirm('Login error!',
                    '<strong>Either the username or password you entered was incorrect. Please try again.</strong>',
                    'Yellow',
                    'imageYellowCaution');
            }
        }
    });
    return false;
}

function loadDefault() {
    map.setCenter(new GLatLng(38.065392,-94.921875), 4, G_NORMAL_MAP);
}

function begin() {
    if(rememberRoute == false) {
        new Insertion.Top('map', '<img style="position: relative; left: 304px; top: 179px;" src="i/progressbar.gif" />');
        self.setTimeout('loadMap()', 3000);
    }
    Effect.BlindUp('home', { queue: 'front'});
    Effect.BlindDown('map', { queue: 'end'});
    Element.show('postcodeSearch');
    Element.show('totalDistance');
    rememberRoute = false;
    if(urId > 0) {
        self.setTimeout('populateUserRoutes()', 3000);
        self.setTimeout('populateUserLocations()', 3000);
        if(points.length > 1)
            Element.show('save');
    }
    if(points.length > 1) {
            Element.show('undo');
            Element.show('clear');
    }
}

/*
function doneDblClick() {
    doubleClick = true;
}
*/

//intialize the map
function loadMap() {
    map = new GMap2($('map'));
    map.addControl(new GLargeMapControl());
    map.addControl(new GMapTypeControl());
    map.disableDoubleClickZoom();
    //map.enableGoogleBar();
    map.enableScrollWheelZoom();
    loadUserRoute(getQuerystringValue('r'), true);
    
    GEvent.addListener(map, "dblclick", function() {
        doubleClick = true;
    });
    
    //add a listener for when the map finishes moving.
    GEvent.addListener(map, "moveend", function() {
        //if the user double clicked
        if (doubleClick == true && disableFeatures == false) {
            doubleClick = false;
            //put the co-ords where they clicked into the 'points' array
            points.push(new GLatLng(map.getCenter().lat(), map.getCenter().lng()));
            //call my function to draw the lines
            drawLine();
            //$('dist').innerHTML = getLastDistance();
            totalDistance += getLastDistance();
            $('dist').innerHTML = totalDistance.toFixed(2);
        }
        doubleClick = false;
    });
    if(urId == 0) {
        showConfirm('Welcome to Run Finder!',
            'Welcome to Run Finder. To plot your running route first search for an area using the postcode search above and then <strong>double click</strong> on a series of points to plot your route! Remember to register to access all the features.',
            'Green',
            'imageGreenWelcome');
    }
}

function getPostcode() {
    if(disableFeatures)
        return false;
    var pc = escape($F('postcode'));
    var myAjax = new Ajax.Request(ajaxUrl, {
        method: 'get',
        parameters: 'locatepostcode='+pc,
        onComplete: function(postcode) {
            loc = new String(postcode.responseText);
            if(loc == 'false') {
                showConfirm('Postcode not found!',
                    'Sorry, we could not find the postcode <strong>'+pc+'</strong>. Please make sure it is correct and try again.',
                    'Yellow',
                    'imageYellowCaution');
            } else {
                latlng = loc.split(',');
                var lat = parseFloat(latlng[0]);
                var lng = parseFloat(latlng[1]);
                if(map.getZoom() < 14) {
                    map.setZoom(14);
                }
                map.panTo(new GLatLng(lat, lng));
            }
        }
    });
    return false;
}

function loadUserRoute(routeId, hideLoading) {
    if(disableFeatures)
        return;
    var highlightedRoute = currentRouteId;
    currentRouteId = 0;
    if(routeId > 0) {
        totalDistance = 0;
        points.splice(0, points.length);
        map.clearOverlays();
        var myAjax = new Ajax.Request(ajaxUrl, { 
            method: 'get', 
            parameters: 'loadRoute&routeId=' + routeId, 
            onLoading: function() { 
                if(!hideLoading)
                    showMainLoader(); 
            },
            onLoaded: function() { 
                if(!hideLoading)
                    hideMainLoader(); 
            },
            onComplete: function(returnData) { 
                var route = returnData.responseText;
                if(route == 'fail') {
                    loadDefault();
                    showConfirm('Load error!',
                        '<strong>Sorry, the route cannot be loaded.</strong>',
                        'Yellow',
                        'imageYellowCaution');
                } else {
                    var routeElements = route.split(',');
                    var lat = parseFloat(routeElements[0]);
                    var lng = parseFloat(routeElements[1]);
                    var zoom = parseFloat(routeElements[2]);
                    
                    map.setCenter(new GLatLng(lat, lng), zoom);
                    
                    switch(routeElements[3]) {
                        case 'map':
                        map.setMapType(G_NORMAL_MAP)
                        break;
                        case 'sat':
                        map.setMapType(G_SATELLITE_MAP)
                        break;
                        case 'hyb':
                        map.setMapType(G_HYBRID_MAP)
                        break;
                        default : G_NORMAL_MAP;
                    }
                    var loadPoints = routeElements[4];
                    if(loadPoints.length > 0) {
                        var loadLatLng = loadPoints.split('p');
                        var latLng = '';
                        var n = loadLatLng.length; 
                        for (i = 0; i < n; i++) {
                            var latLng = loadLatLng[i].split('x');
                            points.push(new GLatLng(parseFloat(latLng[0]), parseFloat(latLng[1])));
                        }
                        drawLine();
                        if(highlightedRoute)
                            Element.setStyle('route'+highlightedRoute, {backgroundColor: '#666666'});
                        if(urId > 0)
                            Element.setStyle('route'+routeId, {backgroundColor: '#8d8d8d'});
                        $('dist').innerHTML = getTotalDistance();
                        currentRouteId = routeId;
                        if(!Element.visible('save') && urId > 0)
                            Element.show('save');
                        if(!Element.visible('add') && urId > 0)
                            Element.show('add');
                        
                    }
                    else
                        cleanPage();
                }
                //hideMainLoader();
            } 
        });
    }
    else
        loadDefault();
}

function showMainLoader() {
    var bodyWidth = (Element.getDimensions('theBody').width / 2) - 99; //calculate the screen width
    new Insertion.Top('theBody',
        '<div id="mainLoading" style="left: '+bodyWidth+'px;"><img src="i/loading.gif" alt="" /></div>');
}

function hideMainLoader() {
    Element.remove('mainLoading');
}

function drawLine() {
    //remove all the overlays
    map.clearOverlays();
    if (points.length > 0) {
        /*Element.show('totalDistance');
        Element.show('undo');
        Element.show('clear');
        if(!Element.visible('update') && currentRouteId > 0 && urId > 0)
            Element.show('update');
        else if(Element.visible('update') && currentRouteId == 0)
            Element.hide('update');
        */
        if(!Element.visible('totalDistance'))
            Element.show('totalDistance');
        if(!Element.visible('undo'))
            Element.show('undo');
        if(!Element.visible('clear'))
            Element.show('clear');
        if(!Element.visible('update') && currentRouteId > 0 && urId > 0)
            Element.show('update');
        else if(Element.visible('update') && currentRouteId == 0)
            Element.hide('update');
        
        if(points.length > 1 && urId > 0)
            Element.show('save');
        else
            Element.hide('save');
        //create a line, sending the array of points
        routeLine = map.addOverlay(new GPolyline(points, '#AE2C00', 3, 0.7));
        
        //calculate and display the total distance
        //$('dist').innerHTML = getTotalDistance();
        
         //add markers at every point
        var n = points.length;
        for(i = 1; i < n; i++) {
            var marker = new GMarker(points[i], Icon);
            map.addOverlay(marker);
        }
        
        /*
        for(i = 1; i < points.length; i++) {
            var marker = new GMarker(points[i], Icon);
            map.addOverlay(marker);
        }
        */

        //add a marker where the last point is
        var lastMarker = new GMarker(points[points.length-1], IconEnd);
        map.addOverlay(lastMarker);
    }
}

function removeLast() {
    if(points.length > 0 && disableFeatures == false) {
        if(points.length > 1) {
            totalDistance -= getLastDistance();
            if(totalDistance < 0)
                totalDistance = 0
            $('dist').innerHTML = totalDistance.toFixed(2);
        }
        //remove the last point
        points.pop();
        //redraw line
        drawLine(points);
        //pan and center to new last point
        if(points.length > 0)
            map.panTo(points[points.length-1]);
        else
            cleanPage();
    }
}

function removeAll() {
    if(disableFeatures)
        return;
    var msg = (currentRouteId) ? ' This will not effect your saved information.' : '';
    showConfirm('Confirm route clear',
        '<strong>Are you sure you wish to clear this route?'+msg+'</strong>',
        'Yellow',
        'imageYellowCaution',
        true,
        '<a href="#" onclick="clearRoute(); return false;"><img src="i/hover_button_yes_Yellow.gif" /></a> '
        );
}

function clearRoute() {
    totalDistance = 0;
    points.splice(0, points.length);
    map.clearOverlays();
    cleanPage();
    Element.remove('hoverBox');
    disableFeatures = false;
}

function cleanPage() {
    Element.hide('undo');
    Element.hide('clear');
    Element.hide('update');
    Element.hide('save');
    $('dist').innerHTML = '0.00';
    if(currentRouteId)
        Element.setStyle('route'+currentRouteId, {backgroundColor: '#666666'});
    currentRouteId = 0;
}

function getDistance(point01, point02) {
    var lng01 = point01.lng();
    var lat01 = point01.lat();
    var lng02 = point02.lng();
    var lat02 = point02.lat();
    var dist = Math.acos(
    Math.sin(lat01*(Math.PI/180))
        * Math.sin(lat02*(Math.PI/180))
        + Math.cos(lat01*(Math.PI/180))
        * Math.cos(lat02*(Math.PI/180))
        * Math.cos((lng01 - lng02)*(Math.PI/180)));
    dist = dist*(180/Math.PI);
    miles = dist * 69;
    return miles;
}

function getTotalDistance() {
    //var totalDistance = 0;
    totalDistance = 0;
    var n = points.length;
        for(i = 0; i < n-1; i++) {
        var distance = getDistance(points[i], points[i+1]);
        totalDistance += distance;
    }
    return totalDistance.toFixed(2);
}

function getLastDistance() {
    var n = points.length;
    return getDistance(points[n-2], points[n-1]);
}

function showConfirm(title, message, color, image, showClose, button) {
    disableFeatures = true;
    var button = button || '';
    var showClose = showClose || true;
    showClose = (showClose == true) ? '<a href="#" onclick="Element.remove(\'hoverBox\'); disableFeatures = false; return false;"><img src="i/hover_button_close_' + color + '.gif" /></a>' : '';
    //showClose = (showClose) ? '<input class="closeGreen" onclick="Element.remove(\'hoverBox\'); disableFeatures = false; return false;" type="submit" value="Close" />' : '';
    var randomPos = (Math.round(Math.random()*5)) * 10; //create a random number 0 - 50
    var randomDir = Math.round(Math.random()*1); //create a random number 0 or 1
    var bodyWidth = (Element.getDimensions('theBody').width / 2) - 210; //calculate the screen width
    var bodyHeight = 175;
    //randomly move the box
    if(randomDir == 1) {
        bodyWidth += randomPos;
        bodyHeight += randomPos;
    } else {
        bodyWidth -= randomPos;
        bodyHeight -= randomPos;
    }
    new Insertion.Top('theBody',
    '<div id="hoverBox" class="popUpBox popUpBox' + color + ' hover' + color + '" style="left: ' + bodyWidth + 'px; top: ' + bodyHeight + 'px;">'+
        '<div class="titlebar titleBar' + color + '">'+
            '<a href="#" onclick="Element.remove(\'hoverBox\'); disableFeatures = false; return false;"><img class="close" src="i/window_close.gif" width="14" height="14" alt="Close" /></a>'+
            title +
        '</div>'+
        '<div class="results">'+
            '<div class="content '+ image + '">' + message +
                '<div class="hoverButtons">' + button + showClose +
            '</div>'+
        '</div>'+
    '</div>');
    new Draggable('hoverBox');
}

//Get querystring value for a key
function getQuerystringValue(querystringKey) {
    var querystring = window.location.search.substring(1); //foo=bar&moo=cow
    var keyValue = querystring.split('&'); //[0] => 'foo=bar', [1] => 'moo=cow'
    for (var i = 0; i < keyValue.length; i++) {
        var key = keyValue[i].split('='); //[0] => 'foo', [1] => 'bar'
        if (key[0] == querystringKey) {
            return key[1]; // bar
        }
    }
  return 0;
}

function loadJs(name) {
    var objHead = document.getElementsByTagName('head');
    var objJS = objHead[0].appendChild(document.createElement('script'));
    objJS.setAttribute("type","text/javascript");
    objJS.setAttribute("src", name);
}