var isIE6 = navigator.appName == "Microsoft Internet Explorer" && parseFloat(navigator.appVersion) < 7;

var activeElement = null;
var countries = null;
var fResetCountries = false;

function findObj(id) {
    if (document.getElementById) {
        return document.getElementById(id);
    } else if (document.all) {
        return document.body.all[id];
    }
    return null;
}

function hide() {
    if (activeElement) {
        findObj(activeElement).style.display = "none";
    }
   activeElement = null;
}

function show(id) {
    hide();
    activeElement = id;                                                       
    findObj(activeElement).style.display = "block";
}

function check(name, id) {
    var o = eval("document.formular."+ name);
    var i = 0;
    for (i = 0; i < o.length; i++) {
        if (o[i].value == id) {
            o[i].checked = true;
            break;
        }
    }
}

function checkCheckbox(name) {
    var o = eval("document.formular."+ name);
    if (o) {
        if (o.checked || o.disabled) {
            o.checked = false;
        } else {
            o.checked = true;
        }
    }
}

function setLocation() {
    var a = findObj('auswahl');
    var b = findObj('location');
    b.value = a.options[a.selectedIndex].text;
}

function clearInput() 
{
    $('EinstellungenZielnummer').value = '';
    if ($('pricediv')) {
        Element.remove('pricediv');
        Element.remove('footnotes');
    }
}

function clearCountrySelection()
{
    var inputField = findObj('EinstellungenLandwahl');
    inputField.options[inputField.selectedIndex].selected = 0;
}

function onMobileSelect()
{
    if ($('pricediv')) {
        Element.remove('pricediv');
        Element.remove('footnotes');
    }
}

function selectEnteredCountry(country)
{
    var i = $('EinstellungenLandwahl').length;
    
    while (i-- > 0) {
        if ($('EinstellungenLandwahl').options[i].value == country) {
            $('EinstellungenLandwahl').selectedIndex = i;
            break;
        }
    };
    return false;
}


function updateCountry(item)
{
    var inputField = findObj('EinstellungenZielnummer');
    var value      = inputField.value;
    
    var p = item.id.lastIndexOf('-') + 1;
    var q = item.id.lastIndexOf('-', p - 2) + 1;
    
    var countryCode = item.id.substr(p);
    var countryId   = item.id.substr(q, p - q - 1);

    clearCountrySelection();
    
    while ((value.substr(0, 1) == '+') || (value.substr(0, 1) == '0')) {
        value = value.substr(1);
    }
    if (value.substr(0, countryCode.length) != countryCode) { 
        value = countryCode;
    }
    inputField.value = '+' + value;

    selectEnteredCountry(countryId);
}

function removePriceAndFooter()
{
    if ($('pricediv')) {
        Element.remove('pricediv');
    }
    if ($('footnotes')) {
        Element.remove('footnotes');
    }
}

function showAusland()
{
    var btnShowAusland = findObj('btn_show_ausland');
    btnShowAusland.click();
}
function showInland()
{
    var btnShowInland = findObj('btn_show_inland');
    btnShowInland.click();
}
function clearTarSelection()
{
    if ($('EinstellungenZielortauswahl'))
    {
        $('EinstellungenZielortauswahl').options[$('EinstellungenZielortauswahl').selectedIndex].selected = null;
        Element.remove('EinstellungenZielortauswahl');
        Element.remove('umbruch');
    }
    if ($('pricediv')) {
        Element.remove('pricediv');
        Element.remove('footnotes');
    }
}

function clearLocSelection()
{
    if ($('EinstellungenStandortauswahl'))
    {    
        $('EinstellungenStandortauswahl').options[inputField.selectedIndex].selected = null;
    
        Element.remove('EinstellungenStandortauswahl');
        Element.remove('umbruch');
    }
    if ($('pricediv')) {
        Element.remove('pricediv');
        Element.remove('footnotes');
    }
}    

function setLocInput()
{
    if ($('EinstellungenStandort') && $('EinstellungenStandortauswahl'))
    {
        var selectedText = $('EinstellungenStandortauswahl').options[$('EinstellungenStandortauswahl').selectedIndex].text;
        $('EinstellungenStandort').value = selectedText;
    }
}

function setTarInput()
{
    if ($('EinstellungenZielort') && $('EinstellungenZielortauswahl'))
    {
        var selectedText = $('EinstellungenZielortauswahl').options[$('EinstellungenZielortauswahl').selectedIndex].text;
        $('EinstellungenZielort').value = selectedText;
    }
}

