﻿var xmlHttpRefreshPushPins;
var xmlHttpCreatingNewPin;
var xmlHttpSendMail;
var xmlHttpGetPinInformation;
var xmlHttpGetDrivingDirection;
var xmlHttpSetCenterAtOnePinStartUP;

var map = null;
var xmlHttpPins;
var xmlPinsXml;
var xmlDoc;
var topleft;
var bottomright;
var XMaxValue;
var XMinValue;
var YMaxValue;
var YMinValue;
var RowCount = 0;
var ShowingAll = false;
var viewPerson = true;
var viewClub = false;
var viewShop = false;
var showallurl;
var NewXYPos;
var NewName;
var NewDescription;
var NewShop;
var NewClub;
var NewEmail;
var Password;
var gUserID;
var searchResult = null;
var SearchStarteDestinations = 0;
var SearchStarteDestinationsXY = null;
var directionsString = null;
var myGMarkerArray = new Array(500);
var myGMarkerArrayI = 0;
var mapdirections = null;
var lastPopUpTime = null;

function RefreshPushPins() {
    if (lastPopUpTime == null || calculateTime(new Date()) > calculateTime(lastPopUpTime) + 700) {
        xmlHttpRefreshPushPins = null;
        GetMapView();
        xmlHttpRefreshPushPins = GetXmlHttpObject();
        if (xmlHttpRefreshPushPins == null) {
            alert("Browser does not support HTTP Request");
            return;
        }
        var url = "getuser.php";
        url = url + "?XMinValue=" + XMinValue + "&XMaxValue=" + XMaxValue;
        url = url + "&YMinValue=" + YMinValue + "&YMaxValue=" + YMaxValue;
        url = url + "&PersonOnly=" + viewPerson + "&ClubOnly=" + viewClub + "&ShopOnly=" + viewShop;
        xmlHttpRefreshPushPins.onreadystatechange = loadingFullPins;
        xmlHttpRefreshPushPins.open("GET", url, true);
        xmlHttpRefreshPushPins.send(null);
    }
}

function calculateTime(timetoconvert) {
    var answer = 0;
    answer = timetoconvert.getHours() * 3600000;
    answer += timetoconvert.getMinutes() * 60000;
    answer += timetoconvert.getSeconds() * 1000;
    answer += timetoconvert.getMilliseconds();
    return answer;
}



function loadingFullPins() {
    statusTextChange("Loading.......");
    xmlDoc = null;

    for (var i = 0; myGMarkerArrayI > i; i++) {
        map.removeOverlay(myGMarkerArray[i]);
    }

    myGMarkerArrayI = 0;
    myGMarkerArray = null;
    myGMarkerArray = new Array(500);


    var allLoaded = false;
    if (xmlHttpRefreshPushPins.readyState == 4 || xmlHttpRefreshPushPins.readyState == "complete") {
        xmlDoc = xmlHttpRefreshPushPins.responseXML;
        //id, xpos, ypos, title, description, club, email, shop
        if (xmlDoc != null) {
            if (xmlDoc.getElementsByTagName("RowCount").length > 0) {
                RowCount = xmlDoc.getElementsByTagName("RowCount")[0].childNodes[0].nodeValue;
                ShowingAll = xmlDoc.getElementsByTagName("viewAll")[0].childNodes[0].nodeValue;
                //alert("Vis alle " + xmlDoc.getElementsByTagName('viewAll')[0].childNodes[0].nodeValue);
                //alert(RowCount);
                var dataArray = xmlDoc.getElementsByTagName('p');
                var dataArrayLen = dataArray.length;
                for (var i = 0; i < dataArrayLen; i++) {
                    var jID;
                    var jXpos;
                    var jYpos;
                    var jTitle;
                    var jDescription;
                    var jClub;
                    var jEmail;
                    var jShop;

                    if (dataArray[i].getElementsByTagName("id")[0].childNodes[0] != null) {
                        jID = dataArray[i].getElementsByTagName("id")[0].childNodes[0].nodeValue;
                    }
                    if (dataArray[i].getElementsByTagName("x")[0].childNodes[0] != null) {
                        jXpos = dataArray[i].getElementsByTagName("x")[0].childNodes[0].nodeValue;
                    }
                    if (dataArray[i].getElementsByTagName("y")[0].childNodes[0] != null) {
                        jYpos = dataArray[i].getElementsByTagName("y")[0].childNodes[0].nodeValue;
                    }
                    if (dataArray[i].getElementsByTagName("t")[0].childNodes[0] != null) {
                        jTitle = dataArray[i].getElementsByTagName("t")[0].childNodes[0].nodeValue;
                    }
                    if (dataArray[i].getElementsByTagName("d")[0].childNodes[0] != null) {
                        jDescription = dataArray[i].getElementsByTagName("d")[0].childNodes[0].nodeValue;
                    }
                    if (dataArray[i].getElementsByTagName("c")[0].childNodes[0] != null) {
                        jClub = dataArray[i].getElementsByTagName("c")[0].childNodes[0].nodeValue;
                    }
                    if (dataArray[i].getElementsByTagName("e")[0].childNodes[0] != null) {
                        jEmail = dataArray[i].getElementsByTagName("e")[0].childNodes[0].nodeValue;
                    }
                    if (dataArray[i].getElementsByTagName("s")[0].childNodes[0] != null) {
                        jShop = dataArray[i].getElementsByTagName("s")[0].childNodes[0].nodeValue;
                    }
                    loadPinData(jID, jXpos, jYpos, jTitle, jDescription, jClub, jEmail, jShop);
                    if (i == dataArrayLen - 1) {
                        allLoaded = true;
                    }
                } // for end
            }  // if end
        } // if end
        if (allLoaded || RowCount == 0) {
            statusTextChange("");
            showRowCount();
        }
        loadSearchResultPins();


    } //if end

}


