/*-------------this module has scripts for-------------------------
- navigation
- httprequests
- cookie management
- data manipulation in table & detail(form)
- mapping (to support a Google Maps application)
The last two categories may need extensive adaption in scripts to make them work for your needs, but are there as examples
------------------------------------------------------------------*/


/*------------------navigation -----------------------------------*/
function setNav(i) {//skips when i=0
    if(i>0) document.getElementById('nav' + i).className = 'on';
}
function show(subnav, mydiv) {//mydiv is optional;
    if(!mydiv) mydiv=subnav; //if only one number is specified, the [i] for destination[i] is the same as for subnav[i]
    var i;
    for (i = 0; i <= 10; i++) {
        if (document.getElementById('show' + i)) document.getElementById('show' + i).style.display = 'none';
        if (document.getElementById('subnav' + i)) document.getElementById('subnav' + i).className = 'none';
    }
    document.getElementById('show' + mydiv).style.display = 'block';
    if (document.getElementById("subnav" + subnav)) document.getElementById("subnav" + subnav).className = "subnavfocus";
}
 function togglediv(mydiv) {
    if (document.getElementById(mydiv).style.display == 'block') {
        document.getElementById(mydiv).style.display = "none";
    }
    else {
        document.getElementById(mydiv).style.display = "block";
    }
}
function golink(field) {
    if (document.forms['detail'][field].value != "") window.open(document.forms['detail'][field].value, 'mywindow')
}
/*----------------------------misc------------------------------- */
function clearForm(myform) { //clear detail form if necessary
    var form = document.forms[myform];
    for (i = 0; i < form.elements.length; +i++) {
        form.elements[i].value = "";
        if (form.elements[i].type == "checkbox") {
            form.elements[i].checked = 0;
        }
    }
}
/*------------------httprequests -----------------------------------*/
var destination;
var mycase;
var result;

function getdiv(url, parameters, dest) {
    if (!parameters) parameters = "";//parameters is optional
    if (!dest) { destination = url.substring(0, url.length - 4) } else { destination = dest };//dest is optional; if not defined, it assumes the id of the destination div is the name of the url minus the asp/php suffix
    mycase = "div";
    httpdataRequest('include/' + url, parameters, 'POST');
}
function httpdataRequest(url, parameters,method) {
    http_request = false;
    if (window.XMLHttpRequest) { // Mozilla, Safari,...
        http_request = new XMLHttpRequest();
        if (http_request.overrideMimeType) { // set type accordingly to anticipated content type
            http_request.overrideMimeType('text/html');
        }
    }
    else if (window.ActiveXObject) {
        try {http_request = new ActiveXObject("Msxml2.XMLHTTP");
            http_request.setRequestHeader("Content-Type", "text/xml");
            http_request.setRequestHeader("Cache-Control", "no-cache");
        }catch (e) { try {
                http_request = new ActiveXObject("Microsoft.XMLHTTP");
                http_request.setRequestHeader("Content-Type", "text/xml");
                http_request.setRequestHeader("Cache-Control", "no-cache");
            } catch (e) { }        }
    }
    if (!http_request) {alert('Giving up :(Cannot create XMLHTTP instance)');return false;}
    http_request.onreadystatechange = eval('asyncHandler');
    if (method == 'GET') {
        if (parameters == '') { dummy = '?bogus=' + Math.random(); } else { dummy = '&bogus=' + Math.random(); }
        //IMPORTANT: dummy is a hack; adding the dummy to the url causes every URL to be different so that IE does not re-use the stale cache result!!!
        //testing:alert(url+ parameters+dummy);
        http_request.open('GET', url + parameters + dummy, true);
        http_request.send(null);
    }
    else {
        http_request.open('POST', url, true);//alert(url+ parameters);
        http_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        http_request.setRequestHeader("Content-length", parameters.length);
        http_request.setRequestHeader("Connection", "close");
        http_request.send(parameters);
    }
}
function asyncHandler() {
    //try {
        if (http_request.readyState == 4) {
            if (http_request.status == 200) {
                flag_update = 0;//alert(mycase);
                result = http_request.responseText;// alert(result);
                switch (mycase) {
                    case "div": //alert('div: ' + destination);
                        document.getElementById(destination).innerHTML = result;
                        if (!lastshow) { lastshow = "div0"; }  //show=1: force show
                        hideTable(lastshow, 1);
                        break;
                    case "new": if (result != 0) { showDetail(result); break; }
                        else { alert("an error occurred; please log out and log back in"); }
                    case "new1": showDetail(result, 1); break;
                    case "new0": showDetail(result, 0); break;
                    case "accessed": return;
                    case "detail": 
                        loadDetail(result);
                        //updateAccessed();
                        break;
                    case "delete":
                        document.getElementById('content_detail').style.display = "none";
                        document.getElementById('content_table').style.display = "block";
                        getdiv('list.asp', 'find=%', 'table')
                        break;
                    case "markers": loadmarkers(result);
                    default: 
                        self.status = result;
                }
            } else {
                alert(http_request.status + ' sorry; a glitch happened and your data did not get updated...');
            }
        }
   // } catch (e) { }
    }