function setCountry() {
    var c = findObj('location');
    var d = findObj('EinstellungenLandwahl');
    var e = findObj('countryCode');
    var f = findObj('countryId');
    var i = findObj('EinstellungenZielnummer');
    var p = d.options[d.selectedIndex].value.split(":");

    show('location_1');
    findObj('location_2').style.display = 'none';
    c.value = d.options[d.selectedIndex].text;
    e.value = '+'+ p[1];
    f.value = p[0];
    i.value = '+' + p[1];
}

function selectCountry(n, m) {
    var o = n + 10;
    if (o > m-1) {
        o = m-1;
    }
    document.getElementById('EinstellungenLandwahl').selectedIndex=o;
    document.getElementById('EinstellungenLandwahl').selectedIndex=n;
}


function resetCountryCode()
{
    var o = document.getElementById('countrySelect');
    var n;
    var i;
    if (fResetCountries) {
        while (o.length > 0) {
            o.options[o.length - 1] = null;
        }
        for (i=0; i < countries.length; i++) {
            n = new Option(countries[i][0], countries[i][1], false, false);
            o.options[o.length] = n;
        }
        document.getElementById('input_countryCode').value = '';
        document.getElementById('error_countryCode').style.visibility = 'hidden';

        fResetCountries = false;
    }
}


function selectCountryCode() {
    var cc = document.getElementById('input_countryCode').value;
    var p = 0;
    while ((cc.substr(p, 1) == '+') || (cc.substr(p, 1) == '0')) {
        p++;
    }
    cc = cc.substr(p, cc.length - p);
    var o = document.getElementById('countrySelect');
    var i;

    if (countries == null) {
        countries = new Array();
        for (i=0; i < o.length; i++) {
            countries[i] = new Array(o.options[i].text, o.options[i].value);
        }
    }

    while (o.length > 0) {
        o.options[o.length - 1] = null;
    }

    var n;
    var p;
    for (i = 0; i < countries.length; i++) {
        p = countries[i][1].split(":");
        if (cc == p[1]) {
            n = new Option(countries[i][0], countries[i][1], false, false);
            o.options[o.length] = n;
        }
    }
    if (o.length > 0) {
        o.selectedIndex = 0;
        setCountry();
        document.getElementById('error_countryCode').style.visibility = 'hidden';
    } else {
        document.getElementById('error_countryCode').style.visibility = 'visible';
    }

    fResetCountries = true;
}


function resetClock() {
    var d = new Date();
    var h = d.getHours();
    var m = d.getMinutes();
    document.formular.start_h.value = h;
    document.formular.start_m.value = m;
    _checkNum(24, 'start_h');
    _checkNum(60, 'start_m');
    _checkNum(10, 'dauer_h');
    _checkNum(60, 'dauer_m');
    hideCalendar();
}

function up(max, name) {
    var o = eval("document.formular."+ name);
    var v;
    if (o) {
        v = parseInt(o.value, 10) + 1;
    }
    hideCalendar();
    o.value = v;
    _checkNum(max, name, 0);
}

function down(max, name) {
    var o = eval("document.formular."+ name);
    var v;
    if (o) {
        v = parseInt(o.value, 10) - 1;
    }
    hideCalendar();
    o.value = v;
    _checkNum(max, name, 0);
}

function checkNum(max, name) {
    _checkNum(max, name, max-1);
}


function _checkNum(max, name, next) {
    var o = eval("document.formular."+ name);
    var v;
    if (o) {
        v = parseInt(o.value, 10) || 0;
        if (v < 0) {
            v = max - 1;
        } else if (v >= max) {
            v = next;
        }
        if (v < 10) {
            v = "0" + String(v);
        }
        o.value = v;
    }
}

function showCalendar() 
{
	new Ajax.Updater('calendar-div', '../kalender');
	Element.show('calendar-div');
}
function showCalendarPrev (url)
{
    new Ajax.Updater('calendar-div', '../'+url);
}
function showCalendarNext (url)
{
    new Ajax.Updater('calendar-div', '../'+url);
}

function selectDate(mydate)
{
    if ($('EinstellungenDatum'))
    {
        $('EinstellungenDatum').value = mydate;
        hideCalendar();
    }
}
function hideCalendar() 
{
    if ($('calendar-div'))
    {
        Element.hide('calendar-div');
    }
}

function ieHideSelects(displayStyle) {
	if (!isIE6) return;
	var selects = document.getElementsByTagName("select");
	for (var i = 0; i < selects.length; i++) {
		if (displayStyle == "none") {
			selects[i].style.visibility = "hidden";
		}
		if (displayStyle == "inline") {
			selects[i].style.visibility = "visible";
		}
	}
}