function CreatingNewPin() {
    xmlHttpCreatingNewPin = null;
    xmlHttpCreatingNewPin = GetXmlHttpObject();
    if (xmlHttpCreatingNewPin == null) {
        alert("Browser does not support HTTP Request");
        return;
    }
    HandledNewPushPinVars();
    if (NewName == "") {
        alert("You have to give the pushpin a name");
    } else {
        //do an update
        if (gUserID > 0) {
            var url = "createuser.php";
            url = url + "?UserID=" + encodeURI(gUserID);
            url = url + "&NewXYPos=" + encodeURI(NewXYPos);
            url = url + "&NewName=" + encodeURI(NewName);
            url = url + "&NewDescription=" + encodeURI(NewDescription);
            url = url + "&NewShop=" + encodeURI(NewShop);
            url = url + "&NewClub=" + encodeURI(NewClub);
            url = url + "&NewEmail=" + encodeURI(NewEmail);
            url = url + "&Password=" + encodeURI(Password);
        }
        else {
            // do insert
            var url = "createuser.php";
            url = url + "?NewXYPos=" + encodeURI(NewXYPos);
            url = url + "&NewName=" + encodeURI(NewName);
            url = url + "&NewDescription=" + encodeURI(NewDescription);
            url = url + "&NewShop=" + encodeURI(NewShop);
            url = url + "&NewClub=" + encodeURI(NewClub);
            url = url + "&NewEmail=" + encodeURI(NewEmail);
            url = url + "&Password=" + encodeURI(Password);
        }
        xmlHttpCreatingNewPin.onreadystatechange = SetCenterAtNewPin;
        xmlHttpCreatingNewPin.open("GET", url, true);
        xmlHttpCreatingNewPin.send(null);

        //Handel that the user can se the new club, if he has not cheked on clubs
        if (NewShop == false && NewClub == false) {
            if (!viewPerson) {
                handleViewPerson();
            }
        }
        if (NewClub == true) {
            if (!viewClub) {
                handleViewClub();
            }
        }
        if (NewShop == true) {
            if (!viewShop) {
                handleViewShop();
            }
        }
        RefreshPushPins();
    }
}

function SetCenterAtOnePinStartUP(parPinID) {
    xmlHttpSetCenterAtOnePinStartUP = null;
    xmlHttpSetCenterAtOnePinStartUP = GetXmlHttpObject();
    if (xmlHttpSetCenterAtOnePinStartUP == null) {
        alert("Browser does not support HTTP Request");
        return;
    }
    var url = "setcenterpin.php";
    url = url + "?GetUserID=" + parPinID;
    xmlHttpSetCenterAtOnePinStartUP.onreadystatechange = SetCenterAtOnePin;
    xmlHttpSetCenterAtOnePinStartUP.open("GET", url, true);
    xmlHttpSetCenterAtOnePinStartUP.send(null);
}

function SetCenterAtOnePin() {
    if (xmlHttpSetCenterAtOnePinStartUP.readyState == 4 || xmlHttpSetCenterAtOnePinStartUP.readyState == "complete") {
        xmlDoc = null;
        var jXpos;
        var jYpos;
        var jclub;
        var jshop;
        if (xmlHttpSetCenterAtOnePinStartUP.responseXML != null) {
            xmlDoc = xmlHttpSetCenterAtOnePinStartUP.responseXML;
            //id, xpos, ypos, title, description, club, email, shop
            if (xmlDoc != null) {
                var dataArray = xmlDoc.getElementsByTagName('p');
                var dataArrayLen = dataArray.length;
                for (var x = 0; x < dataArrayLen; x++) {


                    if (dataArray[x].getElementsByTagName("x")[0].childNodes[0] != null) {
                        jXpos = dataArray[x].getElementsByTagName("x")[0].childNodes[0].nodeValue;
                    }
                    if (dataArray[x].getElementsByTagName("y")[0].childNodes[0] != null) {
                        jYpos = dataArray[x].getElementsByTagName("y")[0].childNodes[0].nodeValue;
                    }
                    if (dataArray[x].getElementsByTagName("c")[0].childNodes[0] != null) {
                        jclub = dataArray[x].getElementsByTagName("c")[0].childNodes[0].nodeValue;
                        if (jclub == 'ON' || jclub == 'on' || jclub == 'On') {
                            jclub = true;
                        }
                        else {
                            jclub = false;
                        }

                    }
                    if (dataArray[x].getElementsByTagName("s")[0].childNodes[0] != null) {
                        jshop = dataArray[x].getElementsByTagName("s")[0].childNodes[0].nodeValue;
                        if (jshop == 'ON' || jshop == 'on' || jshop == 'On') {
                            jshop = true;
                        }
                        else {
                            jshop = false;
                        }
                    }
                }
            }
            if (jXpos != "" && jYpos != "" && jXpos != null && jYpos != null) {
                

                //Handel that the user can se the new club, if he has not cheked on clubs
                if (jshop == false && jclub == false) {
                    if (!viewPerson) {
                        handleViewPerson();
                    }
                }
                if (jclub == true) {
                    if (!viewClub) {
                        handleViewClub();
                    }
                }
                if (jshop == true) {
                    if (!viewShop) {
                        handleViewShop();
                    }
                }
            }
            setCenter(jXpos, jYpos, 13);// RefreshPushPins();
        }

    }
}

function FindCenterAtOnePinStartUP(parPinID) {
    xmlHttpSetCenterAtOnePinStartUP = null;
    xmlHttpSetCenterAtOnePinStartUP = GetXmlHttpObject();
    if (xmlHttpSetCenterAtOnePinStartUP == null) {
        alert("Browser does not support HTTP Request");
        return;
    }
    var url = "setcenterpin.php";
    url = url + "?find=" + parPinID;
    xmlHttpSetCenterAtOnePinStartUP.onreadystatechange = SetCenterAtOnePin;
    xmlHttpSetCenterAtOnePinStartUP.open("GET", url, true);
    xmlHttpSetCenterAtOnePinStartUP.send(null);
}

function SetCenterAtNewPin() {
    if (xmlHttpCreatingNewPin.readyState == 4 || xmlHttpCreatingNewPin.readyState == "complete") {
        xmlDoc = null;
        var jXpos;
        var jYpos;
        if (xmlHttpCreatingNewPin.responseXML != null) {
            xmlDoc = xmlHttpCreatingNewPin.responseXML;
            //id, xpos, ypos, title, description, club, email, shop
            if (xmlDoc != null) {
                var dataArray = xmlDoc.getElementsByTagName('p');
                var dataArrayLen = dataArray.length;
                for (var x = 0; x < dataArrayLen; x++) {


                    if (dataArray[x].getElementsByTagName("x")[0].childNodes[0] != null) {
                        jXpos = dataArray[x].getElementsByTagName("x")[0].childNodes[0].nodeValue;
                    }
                    if (dataArray[x].getElementsByTagName("y")[0].childNodes[0] != null) {
                        jYpos = dataArray[x].getElementsByTagName("y")[0].childNodes[0].nodeValue;
                    }
                }
            }
            if (jXpos != "" && jYpos != "" && jXpos != null && jYpos != null) {
                setCenter(jXpos, jYpos, 13);
            }
            RefreshPushPins();
        }

    }
}

