var regions = null;
var mapsloc;

/**
 * Loads all Regions from countryID and selects the option of selectID
 */
function loadRegions(country, selectID) {

    var xmlHttpReq = false;
    // Mozilla/Safari
    if (window.XMLHttpRequest) {
        xmlHttpReq = new XMLHttpRequest();
    }
    // IE
    else if (window.ActiveXObject) {
        xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
    }

    var goodurl = '/ajax/ajaxcalls.jsp?action=regions&value='+escape(country);

    xmlHttpReq.open('GET', goodurl);
    xmlHttpReq.onreadystatechange = function() {
        if (xmlHttpReq.readyState == 4 && xmlHttpReq.status==200) {
            var resp = trim(xmlHttpReq.responseText);
            var regions = resp.split(";");

            try {
                $("#regions").unautocomplete();
            } catch (exception) { }


            $("#regions").select();
            $("#regions").autocomplete(regions,{
                minChars: 0,
                max:500,
		formatItem: function(row) {
                        if ((row+"") == "")
                            return "";
                        var itemdata = (row+"").split("?");
			return itemdata[0] +" ("+ itemdata[1] + ")";
		},
		formatResult: function(row) {
                        if ((row+"") == "")
                            return "";
                        var itemdata = (row+"").split("?");
			return itemdata[0];
		}
            });
            
            $("#regions").focus();

        } 
    }
    xmlHttpReq.send(null);
}

function loadTowns(region, country) {

    var xmlHttpReq = false;
    // Mozilla/Safari
    if (window.XMLHttpRequest) {
        xmlHttpReq = new XMLHttpRequest();
    }
    // IE
    else if (window.ActiveXObject) {
        xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
    }

    var goodurl = '/ajax/ajaxcalls.jsp?action=towns&region='+escape(region)+'&country='+escape(country)+'&value=as';

    xmlHttpReq.open('GET', goodurl);
    xmlHttpReq.onreadystatechange = function() {
        if (xmlHttpReq.readyState == 4 && xmlHttpReq.status==200) {
            var resp = trim(xmlHttpReq.responseText);
            var towns = resp.split(";");

            try {
                $("#town").unautocomplete();
            } catch (exception) { }


            //$("#town").val('');
            $("#town").autocomplete(towns,{
                max:500,
                minChars: 0
            });

        }
    }
    xmlHttpReq.send(null);
}

///**
// *
// */
//function startTimerDayInfoPrice(accommodationid, timeinmillis, myHtmlElement) {
//    if (myTimer)
//        clearTimeout(myTimer);
//
//    myTimer = window.setTimeout("setDayInfoPrice("+accommodationid+", "+timeinmillis+", '"+myHtmlElement.id+"')",1000);
//}

/**
 * toggles a Dailyinfo
 */
//var myTimer=null;
//function setDayInfoPrice(accommodationid, timeinmillis, elementID) {
//
//    myHtmlElement = document.getElementById(elementID);
//
//    var xmlHttpReq = false;
//    // Mozilla/Safari
//    if (window.XMLHttpRequest) {
//        xmlHttpReq = new XMLHttpRequest();
//    }
//    // IE
//    else if (window.ActiveXObject) {
//        xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
//    }
//
//    xmlHttpReq.open('GET', 'ajax/ajaxcalls.jsp?action=dayInfoPrice&value='+accommodationid+'&time='+timeinmillis+'&price='+myHtmlElement.value);
//    xmlHttpReq.onreadystatechange = function() {
//        if (xmlHttpReq.readyState == 4) {
//            var resp = trim(xmlHttpReq.responseText);
//
//            if (resp == 'true') {
//                myHtmlElement.style = 'background-colour: green;';
//            } else if (resp == 'false') {
//                myHtmlElement.style = 'background-colour: red;';
//            } else
//                myHtmlElement.style = 'background-colour: red;';
//
//        }
//    }
//    xmlHttpReq.send(null);
//}


function numberInput(el)
{
    var val = el.value.replace(/[^\d]/g, '');
    el.value = val;
}

/**
 * toggles a Dailyinfo
 */