// gibt die y-Position des übergebenen elements zurück
function getY( oElement )
{
	var iReturnValue = 0;
	while( oElement != null ) {
		iReturnValue += oElement.offsetTop;
		oElement = oElement.offsetParent;
	}
	return iReturnValue;
}

//gibt die x-Position des übergebenen elements zurück
function getX( oElement )
{
	var iReturnValue = 0;
	while( oElement != null ) {
		iReturnValue += oElement.offsetLeft;
		oElement = oElement.offsetParent;
	}
	return iReturnValue;
}

// berechnet die hoehe der renderfläche des browsers
function Fensterhoehe(){
	  if(window.innerHeight) { 
	   return window.innerHeight;
	  } else if (document.documentElement&&document.documentElement.clientHeight){
	   return document.documentElement.clientHeight;
	  } else if (document.body) {
	   return document.body.offsetHeight;
	  }
	}

//berechnet die breite der renderfläche des browsers
function Fensterweite(){
	  if(window.innerWidth){
	   return window.innerWidth; 
	  } else if (document.documentElement&&document.documentElement.clientWidth){
	   return document.documentElement.clientWidth;
	  } else if (document.body) {
	   return window.document.body.offsetWidth;
	  }
} 

function neuAufbau(){
	windowWidth  = Fensterweite();
	windowHeight = Fensterhoehe();
}

function showInfo(id, sender) {
	focusElement = null;
	
	hideCalendar();
	ieHideSelects("none");
	
    $('infolayer-bg').style.display = "block";
    $('infolayer-bg').style.visibility = "visible";
	dokumentHoehe  = $('thisbody').offsetHeight;
	dokumentBreite = $('thisbody').offsetWidth;
	
	
    
    // Position des auslösenden Elements bestimmen
    senderPosX = getX(sender);
    senderPosY = getY(sender);
    
    // Fensterhöhe bestimmen
    windowWidth  = Fensterweite();
    windowHeight = Fensterhoehe();

    // Scroll-Position bestimmen
	scrollPosY = document.documentElement.scrollTop;
	scrollPosX = document.documentElement.scrollLeft;
    
    // Layer anzeigen
    $(id).style.display = "block";
    $(id).style.visibility = "visible";
    
	// Größe des anzuzeigenden Infolayers bestimmen
    infoLayerHeight = $(id).offsetHeight;
    infoLayerWidth  = $(id).offsetWidth;

    // wenn bereits größer als dokumentHoehe und Breite dann nix machen
	if (dokumentHoehe > $('infolayer-bg').offsetHeight)
	{
		$('infolayer-bg').setStyle({ height: dokumentHoehe + 'px' });
	}

	if (windowHeight > $('infolayer-bg').offsetHeight)
	{
		$('infolayer-bg').setStyle({ height: windowHeight + 'px' });		
	}
    
    
    // wenn infolayer-höhe größer ist als fenster-höhe kann man nix machen
    if (infoLayerHeight > windowHeight)
    { 
    	$(id).setStyle({ top: 20 + 'px' });
    	return;
    }
    
    unterStern = true;
    // wenn platz zwischen sternchen und fensterunterkannte nicht reicht
    if (infoLayerHeight > Math.abs(windowHeight - (senderPosY - scrollPosY)))
    	unterStern = false;
    	
    if (unterStern)
    {
    	document.getElementById(id).style.top = senderPosY + 20 + 'px';
    } else if (infoLayerHeight > senderPosY) {
    	document.getElementById(id).style.top = 20 + 'px';
    } else {    	
    	document.getElementById(id).style.top = senderPosY - infoLayerHeight - 20 + 'px';
    }
    
    focusElement = document.getElementById(id).getElementsByTagName('div')[0].getElementsByTagName('a')[0];
    focusElement.focus();
}

function hideInfo(closeBtn) {
	ieHideSelects("inline");
    document.getElementById("infolayer-bg").style.display = "none";
	closeBtn.parentNode.style.display = "none";
	closeBtn.parentNode.style.visibility = "hidden";
}
 
function showTarifInfo(sender) {
    var index  = $('EinstellungenTarif').selectedIndex;
    var id     = $('EinstellungenTarif').options[index].value;

    var o = findObj('selectAuswahl');
    if (o) {
        o.style.visibility = "hidden";
    }

    id = 'info_'+ id;
    showInfo(id, sender);
}

function showCountryMobileInfo(sender)
{
    showInfo('info_countrymobile', sender);
}