function GetPinInformation() {
    xmlHttpGetPinInformation = null;
    GetMapView();
    xmlHttpGetPinInformation = GetXmlHttpObject();
    if (xmlHttpGetPinInformation == null) {
        alert("Browser does not support HTTP Request");
        return;
    }

    var url = "getoneuser.php";
    url = url + "?GetUserID=" + document.getElementById('ProfileGetUserID').value;
    url = url + "&GetUserPassword=" + encodeURI(document.getElementById('ProfileGetPassword').value);
    xmlHttpGetPinInformation.onreadystatechange = GetPinInformationShow;
    xmlHttpGetPinInformation.open("GET", url, true);
    xmlHttpGetPinInformation.send(null);
}

function GetPinInformationShow() {
    if (xmlHttpGetPinInformation.readyState == 4 || xmlHttpGetPinInformation.readyState == "complete") {
        var jXpos;
        var jYpos;
        xmlDoc = null;
        if (xmlHttpGetPinInformation.responseXML != null) {
            xmlDoc = xmlHttpGetPinInformation.responseXML;
            //id, xpos, ypos, title, description, club, email, shop
            if (xmlDoc != null) {
                var dataArray = xmlDoc.getElementsByTagName('p');
                var dataArrayLen = dataArray.length;
                for (var x = 0; x < dataArrayLen; x++) {


                    if (dataArray[x].getElementsByTagName("x")[0].childNodes[0] != null) {
                        jXpos = dataArray[x].getElementsByTagName("x")[0].childNodes[0].nodeValue;
                    }
                    if (dataArray[x].getElementsByTagName("y")[0].childNodes[0] != null) {
                        jYpos = dataArray[x].getElementsByTagName("y")[0].childNodes[0].nodeValue;
                    }
                }
            }
            if (jXpos != "" && jYpos != "" && jXpos != null && jYpos != null) {
                setCenter(jXpos, jYpos, 13);
            }
        }
        ClearTextBoxes();
        if (xmlHttpGetPinInformation.responseXML != null) {
            xmlDoc = xmlHttpGetPinInformation.responseXML;
            //id, xpos, ypos, title, description, club, email, shop
            if (xmlDoc != null) {
                var dataArray = xmlDoc.getElementsByTagName('p');
                var dataArrayLen = dataArray.length;
                if (dataArrayLen == 0) {
                    alert("Wrong PushPinID or password");
                }
                for (var i = 0; i < dataArrayLen; i++) {
                    var jID;
                    var jXpos;
                    var jYpos;
                    var jTitle;
                    var jDescription;
                    var jClub;
                    var jEmail;
                    var jShop;
                    var jPassword

                    if (dataArray[i].getElementsByTagName("id")[0].childNodes[0] != null) {
                        jID = dataArray[i].getElementsByTagName("id")[0].childNodes[0].nodeValue;
                    }
                    if (dataArray[i].getElementsByTagName("x")[0].childNodes[0] != null) {
                        jXpos = dataArray[i].getElementsByTagName("x")[0].childNodes[0].nodeValue;
                    }
                    if (dataArray[i].getElementsByTagName("y")[0].childNodes[0] != null) {
                        jYpos = dataArray[i].getElementsByTagName("y")[0].childNodes[0].nodeValue;
                    }
                    if (dataArray[i].getElementsByTagName("t")[0].childNodes[0] != null) {
                        jTitle = dataArray[i].getElementsByTagName("t")[0].childNodes[0].nodeValue;
                    }
                    if (dataArray[i].getElementsByTagName("d")[0].childNodes[0] != null) {
                        jDescription = dataArray[i].getElementsByTagName("d")[0].childNodes[0].nodeValue;
                    }
                    if (dataArray[i].getElementsByTagName("c")[0].childNodes[0] != null) {
                        jClub = dataArray[i].getElementsByTagName("c")[0].childNodes[0].nodeValue;
                        if (jClub == 'ON' || jClub == 'on' || jClub == 'On') {
                            jClub = true;
                        }
                        else {
                            jClub = false;
                        }
                    }
                    if (dataArray[i].getElementsByTagName("e")[0].childNodes[0] != null) {
                        jEmail = dataArray[i].getElementsByTagName("e")[0].childNodes[0].nodeValue;
                    }
                    if (dataArray[i].getElementsByTagName("s")[0].childNodes[0] != null) {
                        jShop = dataArray[i].getElementsByTagName("s")[0].childNodes[0].nodeValue;
                        if (jShop == 'ON' || jShop == 'on' || jShop == 'On') {
                            jShop = true;
                        }
                        else {
                            jShop = false;
                        }
                    }
                    if (dataArray[i].getElementsByTagName("pa")[0].childNodes[0] != null) {
                        jPassword = dataArray[i].getElementsByTagName("pa")[0].childNodes[0].nodeValue;
                    }

                    WriteInTextBoxes(jID, jXpos, jYpos, jTitle, jDescription, jClub, jEmail, jShop, jPassword);
                    document.getElementById("submitbutton").setAttribute('value', 'Update pushpin');
                    document.getElementById("submitbutton").disabled = false;
                    document.getElementById("deletebutton").disabled = false;
                    //Handel the user can se the new club, if he has not cheked on clubs
                    if (jShop == false && jClub == false) {
                        if (!viewPerson) {
                            handleViewPerson(); RefreshPushPins();
                        }
                    }
                    if (jClub == true) {
                        if (!viewClub) {
                            handleViewClub(); RefreshPushPins();
                        }
                    }
                    if (jShop == true) {
                        if (!viewShop) {
                            handleViewShop(); RefreshPushPins();
                        }
                    }
                } // for end
            }  // if end
        }
    }
}