/*------------------Cookie management -----------------------------------*/
function gogeoreference() {
    position = "?q=" + document.forms['detail']['lattitude'].value + ",+ " + document.forms['detail']['longitude'].value + "(" + document.forms['detail']['item'].value + ")&iwloc=A&hl=en";
    url = "http://maps.google.com/maps" + position;
    window.open(url, "map");
}
function geoconvert(id) {
    dest = (id.substring(0, 4) == 'latt' ? 'lattitude' : 'longitude');
    id = id.substring(0, 4);
    NW = ((document['detail'][id + 'NW'].value == 'S') || (document['detail'][id + 'NW'].value == 'W')) ? -1 : 1;
    if (document['detail'][id + 'degrees'].value != 'degrees' && document['detail'][id + 'minutes'].value != 'minutes' && document['detail'][id + 'seconds'].value != 'seconds') {
        degrees = document.getElementById(id + 'degrees').value;
        minutes = document.getElementById(id + 'minutes').value / 60;
        seconds = (document.getElementById(id + 'seconds').value) / 3600;
        conversion = NW * (parseFloat(degrees) + parseFloat(minutes) + parseFloat(seconds));

        document['detail'][dest].value = conversion; ;
        update(dest);
    }
}
function set_cookie(name, value, expires, path, domain, secure) {
    // set time, it's in milliseconds
    var today = new Date();
    today.setTime(today.getTime());
    /*
    if the expires variable is set, make the correct
    expires time, the current script below will set
    it for x number of days, to make it for hours,
    delete * 24, for minutes, delete * 60 * 24
    */
    if (expires) {
        expires = expires * 1000 * 60 * 60 * 24;
    }
    var expires_date = new Date(today.getTime() + (expires));
    document.cookie = name + "=" + escape(value) +
	((expires) ? ";expires=" + expires_date.toGMTString() : "") +
	((path) ? ";path=" + path : "") +
	((domain) ? ";domain=" + domain : "") +
	((secure) ? ";secure" : "");
    if (!get_cookie(name)) { alert("cookie was not set; perhaps no https://?") }
}
function get_cookie(check_name) {
    // first we'll split this cookie up into name/value pairs
    // note: document.cookie only returns name=value, not the other components
    var a_all_cookies = document.cookie.split(';');
    var a_temp_cookie = '';
    var cookie_name = '';
    var cookie_value = '';
    var b_cookie_found = false; // set boolean t/f default f

    for (i = 0; i < a_all_cookies.length; i++) {
        // now we'll split apart each name=value pair
        a_temp_cookie = a_all_cookies[i].split('=');


        // and trim left/right whitespace while we're at it
        cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');

        // if the extracted name matches passed check_name
        if (cookie_name == check_name) {
            b_cookie_found = true;
            // we need to handle case where cookie has no value but exists (no = sign, that is):
            if (a_temp_cookie.length > 1) {
                cookie_value = unescape(a_temp_cookie[1].replace(/^\s+|\s+$/g, ''));
            }
            // note that in cases where cookie is initialized but no value, null is returned
            return cookie_value;
            break;
        }
        a_temp_cookie = null;
        cookie_name = '';
    }
    if (!b_cookie_found) {
        return null;
    }
}
function delete_cookie(name, path, domain) {
    if (get_cookie(name)) document.cookie = name + "=" +
    ((path) ? ";path=" + path : "") +
    ((domain) ? ";domain=" + domain : "") +
    ";expires=Thu, 01-Jan-1970 00:00:01 GMT";
}

function loadfromcookie() {
    var a = get_cookie("profile").split(",");
    //var a=result.split(regexpr);//0]=>
    a.forEach(alert);
}
/*----------------------------table & detail manipulation--------------- */
var lastshow;