function showCountryMobileInfoSel(sender)
{
    showInfo('info_countrymobile', sender);
}

function showCountryFormatInfo(sender)
{
    showInfo('info_countryformat', sender);
}

function showCountrySelectInfo(sender)
{
    showInfo('info_countryselect', sender);
}

function checkDate() {
    var b = new Date();
    var d = document.formular.datum.value;
    var p = d.split(".");

    if (p.length > 3) {
        d = b.getDate() +"."+ (b.getMonth() + 1) +"."+ b.getFullYear();
    } else {
        p[0] = parseInt(p[0], 10);
        p[1] = parseInt(p[1], 10);
        p[2] = parseInt(p[2], 10);
        for(var i = 0; i < 3; i++) {
            if (String(p[i]) == "NaN") {
                p[i] = 0;
            }

        }
        if (p[2] < b.getFullYear()) {
            p[2] = b.getFullYear();
        } else if (((p[1] >= b.getMonth() + 1) && (p[2] == b.getFullYear() + 1)) || (p[2] > b.getFullYear() + 1)) {
            p[2] = b.getFullYear() + 1;
        }
        if (p[1] < 1) {
            p[1] = 1;
        } else if (p[1] > 12) {
            p[1] = 12;
        } else if ((p[1] > b.getMonth() + 1) && (p[2] > b.getFullYear())) {
            p[1] = b.getMonth() + 1;
        } else if ((p[1] <= b.getMonth() + 1) && (p[2] <= b.getFullYear())) {
            p[1] = b.getMonth() + 1;
        }
        if ((p[0] < 1)) {
            p[0] = 1;
        }
        if (p[0] > 31) {
            p[0] = 31;
        }
        if ((p[0] > 30) && (p[1] != 1) && (p[1] != 3) && (p[1] != 5) && (p[1] != 7) && (p[1] != 8) && (p[1] != 10) && (p[1] != 12)) {
            p[0] = 30;
        }
        if ((p[0] > 28) && (p[1] == 2)) {
            p[0] = 28;
        }
        d = p[0] +"."+ p[1] +"."+ p[2];
    }

    // correct date
    p = d.split(".");
    if (p[0].length < 2) {
        p[0] = "0"+ p[0];
    }
    if (p[1].length < 2) {
        p[1] = "0"+ p[1];
    }
    while (p[2].length < 4) {
        p[2] = "0"+ p[2];
    }
    d = p[0] +"."+ p[1] +"."+ p[2];

    document.formular.datum.value = d;
}


function checkONKZ()
{
    var t = findObj("location").value;

    if (t.substr(0, 3) == "032") {
        check("type", 3);
        return 3;
    } else {
        check("type", 1);
        return 1;
    }
}

var location_val = "";

function selectType(mode, type) {
    hideCalendar();
    check("type", type);
    o = findObj("choose_1");
    if (o) {
        o.style.display = "none";
    }
    o = findObj("choose_2");
    if (o) {
        o.style.display = "none";
    }
    if (mode == 0) { // Inland
        var o = null;
        switch (type) {
            case 1:
            o = findObj("choose_1");
            if (o) {
                o.style.display = "block";
            }
            findObj("location").value = location_val;
            findObj("location_2").style.display = "none";
            findObj("location_3").style.display = "none";
            show("location_1");
            break;

            case 3:
            o = findObj("choose_2");
            if (o) {
                o.style.display = "block";
            }
            o = findObj("choose_1");
            if (o) {
                o.style.display = "none";
            }
            location_val = findObj("location").value;
            findObj("location").value = "032";
            findObj("location_1").style.display = "none";
            findObj("location_2").style.display = "none";
            show("location_3");
            break;

            default:
            o = findObj("choose_1");
            if (o) {
                o.style.display = "block";
            }
            findObj("location_1").style.display = "none";
            findObj("location_3").style.display = "none";
            show("location_"+ type);
        }
    } else if (mode == 1) { // Ausland
        if (type < 3) {
            findObj('targetNr').style.display='none';
        } else {
            findObj('targetNr').style.display='block';
        }
    }
}

function in_array(a, v) {
    for (var i = 0; i < a.length; i++) {
        if (a[i] == v) {
            return true;
        }
    }
    return false;
}