function ClearTextBoxes() {
    //Clearing values 
    document.getElementById("hiddenkordinatorXY").value = "";
    document.getElementById("TextName").value = "";
    document.getElementById("TextDescription").value = "";
    document.getElementById("TextShop").checked = false;
    document.getElementById("TextClub").checked = false;
    document.getElementById("chkperson").checked = false;
    document.getElementById("TextEmail").value = "";
    document.getElementById("TextPassword").value = "";
    document.getElementById('TextKordinats').value = "";
    document.getElementById("hiddenuserid").value = "";
    document.getElementById("ProfileGetUserID").value = "";
    document.getElementById("ProfileGetPassword").value = "";
    document.getElementById("panel").value = "";
    document.getElementById("submitbutton").setAttribute('value', 'Register pushpin');
    initilizeMap();
    map.clearOverlays();
    searchResult = null;
    if (mapdirections != null) {
        mapdirections.clear();
    }
    RefreshPushPins();


}

function WriteInTextBoxes(jID, jXpos, jYpos, jTitle, jDescription, jClub, jEmail, jShop, jPassword) {
    document.getElementById("TextName").value = jTitle;
    document.getElementById("TextDescription").value = jDescription;
    document.getElementById("TextShop").checked = jShop;
    document.getElementById("TextClub").checked = jClub;
    if (jShop != true && jClub != true) {
        document.getElementById("chkperson").checked = true;
    }
    document.getElementById("TextEmail").value = jEmail;
    document.getElementById("TextPassword").value = jPassword;
    document.getElementById("TextKordinats").value = jXpos + ", " + jYpos;
    document.getElementById("hiddenkordinatorXY").value = jXpos + ", " + jYpos;
    document.getElementById("hiddenuserid").value = jID;
}

function DeletePin() {
    xmlHttp = null;
    xmlHttp = GetXmlHttpObject();
    if (xmlHttp == null) {
        alert("Browser does not support HTTP Request");
        return;
    }

    var deleteuserid = document.getElementById('hiddenuserid').getAttribute('value')
    if (deleteuserid > 0) {
        var url = "deleteuser.php";
        url = url + "?DeleteUserID=" + deleteuserid
        xmlHttp.onreadystatechange = DeleteUserShow;
        xmlHttp.open("GET", url, true);
        xmlHttp.send(null);
    }
}

function DeleteUserShow() {
    if (xmlHttp.readyState == 4 || xmlHttp.readyState == "complete") {
        RefreshPushPins();

    }
    ClearTextBoxes();
}

function HandledNewPushPinVars() {
    // Geting Values
    NewXYPos = document.getElementById('hiddenkordinatorXY').getAttribute('value');
    NewName = document.getElementById("TextName").value;
    NewDescription = document.getElementById("TextDescription").value;
    NewShop = document.getElementById("TextShop").checked;
    NewClub = document.getElementById("TextClub").checked;
    NewEmail = document.getElementById("TextEmail").value;
    Password = document.getElementById("TextPassword").value;
    gUserID = document.getElementById("hiddenuserid").value;

    ClearTextBoxes();
}

function showRowCount() {
    //Handel the rowcount
    var txtRowCount = document.createTextNode(RowCount);
    if (document.getElementById("lblrowCount").firstChild != null) {
        document.getElementById("lblrowCount").replaceChild(txtRowCount, document.getElementById("lblrowCount").firstChild);
    }
    else {
        document.getElementById("lblrowCount").appendChild(txtRowCount);
    }

    // handle the is all loaded value
    if (ShowingAll == 'true') {
        showallurl = "<img id=\"viewallImg\" alt=\"\" src=\"viewall.png\" title=\"All pushpins are showing in the current view\"/>";
        var txtShowingAll = document.createTextNode("Showing All");
    }
    else {
        var txtShowingAll = document.createTextNode("Showing some");
        showallurl = "<img id=\"viewallImg\" alt=\"\" src=\"viewallnot.png\" title=\"Zoom in to get even more details of pushpins representation\"/>";
    }

    document.getElementById("ViewAlldiv").innerHTML = showallurl;
}

function statusTextChange(setText) {
    // handlet the loading status
    var txt = document.createTextNode(setText);
    if (document.getElementById("statusText").firstChild != null) {
        document.getElementById("statusText").replaceChild(txt, document.getElementById("statusText").firstChild);
    }
    else {
        document.getElementById("statusText").appendChild(txt);
    }
}

function GetXmlHttpObject() {
    objXMLHttp = null
    if (window.XMLHttpRequest) {
        objXMLHttp = new XMLHttpRequest()
    }
    else if (window.ActiveXObject) {
        objXMLHttp = new ActiveXObject("Microsoft.XMLHTTP")
    }
    return objXMLHttp
}


function GetMap(posx, posy, zoom) {
    if (GBrowserIsCompatible()) {
        var ct = new GLatLng(posx, posy);
        map = new GMap2(document.getElementById("myMap"), { googleBarOptions: { suppressInitialResultSelection: true, showOnLoad: true} });
        map.addControl(new GLargeMapControl());
        map.addControl(new GMapTypeControl());
        map.enableGoogleBar();

        GEvent.addListener(map, "moveend", function() { oneEndZoom(); });
        GEvent.addListener(map, "movestart", function() { oneStartZoom(); });
        GEvent.addListener(map, "click", function(overlay, point) { onclicklocationEvent(overlay, point); });
        GEvent.addListener(map, "infowindowopen", function() {
            lastPopUpTime = new Date();
        });
        map.setCenter(ct, zoom);
    }
}

//event handler for pushpin event
function onclicklocationEvent(overlay, point) {
    if (point) {
        var x = " " + point.lat();
        var y = " " + point.lng();
        var position = " " + point;
        x = x.replace(" ", "");
        x = x.replace("(", "");
        x = x.replace(")", "");
        y = y.replace(" ", "");
        y = y.replace("(", "");
        y = y.replace(")", "");
        position = position.replace(" ", "");
        position = position.replace("(", "");
        position = position.replace(")", "");

        document.getElementById('TextKordinats').value = position;
        document.getElementById('submitbutton').disabled = false;
        document.getElementById('hiddenkordinatorXY').value = position;

        statusTextChange("");
    }
}

function oneStartZoom() {

}
function oneEndZoom() {
    RefreshPushPins();
}

// Create icon
var pilotIcon = new GIcon();
pilotIcon.image = 'pilot2.png';
pilotIcon.iconSize = new GSize(25, 25);
pilotIcon.iconAnchor = new GPoint(6, 20);
pilotIcon.infoWindowAnchor = new GPoint(5, 1);