function hideTable(myid, show) {
    if (!show) { show = 0; }  //show=1: force show
    var mytable = 'table' + myid.slice(4);
    return;if (!document.getElementById(mytable)) return;
    if ((document.getElementById(mytable).className == "listing show_group") || (show = !1)) {
        document.getElementById(mytable).className = "listing hide_group";
        if (!document.getElementById(myid)) return;
        document.getElementById(myid).innerHTML = "&nbsp;+&nbsp;";
        return;
    }

    document.getElementById(mytable).className = 'listing show_group';
    document.getElementById(myid).innerHTML = "&nbsp;-&nbsp;";
    lastshow = myid;
}
function toggledetail() {
    if (document.getElementById('content_detail').style.display == 'block') {
        if (document.forms['detail']['item'].value == "New amenity...") {
            if (confirm("You have not named this amenity. If you click OK this entry will be deleted -- Click CANCEL to still give this amenity a name...")) {
                deleterecord(document['detail']['id'].value); return;
            }
        }
        if (document['detail']['cat_id'].options[document['detail']['cat_id'].selectedIndex].text == 'Choose...' || document['detail']['subj1_id'].options[document['detail']['subj1_id'].selectedIndex].text == "Choose...")
        { alert("Please select a category and (one) subject before you close this amenity.."); return; }

        document.getElementById('content_detail').style.display = "none";
        document.getElementById('content_table').style.display = "block";
        getdiv('list.asp', 'find=%', 'table')
    }
    else {
        document.getElementById('content_detail').innerHTML = "loading your ";
        document.getElementById('content_detail').style.display = "block";
        document.getElementById('content_table').style.display = "none";
    }
}
function addrecord() {
    checklogin();
    toggledetail();
    getdiv('detail.asp', "find=new&sponsor=" + sponsor, "detail");
} function deleterecord(id) {
    if (confirm("This will delete this record and cannot be undone; are you sure?")) {
        mycase = "delete";
        httpdataRequest("include/deleterecord.asp", "id=" + id, 'POST');
    }
}
function update(id, dropdown) {
    if (dropdown === undefined) dropdown = 0;
    mycase = "";
    checklogin();
    if (dropdown == 1) {
        index = document['detail'][id].selectedIndex;
        if (document['detail'][id].options[document['detail'][id].selectedIndex].text == 'other') {
            dropdown = prompt("Please specify", "dropdown category");
            if (dropdown == null) { return; }
            myvalue = prompt("Please verify for typos", dropdown);
            document['detail'][id].options[index].text = dropdown;
        } else { myvalue = document['detail'][id].value }
        if ([id] == 'cat_id') {
            setsubjects(document['detail'][id].options[document['detail'][id].selectedIndex].text);
        }

    } else { myvalue = document['detail'][id].value; }
    myindex = document['detail']['id'].value;
    myvalue = myvalue.replace(/ /g, "chr(32)");
    myvalue = myvalue.replace(/&/g, " and ");
    myvalue = myvalue.replace(/"/g, "'");
    myvalue = myvalue.replace(/'/g, "chr(39)");
    parameters = "id=" + myindex + "&sponsor=" + sponsor + "&field=" + id + "&value=" + myvalue;
    httpdataRequest('include/update.asp', parameters, 'POST');
}
function setsubjects(category) {
    document['detail']['subj1_id'].innerHTML = "<option selected>Choose...</option>" + document.getElementById(category).innerHTML;
    document['detail']['subj2_id'].innerHTML = "<option selected></option>" + document.getElementById(category).innerHTML;
}

/*------------------Mapping -----------------------------------*/
var sponsor;
function checklogin() {
    sponsor = get_cookie('sponsor')
    if (sponsor == null) {
        sponsor = prompt("Logging who added - just your first name", "name");
        set_cookie("sponsor", sponsor)
    }
}
function gogeoreference() {
    position = "?q=" + document.forms['detail']['lattitude'].value + ",+ " + document.forms['detail']['longitude'].value + "(" + document.forms['detail']['item'].value + ")&iwloc=A&hl=en";
    url = "http://maps.google.com/maps" + position;
    window.open(url, "map");
}
function geoconvert(id) {
    dest = (id.substring(0, 4) == 'latt' ? 'lattitude' : 'longitude');
    id = id.substring(0, 4);
    NW = ((document['detail'][id + 'NW'].value == 'S') || (document['detail'][id + 'NW'].value == 'W')) ? -1 : 1;
    if (document['detail'][id + 'degrees'].value != 'degrees' && document['detail'][id + 'minutes'].value != 'minutes' && document['detail'][id + 'seconds'].value != 'seconds') {
        degrees = document.getElementById(id + 'degrees').value;
        minutes = document.getElementById(id + 'minutes').value / 60;
        seconds = (document.getElementById(id + 'seconds').value) / 3600;
        conversion = NW * (parseFloat(degrees) + parseFloat(minutes) + parseFloat(seconds));

        document['detail'][dest].value = conversion; ;
        update(dest);
    }
}
function mapit(lat, lng) {
    document['detail']['lattitude'].value = lat;
    document['detail']['longitude'].value = lng;
    mycase = "";
    togglediv('map');
    httpdataRequest('include/update.asp', "id=" + document['detail']['id'].value + "&sponsor=" + sponsor + "&field=latlng&lat=" + lat + "&lng=" + lng, 'POST');
}
   
    
    
    
    