function showOptions() {
    var index   = document.formular.anschluss.selectedIndex;
    var tarifId = document.formular.anschluss.options[index].value;
    var o;
    var val = new Array();
    var n;

    if (tarifId == 0) {
        // disable all options
        for (var i = 0; i < options.length; i++) {
            o = findObj('optional_'+ options[i]);
            p = findObj("text_optional_"+ options[i]);
            if (o) {
                o.checked = false;
                o.disabled = true;
                p.style.color = '#999999';
            }
        }
    } else {
        for (var i = 0; i < combinations.length; i++) {
            if (in_array(combinations[i], tarifId)) {
                for (var j = 0; j < combinations[i].length; j++) {
                    o = findObj('optional_'+ combinations[i][j]);
                    if (o) {
                        val['optional_'+ combinations[i][j]] = false;
                    }
                }
            }
        }
        for (var i = 0; i < options.length; i++) {
            if (val['optional_'+ options[i]] !== false) {
                val['optional_'+ options[i]] = true;
            }
        }

        // show options
        for (var id in val) {
            o = findObj(id);
            p = findObj("text_"+ id);
            if (o) {
                o.disabled = val[id];
                if (val[id]) {
                    o.checked = false;
                    p.style.color = '#999999';
                } else {
                    p.style.color = '#000000';
                }
            }
        }
    }
}



function onLoadFnktns()
{
    if ($('EinstellungenStandort'))
    {
        $('EinstellungenStandort').focus();
    } 
    else if ($('EinstellungenDatum'))
    {
        $('EinstellungenDatum').focus();
    }
    if ($('calendar-div'))
    {
        Element.hide('calendar-div');
        new Draggable('calendar-div');
    }
    if ($('preisanker'))
    {
        location.href='#preis';
    }
}

function submitTab(name, value) {
	try {
		var f = document.forms[0];
		var hf = document.createElement("input");
		hf.type = "hidden";
		hf.name = name;
		hf.value = value;
		f.appendChild(hf);
		f.submit();
		return false;
	}
	catch(e) {}
	return true;
}

/* Einblenden des Fußnoten-Layers */
function zeigeOverlay() {
    /* ID des Overlay-Layers welche die Nachrichtenbox enthält */
    id1 = 'overlay-layer';
    id2 = 'overlay-tabelle';
    id3 = 'preisuebersicht';

    /*
	 * passt die Größe des Hintergrund-Layers an die Größe der
	 * HTML-Tabellenseite an
	 */
    document.getElementById(id1).style.height = document.getElementById(id3).offsetHeight + 10 +"px";
    document.getElementById(id1).style.width = document.getElementById(id3).offsetWidth + 10 + "px";

    /* layer und box anzeigen */
    document.getElementById(id1).style.display = 'block';
    document.getElementById(id2).style.display = 'block';
}

/* Layer und Box ausblenden */
function schliesseOverlay() {
    id1 = 'overlay-layer';
    id2 = 'overlay-tabelle';

    document.getElementById(id1).style.display = 'none';
    document.getElementById(id2).style.display = 'none';
}

function overlayDrucken(sender) {
	//Overlay-box, welche den Druckdialog aufgerufen hat, sichtbar machen
	sender.parentNode.style.display = "block";
	
	attachPrintLayoutToPage('overlay');
	window.print();
}

/**
 * wählt das korrekte Drucklayout (print.css) aus um entweder die Overlays oder die Gesamtansicht zu drucken
 * @param layout kann die werte "overlay" und "page" annehmen
 * @return null
 */
function attachPrintLayoutToPage(layout) {
	
	//wenn bereits ein PrintStylesheet eingebunden wurde, dann muss dieses zuerst entfernt werden
	if (document.getElementById('printStyleSheet') != null) {
		document.getElementsByTagName('head')[0].removeChild(document.getElementById('printStyleSheet'));
	}
	
	var header = document.getElementsByTagName('head')[0];
	var elem = document.createElement("link");
	var attr = document.createAttribute("id");
	attr.nodeValue = "printStyleSheet";
	elem.setAttributeNode(attr);
	attr = document.createAttribute("rel");
	attr.nodeValue = "stylesheet";
	elem.setAttributeNode(attr);
	attr = document.createAttribute("type");
	attr.nodeValue = "text/css";
	elem.setAttributeNode(attr);
	attr = document.createAttribute("media");
	attr.nodeValue = "print";
	elem.setAttributeNode(attr);
	attr = document.createAttribute("href");
	
	//Layout für Overlay druck
	if (layout == "overlay") {
		attr.nodeValue = document.getElementById('basepath').value + "/css/print-overlay.css";
	}
	//Layout für Seitendruck
	if (layout == "page") {
		attr.nodeValue = document.getElementById('basepath').value + "/css/print.css";
	}
	elem.setAttributeNode(attr);
	
	//generierten Link in Dokument einhängen
	header.appendChild(elem);
}