var clubIcon = new GIcon();
clubIcon.image = 'helicopter.png';
clubIcon.iconSize = new GSize(25, 25);
clubIcon.iconAnchor = new GPoint(6, 20);
clubIcon.infoWindowAnchor = new GPoint(5, 1);

var shopIcon = new GIcon();
shopIcon.image = 'factory.png';
shopIcon.iconSize = new GSize(25, 25);
shopIcon.iconAnchor = new GPoint(6, 20);
shopIcon.infoWindowAnchor = new GPoint(5, 1);

function loadPinData(pinID, xpos, ypos, title, description, club, email, shop) {
    var serviceDirectionHtml = null;
    var emailServiceHTML = null;
    if (xpos != '' && ypos != '') {
        var iconpath = '';

        if (email == 'emailyes') {
            emailServiceHTML = "<div id=\"mailform\">" +
			                    "Your email:<input type=\"text\" name=\"from\" id=\"from\" onblur=\"checkemail(this)\" />" +
	                            "<textarea name=\"formbody\" id=\"formbody\" rows=\"8\" cols=\"8\"></textarea>" +
	                            "<input type=\"hidden\" name=\"mailto\" id=\"mailto\" value=\"" + pinID + "\" />" +
		                        "<input id=\"sendmailbutton\" type=\"submit\" onclick=\"SendEmail();\" value=\"Send mail\" name=\"sendmailbutton\" /></div>"
        }
        serviceDirectionHtml = "<br />Get directions to here, with address:<br /><input id=\"StartDesAdr\" title=\"Enter your address to get driving directions \" value=\"Enter your address here\" type=\"text\" onkeypress=\"return clickButton(event,\'getstartroutemapadr\')\" style=\"width: 135px;\" maxlength=\"100\" name=\"StartDesAdr\" onfocus=\"select(this)\"  /> <input id=\"getstartroutemapadr\" type=\"button\" value=\"Get directions\" onclick=\"GetDrivinDirectionsAdr(" + pinID + ");\"/>";//                         pin to this pin.<br />  <input id=\"StartDes\" title=\"Enter your PinID to get driving directions \" value=\"Enter your PinID here\" type=\"text\" onkeypress=\"return clickButton(event,\'getstartroutemapid\')\" style=\"width: 135px;\" maxlength=\"21\" name=\"StartDes\" onfocus=\"select(this)\"  /><br />" + "<input id=\"getstartroutemapid\" type=\"button\" value=\"Get directions\" onclick=\"GetDrivinDirections(" + pinID + ");\"/>"
        serviceDirectionHtml = serviceDirectionHtml + "<br /><br />OR get directions to here with your ID:<br /><input id=\"StartDes\" title=\"Enter your Id to get driving directions \" value=\"Enter your ID here\" type=\"text\" onkeypress=\"return clickButton(event,\'getstartroutemapid\')\" style=\"width: 135px;\" maxlength=\"21\" name=\"StartDes\" onfocus=\"select(this)\"  /> <input id=\"getstartroutemapid\" type=\"button\" value=\"Get directions\" onclick=\"GetDrivinDirections(" + pinID + ");\"/>";
        var gpsxresult = dec2dms(xpos);
        var gpsyresult = dec2dms(ypos);
        serviceDirectionHtml = serviceDirectionHtml + "<br /><br />GPS: N " + gpsxresult['d'] + ' ' + gpsxresult['m'] + ' | E ' + gpsyresult['d'] + ' ' + gpsyresult['m'];
        serviceDirectionHtml = serviceDirectionHtml + "<br /><br /><a href=\"http://map.rcheli.dk\?mypinid=" + pinID + "\">PinID:" + pinID + '</a>';

        var markerOptions = null;
        
        if (club == 'on' && shop != 'on') {
            markerOptions = { icon: clubIcon, autoPan: false };
        }
        if (shop == 'on' && club != 'on') {
            markerOptions = { icon: shopIcon, autoPan: false };
        }
        if (shop != 'on' && club != 'on') {
            markerOptions = { icon: pilotIcon, autoPan: false };
        }
        if (markerOptions == null){
            markerOptions = { icon: pilotIcon, autoPan: false };
        }

        var gll = new GLatLng(xpos, ypos);
        var gm = new GMarker(gll, markerOptions);

        GEvent.addListener(gm, "click", function() {
            if (email == 'emailyes') {
                gm.openInfoWindowTabsHtml([new GInfoWindowTab("Info", "<h3>" + title + "</h3>" + description), new GInfoWindowTab("E-mail", emailServiceHTML), new GInfoWindowTab("Services", serviceDirectionHtml)], { maxWidth: 300 });
            }
            else {
                gm.openInfoWindowTabsHtml([new GInfoWindowTab("Info", "<h3>" + title + "</h3>" + description), new GInfoWindowTab("Services", serviceDirectionHtml)], { maxWidth: 300 });
            }
        });

        map.addOverlay(gm);
        myGMarkerArray[myGMarkerArrayI] = gm;
        myGMarkerArrayI = myGMarkerArrayI + 1;
    }
}

function dec2dms(deg)
{
    var results = new Array();

    results['d'] = Math.floor(deg);
    var remainder = deg - (results['d'] * 1.0);
    var gpsmin = remainder * 60.0;
    results['m'] = roundNearest(gpsmin, -1000)
    return results;
}
        
function roundNearest(num, acc){
    if ( acc < 0 ) {
        num *= acc;
        num = Math.round(num);
        num /= acc;
        return num;
    } else {
        num /= acc;
        num = Math.round(num);
        num *= acc;
        return num;
    }
}

function GetMapView() {
    var topleft = map.getBounds().getNorthEast();
    var bottomright = map.getBounds().getSouthWest();
    topleft = topleft.toUrlValue();
    bottomright = bottomright.toUrlValue();

    var my_temp_Array = bottomright.split(",");
    if (my_temp_Array[0] != null && my_temp_Array[1] != null) {
        XMinValue = my_temp_Array[0];
        YMinValue = my_temp_Array[1];
    }

    my_temp_Array = topleft.split(",");
    if (my_temp_Array[0] != null && my_temp_Array[1] != null) {
        XMaxValue = my_temp_Array[0];
        YMaxValue = my_temp_Array[1];
    }

    XMinValue = XMinValue.replace(" ", "");
    XMinValue = XMinValue.replace("(", "");
    XMinValue = XMinValue.replace(")", "");
    YMaxValue = YMaxValue.replace(" ", "");
    YMaxValue = YMaxValue.replace("(", "");
    YMaxValue = YMaxValue.replace(")", "");
    XMaxValue = XMaxValue.replace(" ", "");
    XMaxValue = XMaxValue.replace(")", "");
    XMaxValue = XMaxValue.replace("(", "");
    YMinValue = YMinValue.replace(" ", "");
    YMinValue = YMinValue.replace(")", "");
    YMinValue = YMinValue.replace("(", "");
}