function toggleDayInfo(htmlElement, hiddenElement) {

    if (htmlElement.innerHTML == 'belegt') {
        htmlElement.innerHTML = 'frei';
        document.getElementById(hiddenElement).value = 'frei';
        htmlElement.parentNode.className = 'frei';
    } else {
        htmlElement.innerHTML = 'belegt';
        document.getElementById(hiddenElement).value = 'belegt';
        htmlElement.parentNode.className = 'belegt';
    }
        

/*    var xmlHttpReq = false;
    // Mozilla/Safari
    if (window.XMLHttpRequest) {
        xmlHttpReq = new XMLHttpRequest();
    }
    // IE
    else if (window.ActiveXObject) {
        xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
    }

    xmlHttpReq.open('GET', 'ajax/ajaxcalls.jsp?action=dayInfo&value='+accommodationid+'&time='+timeinmillis);
    xmlHttpReq.onreadystatechange = function() {
        if (xmlHttpReq.readyState == 4) {
            var resp = trim(xmlHttpReq.responseText);
            if (resp == 'true') {
                htmlElement.innerHTML = 'belegt';
                htmlElement.parentNode.className = 'belegt';
            } else if (resp == 'false') {
                htmlElement.innerHTML = 'frei';
                htmlElement.parentNode.className = 'frei';
            } else {
                htmlElement.innerHTML = resp;
                htmlElement.parentNode.className = '';
            }


        }
    }
    xmlHttpReq.send(null);
*/
}


/**
 * Loads all Regions from countryID and selects the option of selectID
 */
function loadAccommodationTypes(paymentMethodID, selectID) {

    var xmlHttpReq = false;
    // Mozilla/Safari
    if (window.XMLHttpRequest) {
        xmlHttpReq = new XMLHttpRequest();
    }
    // IE
    else if (window.ActiveXObject) {
        xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
    }

    xmlHttpReq.open('GET', 'ajax/ajaxcalls.jsp?action=accommodationTypes&value='+paymentMethodID);
    xmlHttpReq.onreadystatechange = function() {
        if (xmlHttpReq.readyState == 4) {
            var resp = trim(xmlHttpReq.responseText);
            var elements = resp.split("?");

            clearSelectElement('accommodationtype');

            for (var i = 0; i < elements.length; i++) {

                var items = elements[i].split(':');

                if (items.length == 2) {
                    if (items[0] == selectID)
                        addOption(document.getElementById('accommodationtype'), items[0], items[1], true);
                    else
                        addOption(document.getElementById('accommodationtype'), items[0], items[1], false);
                }

            }

        }
    }
    xmlHttpReq.send(null);
}

/**
 * clears the regions selectbox
 */
function clearSelectElement(itemName) {
    regions = document.getElementById(itemName);

    if (regions != null) {
        while (regions.options.length > 0) {
            regions.options[0] = null;
        }
    }

}

function addOption(selectbox, value, text, selected ) {
    var optn = document.createElement("OPTION");
    optn.text = text;
    optn.value = value;
    if (selected) 
        optn.selected = true;
    
    selectbox.options.add(optn);
}

function trim (zeichenkette) {
    return zeichenkette.replace (/^\s+/, '').replace (/\s+$/, '');
}

/**
 * Temporarily stores the Accommodation Memotext via Ajax
 */
function setTempMemo(accommodationid, memotext) {
    makePOSTRequest('ajaxcalls.jsp?action=setTempMemo&accid='+accommodationid+'&memo='+memotext, null);
}

function makePOSTRequest(url, targetposition) {
    makePOSTRequest(url, targetposition, null);
}

function makePOSTRequest(url, targetposition, callback) {
    xhttp_request = false;

    if (window.XMLHttpRequest) { // Mozilla, Safari,...
        xhttp_request = new XMLHttpRequest();
        if (xhttp_request.overrideMimeType) {
            // set type accordingly to anticipated content type
            //xhttp_request.overrideMimeType('text/xml');
            xhttp_request.overrideMimeType('text/html');
        }
    } else if (window.ActiveXObject) { // IE
        try {
            xhttp_request = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e) {
            try {
                xhttp_request = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e) {}
        }
    }
    if (!xhttp_request) {
        alert('Cannot create XMLHTTP instance');
        return false;
    }

    xhttp_request.onreadystatechange = function() {
        if (xhttp_request.readyState == 4) {
            if (xhttp_request.status == 200) {
                result = xhttp_request.responseText;
                if(document.getElementById(targetposition)){
                    // Override other Elements
                    document.getElementById(targetposition).innerHTML = result;
                    if (callback != null) {
                        callback();
                    }
                }
            } else {
                alert('There was a problem with the request.');
            }
        }
    };

    xhttp_request.open('POST', url, true);
    xhttp_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xhttp_request.setRequestHeader("Connection", "close");
    xhttp_request.send(null);

    return true;
}