if (typeof (window.external) != 'undefined') {
    //yes, this is evil browser sniffing, but only IE has this bug
    document.getElementsByName = function(name, tag) {
        if (!tag) {
            tag = '*';
        }
        var elems = document.getElementsByTagName(tag);
        var res = []
        for (var i = 0; i < elems.length; i++) {
            att = elems[i].getAttribute('name');
            if (att == name) {
                res.push(elems[i]);
            }
        }
        return res;
    }

}

function setCenter(posx, posy, zoom) {
    var ct = new GLatLng(posx, posy);
    map.setCenter(ct, zoom);
}

function setViewIcon() {
    if (viewPerson == true) {
        document.getElementById("btnPerson").innerHTML = "<img src=\"pilot2active.png\" alt='' title=\"Viewing fellow RC pilots\"/>";
    }
    else {
        document.getElementById("btnPerson").innerHTML = "<img src=\"pilot2inactive.png\" alt='' title=\"Viewing fellow RC pilots\"/>";
    }
    if (viewClub == true) {
        document.getElementById("btnClub").innerHTML = "<img src=\"helicopteractive.png\" alt='' title=\"Viewing RC flying fields\" />";
    }
    else {
        document.getElementById("btnClub").innerHTML = "<img src=\"helicopterinactive.png\" alt='' title=\"Viewing RC flying fields\"/>";
    }
    if (viewShop == true) {
        document.getElementById("btnShop").innerHTML = "<img src=\"factoryactive.png\" alt='' title=\"Viewing RC shops\"  />";
    }
    else {
        document.getElementById("btnShop").innerHTML = "<img src=\"factoryinactive.png\" alt='' title=\"Viewing RC shops\" />";
    }
}

// toggel the boolean
function handleViewPerson() {
    if (viewPerson == true) {
        viewPerson = false;
    }
    else {
        viewPerson = true;
    }
    setViewIcon();
}
// toggel the boolean
function handleViewClub() {
    if (viewClub == true) {
        viewClub = false;
    }
    else {
        viewClub = true;
    }
    setViewIcon();
}
// toggel the boolean
function handleViewShop() {
    if (viewShop == true) {
        viewShop = false;
    }
    else {
        viewShop = true;
    }
    setViewIcon();
}

function validate(field) {
    var valid = "'*¨~^´`|(){}!#¤%[]"
    var ok = "yes";
    var temp;

    if (field.value.indexOf("script") > -1) {
        alert("Invalid entry!  Only characters and numbers are accepted!");
    }

    if (field.value.indexOf("<?") > -1) {
        alert("Invalid entry!  Only characters and numbers are accepted!");
    }

    for (var i = 0; i < field.value.length; i++) {
        temp = "" + field.value.substring(i, i + 1);
        if (valid.indexOf(temp) != "-1") ok = "no";
    }
    if (ok == "no") {
        alert("Invalid entry!  Only characters and numbers are accepted!");
        field.focus();
        field.select();
    }
}

function checkemail(field) {
    var valid = "1234567890qwertyuiop[]asdfghjklzxcvbnm.@-_QWERTYUIOPASDFGHJKLZXCVBNM";
    var ok = "yes";
    var temp;
    for (var i = 0; i < field.value.length; i++) {
        temp = "" + field.value.substring(i, i + 1);
        if (valid.indexOf(temp) == "-1") ok = "no";
    }
    if (ok == "no") {
        alert("Invalid entry!  Only characters and numbers are accepted!");
        field.focus();
        field.select();
    }
}

function initilizeMap() {
    document.getElementById("submitbutton").disabled = true;
    document.getElementById("deletebutton").disabled = true;
}

function GetDrivinDirections(EndDestinationPinID) {
    if (EndDestinationPinID < 0) {
        SearchStarteDestinations = EndDestinationPinID;
    }

    var StartDestinationPinID = document.getElementById("StartDes").value;
    if (StartDestinationPinID != "" && StartDestinationPinID != "Your PinID") {//xmlHttpGetDrivingDirection
        xmlHttpGetDrivingDirection = null;
        GetMapView();
        xmlHttpGetDrivingDirection = GetXmlHttpObject();
        if (xmlHttpGetDrivingDirection == null) {
            alert("Browser does not support HTTP Request");
            return;
        }
        var url = "getdrivingdirection.php";
        url = url + "?StartPinID=" + StartDestinationPinID + "&EndPinID=" + EndDestinationPinID;
        xmlHttpGetDrivingDirection.onreadystatechange = ShowingDrivingDirection;
        xmlHttpGetDrivingDirection.open("GET", url, true);
        xmlHttpGetDrivingDirection.send(null);
    }
}

function ShowingDrivingDirection() {
    if (xmlHttpGetDrivingDirection.readyState == 4 || xmlHttpGetDrivingDirection.readyState == "complete") {
        var jXpos;
        var jYpos;
        if (SearchStarteDestinations) {

            if (xmlHttpGetDrivingDirection.responseXML != null) {
                xmlDoc = xmlHttpGetDrivingDirection.responseXML;
                //id, xpos, ypos, title, description, club, email, shop
                if (xmlDoc != null) {
                    var dataArray = xmlDoc.getElementsByTagName('p');
                    var dataArrayLen = dataArray.length;
                    if (dataArrayLen == 2) {
                        if (dataArray[0].getElementsByTagName("x")[0].childNodes[0] != null &&
		                    dataArray[0].getElementsByTagName("y")[0].childNodes[0] != null &&
		                    dataArray[1].getElementsByTagName("x")[0].childNodes[0] != null &&
		                    dataArray[1].getElementsByTagName("y")[0].childNodes[0] != null) {

                            GetRouteMap(dataArray[0].getElementsByTagName("x")[0].childNodes[0].nodeValue,
		                        dataArray[0].getElementsByTagName("y")[0].childNodes[0].nodeValue,
		                        searchResult[ChngeSign(SearchStarteDestinations) - 1].LatLong.Latitude,
		                        searchResult[ChngeSign(SearchStarteDestinations) - 1].LatLong.Longitude)
                        }
                    }
                }
            }
            SearchStarteDestinations = null;
        }
        else {
            if (xmlHttpGetDrivingDirection.responseXML != null) {
                xmlDoc = xmlHttpGetDrivingDirection.responseXML;
                //id, xpos, ypos, title, description, club, email, shop
                if (xmlDoc != null) {
                    var dataArray = xmlDoc.getElementsByTagName('p');
                    var dataArrayLen = dataArray.length;
                    if (dataArrayLen == 2) {
                        if (dataArray[0].getElementsByTagName("x")[0].childNodes[0] != null &&
		                    dataArray[0].getElementsByTagName("y")[0].childNodes[0] != null &&
		                    dataArray[1].getElementsByTagName("x")[0].childNodes[0] != null &&
		                    dataArray[1].getElementsByTagName("y")[0].childNodes[0] != null) {
                            GetRouteMap(dataArray[0].getElementsByTagName("x")[0].childNodes[0].nodeValue,
		                        dataArray[0].getElementsByTagName("y")[0].childNodes[0].nodeValue,
		                        dataArray[1].getElementsByTagName("x")[0].childNodes[0].nodeValue,
		                        dataArray[1].getElementsByTagName("y")[0].childNodes[0].nodeValue)
                        }
                    }
                }
            }
        }
    }
}

function GetDrivinDirectionsAdr(EndDestinationPinID) {
    var StartDestinationAdr = document.getElementById("StartDesAdr").value;
    if (StartDestinationAdr != "" && StartDestinationAdr != "Enter your address here"){
        xmlHttpGetDrivingDirection = null;
        GetMapView();
        xmlHttpGetDrivingDirection = GetXmlHttpObject();
                if (xmlHttpGetDrivingDirection == null) {
            alert("Browser does not support HTTP Request");
            return;
        }
        var url = "getdrivingdirection.php";
        url = url + "?StartPinID=" + " " + "&EndPinID=" + EndDestinationPinID;
        xmlHttpGetDrivingDirection.onreadystatechange = ShowingDrivingDirectionAdr;
        xmlHttpGetDrivingDirection.open("GET", url, true);
        xmlHttpGetDrivingDirection.send(null);
    }
}

function ShowingDrivingDirectionAdr() {
    if (xmlHttpGetDrivingDirection.readyState == 4 || xmlHttpGetDrivingDirection.readyState == "complete") {
        var StartDestinationAdr = document.getElementById("StartDesAdr").value;
            if (xmlHttpGetDrivingDirection.responseXML != null) {
                xmlDoc = xmlHttpGetDrivingDirection.responseXML;
                //id, xpos, ypos, title, description, club, email, shop
                if (xmlDoc != null) {
                    var dataArray = xmlDoc.getElementsByTagName('p');
                    var dataArrayLen = dataArray.length;
                    if (dataArrayLen == 2) {
                        if (dataArray[1].getElementsByTagName("x")[0].childNodes[0] != null &&
		                    dataArray[1].getElementsByTagName("y")[0].childNodes[0] != null) {
                            GetRouteMapAdr(StartDestinationAdr, dataArray[1].getElementsByTagName("x")[0].childNodes[0].nodeValue,
		                        dataArray[1].getElementsByTagName("y")[0].childNodes[0].nodeValue);
                        }
                    }
                }
            }
    }
}

function ChngeSign(valuePars) {
    var temp = parseFloat(valuePars);
    var ting = temp * -1;
    return ting;
}


function GetRouteMap(startx, starty, endx, endy) {
    mapdirections = new GDirections(map, document.getElementById("panel"));
    var directionsString = "from: " + startx + "," + starty + " to: " + endx + "," + endy;
    mapdirections.load(directionsString);
}

function GetRouteMapAdr(startAdr, endx, endy) {
    mapdirections = new GDirections(map, document.getElementById("panel"));
    var directionsString = "from: " + startAdr + " to: " + endx + "," + endy;
    mapdirections.load(directionsString);
}


//postback to email form
function sendtomailform(mailid) {
    document.getElementById('useridmail').setAttribute('value', mailid);
    document.themailform.submit();
}


function CenterOneUserAtLoad() {
    // Build an empty URL structure in which we will store
    // the individual query values by key.
    var objURL = new Object();

    // Use the String::replace method to iterate over each
    // name-value pair in the query string. Location.search
    // gives us the query string (if it exists).
    window.location.search.replace(new RegExp("([^?=&]+)(=([^&]*))?", "g"),
    // For each matched query string pair, add that
    // pair to the URL struct using the pre-equals
    // value as the key.
    function($0, $1, $2, $3) {
        objURL[$1] = $3;
    });

    for (var strKey in objURL) {
        // Output the key to the document.
        if (strKey.toLowerCase() == "mypinid") {
            SetCenterAtOnePinStartUP(objURL[strKey]);
        }
        if (strKey.toLowerCase() == "find") {
            FindCenterAtOnePinStartUP(objURL[strKey]);
        }

        // handel the views
        if (strKey.toLowerCase() == "club") {
            if (!viewClub) {
                if (viewPerson) {
                    handleViewPerson();
                }
                if (viewShop) {
                    handleViewShop();
                }
                handleViewClub(); RefreshPushPins();
            }
        }
        if (strKey.toLowerCase() == "shop") {
            if (!viewShop) {
                if (viewPerson) {
                    handleViewPerson();
                }
                if (viewClub) {
                    handleViewClub();
                }
                handleViewShop(); RefreshPushPins();
            }

        }
    }
}

function clickButton(e, buttonid) {
    var evt = e ? e : window.event;
    var bt = document.getElementById(buttonid);
    if (bt) {
        if (evt.keyCode == 13) {
            bt.click();
            return false;
        }
    }
}

function SetCenterLanLon(point, zoom) {
    map.setCenter(point, zoom);
}

function CallBackResults(layer, resultsArray, places, hasMore, veErrorMessage) {
    searchResult = resultsArray;
    loadSearchResultPins();
}