/**
 * loads the Picture into the given Destination
 */
function loadPictureInto(destination, pictureID, link) {
    document.getElementById(destination).src = "loadpicture?id="+pictureID;
    document.getElementById(link).href = "loadpicture?w=800&h=800&id="+pictureID;
}

function closePopup() {
    document.body.removeChild(document.getElementById("popup"));
}

function openPopup(url, title) {
    openPopup(url, title, null);
}

/**
 * Öffnet die angegebene URL über AJAX in einem mittig positionierten Popup-Fenster
 */
function openPopup(url, title, callback) {
    // X-Position ausrechnen
    left = Math.round((document.body.offsetWidth - 490) / 2);

    height = 400;

    // Internet Explorer does implement window.innerHeight
    // Body tag have to be defined before following statement
    windowTop = ((document.documentElement.clientHeight - height) / 2) + 
    document.documentElement.scrollTop;

    // ggf. bereits geöffnetes Popoup schließen
    old = document.getElementById("popup");
    if (old != null) document.body.removeChild(old);

    popup = document.createElement("div");
    popup.id = "popup";
    popup.style.left = left+"px";
    popup.style.top = windowTop+"px";

    headerr = document.createElement("div");
    headerr.className = "popupHeader";

    headline = document.createElement("h1");
    headline.innerHTML = title;
    headline.className = "popupHeadline";

    closebutton = document.createElement("a");
    closebutton.href = "javascript:closePopup();";
    closebutton.innerHTML = "Schlie&szlig;en";
    closebutton.className = "popupCloser"


    content = document.createElement("div");
    content.id = "popupcontent";

    headerr.appendChild(headline);
    headerr.appendChild(closebutton);
    popup.appendChild(headerr);
    popup.appendChild(content);
    
    document.body.appendChild(popup);
    
    makePOSTRequest(url,"popupcontent", callback);
}

/**
 * opens a new Tooltip
 */
function showTooltip(text) {
    Tip(text, BGCOLOR, '#fafafa', BORDERCOLOR, '#A1B43B', FONTFACE, 'Arial, Helvetica, Sans');
}
/**
 * Hides the Tooltip
 */
function hideTooltip() {
    UnTip();
}

/**
 * makes an ajax call to find out how many Hit would be generated with the current Request values
 * Only callable within postrequest.jsp
 */
function calculateHitCount() {

    var regionid = document.getElementById('regions').value;
    var personCount = document.getElementById("personCount").value;
    var dailyprice = document.getElementById("totalprice").value;
    var accommodationtype = document.getElementById("accommodationtype").value;
    var childbeds = document.getElementById("childbeds").value;
    var handicapped = document.getElementById("handicappedaccessible").value;
    var petsallowed = document.getElementById("petsallowed").value;
    var duration = document.getElementById("duration").value;
    
    if (dailyprice == '') {
        document.getElementById("totalprice").value = '0';
        dailyprice = '0';
    }

    // Entfernt sämtliche Textteile aus dem Reisepreis
    var myregex = /^[^0-9]*([0-9]+).*/;
    myregex.exec(dailyprice);
    dailyprice = RegExp.$1;

    var url = "RequestHitCalculator?"
    +"regionid="
    +regionid
    +"&personcount="
    +personCount
    +"&dailyprice="
    +dailyprice
    +"&accommodationtype="
    +accommodationtype
    +"&childbeds="
    +childbeds
    +"&handicappedaccessible="
    +handicapped
    +"&petsallowed="
    +petsallowed
    +"&duration="
    +duration;

    makePOSTRequest(url, "hitcount");
}

/**
 * checks if user really wants to insert Request
 */
function checkHitCountBeforeInsert() {

    var count = document.getElementById("hitcount").innerHTML;
    if (count == 0) {
        res = confirm('Es wurden keine passenden Unterkünfte zu ihrem Gesuch gefunden. Möchten sie dennoch das Gesuch einstellen?');
        if (res == true)
            document.getElementById("requestform").submit();
    } else
        return true;

    return false;
}