function loadSearchResultPins() {
    if (searchResult) {
        if (searchResult.length > 0) {
            for (var i = 0; searchResult.length > i; i++) {
                //l(pinID, xpos, ypos, title, description, club, email, shop)
                loadPinData(-1 - i, searchResult[i].LatLong.Latitude, searchResult[i].LatLong.Longitude, searchResult[i].Name, searchResult[i].Description + "<br/>" + searchResult[i].Phone, false, null, 'on');
            }
        }
    }
}

function toggleBox(ck) {
    var ck_arr = document.getElementsByName(ck.name);
    var ca_ln = ck_arr.length;
    if (ck.checked) {
        for (var i = 0; i < ca_ln; i++) {
            if (ck_arr[i].id != ck.id) {
                ck_arr[i].checked = false;
            }
        }
    } else {
        ck_arr[0].checked = true;
    }
}

function printmap() {
    window.print();
}

function SendEmail() {
    var fromEmail = document.getElementById("from").value;
    var fromMessage = document.getElementById("formbody").value;
    var mailtoID = document.getElementById("mailto").value;

    xmlHttpSendMail = null;
    xmlHttpSendMail = GetXmlHttpObject();
    if (xmlHttpSendMail == null) {
        alert("Browser does not support HTTP Request");
        return;
    }

    if (fromMessage == "" || fromEmail == "") {
        alert("Please write your email address and a message to the user");
    }
    else {
        if (mailtoID > 0) {
            var url = "sendmail.php";
            url = url + "?mailtoID=" + encodeURI(mailtoID);
            url = url + "&fromEmail=" + encodeURI(fromEmail);
            url = url + "&fromMessage=" + encodeURI(fromMessage);
            xmlHttpSendMail.onreadystatechange = MailSendReturn;
            xmlHttpSendMail.open("GET", url, true);
            xmlHttpSendMail.send(null);
        }
    }
}

function MailSendReturn() {
    var xmlDoc = null;
    var emailStatus = null;
    if (xmlHttpSendMail.readyState == 4 || xmlHttpSendMail.readyState == "complete") {
        if (xmlHttpSendMail.responseXML != null) {
            xmlDoc = xmlHttpSendMail.responseXML;
            emailStatus = xmlDoc.getElementsByTagName("mailsend")[0].childNodes[0].nodeValue;
            if (emailStatus == "true") {
                document.getElementById("formbody").value = "Your Message was successfully sent."
                document.getElementById("sendmailbutton").disabled = true;
            }
            else {
                document.getElementById("formbody").value = "Your Message was NOT sent."
                document.getElementById("sendmailbutton").disabled = true;
            }
        }
    }
}

// SEARCH BEGIN
var searchcount = 0;
var searchmax = 10;
var xmlHttpSearchForPushPins;
var dataArraySearchResult;

function BackButton_onclick() {
    if (searchcount > 0) {
        searchcount--;
        document.getElementById('searchCount').firstChild.nodeValue = searchcount;
        nextSearchResult();
    }
}

function ForwardButton_onclick() {
    if (searchcount < searchmax) {
        searchcount++;
        document.getElementById('searchCount').firstChild.nodeValue = searchcount;
        nextSearchResult();
    }
}

function nextSearchResult() {
    var jXpos;
    var jYpos;
    var jclub;
    var jshop;

    if (dataArraySearchResult[searchcount-1].getElementsByTagName("x")[0].childNodes[0] != null) {
        jXpos = dataArraySearchResult[searchcount-1].getElementsByTagName("x")[0].childNodes[0].nodeValue;
    }
    if (dataArraySearchResult[searchcount-1].getElementsByTagName("y")[0].childNodes[0] != null) {
        jYpos = dataArraySearchResult[searchcount-1].getElementsByTagName("y")[0].childNodes[0].nodeValue;
    }
    if (dataArraySearchResult[searchcount-1].getElementsByTagName("c")[0].childNodes[0] != null) {
        jclub = dataArraySearchResult[searchcount-1].getElementsByTagName("c")[0].childNodes[0].nodeValue;
        if (jclub == 'ON' || jclub == 'on' || jclub == 'On') {
            jclub = true;
        }
        else {
            jclub = false;
        }

    }
    if (dataArraySearchResult[searchcount-1].getElementsByTagName("s")[0].childNodes[0] != null) {
        jshop = dataArraySearchResult[searchcount-1].getElementsByTagName("s")[0].childNodes[0].nodeValue;
        if (jshop == 'ON' || jshop == 'on' || jshop == 'On') {
            jshop = true;
        }
        else {
            jshop = false;
        }
    }

    if (jXpos != "" && jYpos != "" && jXpos != null && jYpos != null) {
        //Handel that the user can se the new club, if he has not cheked on clubs
        if (jshop == false && jclub == false) {
            if (!viewPerson) {
                handleViewPerson();
            }
        }
        if (jclub == true) {
            if (!viewClub) {
                handleViewClub();
            }
        }
        if (jshop == true) {
            if (!viewShop) {
                handleViewShop();
            }
        }
        setCenter(jXpos, jYpos, 13);
    }
    //RefreshPushPins();
}

function DOSearch_onclick() {
    var searchFor = document.getElementById('SearchForPushPin').value;
    document.getElementById('searchCount').firstChild.nodeValue = 0;
    searchcount = 0;

    xmlHttpSearchForPushPins = null;
    xmlHttpSearchForPushPins = GetXmlHttpObject();
    if (xmlHttpSearchForPushPins == null) {
        alert("Browser does not support HTTP Request");
        return;
    }
    var url = "searchpins.php";
    url = url + "?Value=" + searchFor;
    xmlHttpSearchForPushPins.onreadystatechange = SearchForResult;
    xmlHttpSearchForPushPins.open("GET", url, true);
    xmlHttpSearchForPushPins.send(null);
}

function SearchForResult() {
    var xmlSearchResult = null;

    if (xmlHttpSearchForPushPins.readyState == 4 || xmlHttpSearchForPushPins.readyState == "complete") {
        xmlDoc = null;
        if (xmlHttpSearchForPushPins.responseXML != null) {
            xmlDoc = xmlHttpSearchForPushPins.responseXML;
            //id, xpos, ypos, title, description, club, email, shop
            if (xmlDoc != null) {
                dataArraySearchResult = xmlDoc.getElementsByTagName('p');
                searchmax = dataArraySearchResult.length;
                document.getElementById('searchCountMax').firstChild.nodeValue = searchmax;
                if (searchmax > 0) {
                    ForwardButton_onclick()
                }
            }

        }

    }
}