$(document).ready(function(){
    $("#profil-form").validate({
    
        submitHandler: function(form){
        
            var response = true;
            $("#onlinebewerbungdialog").dialog({
                autoOpen: false,
                bgiframe: true,
                resizable: false,
                modal: false,
                buttons: {
                    "ja": function(){
                        response = true;
                        $(this).dialog("close");
                    },
                    "nein": function(){
                        response = false;
                        $(this).dialog("close");
                    }
                },
                close: function(event, ui){
                    if (response) {
                        form.submit();
                        /*$('#stellenausschreibungform').submit();*/
                    }
                }
            });
            $("#stellendialog").dialog('open');
            
            
        }
        
    });
    
    // Konfiguration für Plugin ajaxForm
    var options = {
        target: '#profil-form', // target element(s) to be updated
        // with server response
        cache: false,
        beforeSubmit: validate, // pre-submit callback
        success: showResponse
        // post-submit callback
    };
    $('#profil-form').ajaxForm(options);
    
    $(function(){
        // a workaround for a flaw in the demo system
        // (http://dev.jqueryui.com/ticket/4375), ignore!
        $("#dialog").dialog("destroy");
        var name = allFields = $([]);
        $("#dialog-form").dialog({
            autoOpen: false,
            height: 'auto',
            width: 400,
            position: 'top',
            modal: true,
            close: function(){
                allFields.val('').removeClass('ui-state-error');
                $("#dialog").dialog("destroy");
                $('#color1, #color2, #color3, #color4').ColorPickerHide();
            }
        });
        
    });
    // Öffnen der Dialogbox
    $("#inhalt_gearpro button").live('click', function(){
        var extra = $(this).attr('extra');
        $('#dialog-form').dialog('open');
        // Attribut "name" des Buttons wird geholt und in der Dialogbox ausgegeben.
        $('#dialog-form').dialog('option', 'title', $(this).attr('name'));
        // Positionierung mittig
        if ($(this).attr('name') == 'produkt buchen') {
            $('#dialog-form').dialog('option', 'width', 926);
            
        }
        else {
            $('#dialog-form').dialog('option', 'position', 'middle');
        }
        // Inhalt der box ajax + position + ausgabe
        if ($(this).attr('name') == 'stellenanzeige verlängern' || $(this).attr('name') == 'kooperationsanfrage' || $(this).attr('name') == 'kooperation bestätigen' || $(this).attr('name') == 'kooperation auflösen' || $(this).attr('name') == 'kooperation annehmen' || $(this).attr('name') == 'mitarbeiter löschen') {
            changeprofil($(this).attr("class"), $(this).attr("text"), extra);
        }
        else {
            var label = $(this).html();
            $(this).html('');
            var buttonValue = $(this).val();
            $(this).html(label);
            
            changeprofil($(this).attr("class"), buttonValue, extra);
        }
    });
    
    // Öffnen der Dialogbox
    $(".profilmenu .paket_buchen").live('click', function(){
        $('#dialog-form').dialog('open');
        // Attribut "name" des Buttons wird geholt und in der Dialogbox ausgegeben.
        $('#dialog-form').dialog('option', 'title', $(this).attr('name'));
        // Positionierung mittig
        if ($(this).attr('name') == 'produkt buchen') {
            $('#dialog-form').dialog('option', 'width', 926);
            
        }
        else {
            $('#dialog-form').dialog('option', 'position', 'middle');
        }
        // Inhalt der box ajax + position + ausgabe
        if ($(this).attr('name') == 'stellenanzeige verlängern' || $(this).attr('name') == 'kooperationsanfrage' || $(this).attr('name') == 'kooperation bestätigen' || $(this).attr('name') == 'kooperation auflösen' || $(this).attr('name') == 'kooperation annehmen' || $(this).attr('name') == 'mitarbeiter löschen') {
            changeprofil($(this).attr("class"), $(this).attr("text"));
        }
        else {
            changeprofil($(this).attr("class"), $(this).attr("value"));
        }
    });
    
    
    
    // Öffnen der Dialogbox
    $("#stellemerkenoben button").live('click', function(){
        $('#dialog-form').dialog('open');
        // Attribut "name" des Buttons wird geholt und in der Dialogbox ausgegeben.
        $('#dialog-form').dialog('option', 'title', $(this).attr('name'));
        // Positionierung mittig
        $('#dialog-form').dialog('option', 'position', 'middle');
        // Breite anpassen
        $('#dialog-form').dialog('option', 'width', 550);
        
        // Inhalt der box ajax + position + ausgabe
        changeprofil($(this).attr("class"), $(this).attr("value"));
    });
    
    $(".profilkontakt").live("click", function(){
    
        $('#dialog-form').dialog('open');
        // Attribut "name" des Buttons wird geholt und in der Dialogbox ausgegeben.
        $('#dialog-form').dialog('option', 'title', $(this).attr('name'));
        // Positionierung mittig
        $('#dialog-form').dialog('option', 'position', 'middle');
        // Breite anpassen
        $('#dialog-form').dialog('option', 'width', 450);
        // Inhalt der box ajax + position + ausgabe
        
        changeprofil('profilkontakt', $(this).attr("value"));
    });
    
    
    
    // Holt sich die Daten für die Dialogbox per Ajax.
    function changeprofil(type, val, extra){
        $("#profil-form").attr("extra", extra);
        $("#profil-form").html('<center><img src="typo3conf/ext/dhda/bajax.gif" border="0"></center>');
        var sid = unescape(decodeURI($(document).getUrlParam("sid")));
        //alert('type: ' + type + ' --- ' + 'value: ' + val);
        $.ajax({
            url: "index.php", // Achtung mit RealURL!
            type: "GET", // Daten per GET verschicken
            async: false,
            cache: false,
            data: {
                eID: "dhda", // die erstellte eID
                todo: 'profil',
                type: type,
                value: val,
                sid: sid
            },
            dataType: "json", // das gibts zurück
            // Es hat funktioniert?
            success: function(response){
                // Inhalt in die Dialogbox
                $("#profil-form").html(response);
                // Inhalt verändert sich, daher Neupositionierung der Dialogbox.
                $('#dialog-form').dialog('option', 'position', 'middle');
                // Nach dem Anzeigen erstmal div mit abbrechen/submit ausblenden
                if (type == 'paket_buchen') {
                    //$(".submitButton").attr("disabled", "disabled");
                    $(".submitButton").parent('div').css('display', 'none');
                }
                
                
            },
            // Schade, es war ein Fehler
            error: function(error){
            }
        });
    }
    
    // Bei Klick "abschicken" werden Daten versendet....
    $(".submitButton").live('click', function(){
        // Formular mit gesamten Inhalt an wird versendet.
        // eID usw. als hidden-Felder
        $('#profil-form').ajaxForm(options);
    });
    
    // Keine Änderungen vorgenommen, Dialogbox wird geschlossen.
    $(".resetButton").live('click', function(){
        $("#dialog-form").dialog('close');
        $("#dialog").dialog("destroy");
        $('#color1, #color2, #color3, #color4').ColorPickerHide();
    });
    
    // Prüfung des formulars sollte auch nochmal in der dhda.js sein,
    // showRequest stammt von ajaxform
    function validate(formData, jqForm, options){
        $("#gprofil").validate({
            rules: {
                "email": {
                    required: true,
                    email: true
                },
                "name": "required",
                "tx_erweitertfeuser_vorname": "required",
                "zip": "required",
                "city": "required",
                "telephone": {
                    required: true
                },
                "address": "required",
                "tx_erweitertfeuser_hausnummer": "required"
            },
            messages: {
                "email": {
                    required: " > Bitte eine Emailadresse eingeben",
                    email: " > Bitte eine richtige Emailadresse eingeben"
                },
                "name": {
                    required: " > Bitte Nachnamen angeben"
                },
                "tx_erweitertfeuser_vorname": {
                    required: " > Bitte Vornamen angeben"
                },
                
                "zip": {
                    required: " > Bitte PLZ angeben"
                },
                "city": {
                    required: " > Bitte Ort angegeben"
                },
                "telephone": {
                    required: " > Bitte Telefonnummer angeben"
                },
                "address": {
                    required: " > Bitte Adresse angeben"
                },
                "tx_erweitertfeuser_hausnummer": {
                    required: " > Bitte Ort angegeben"
                }
            }
        });
        
    }
    
    // ajaxForm
    function showResponse(responseText, statusText, xhr, $form){
        $("#dialog-form").dialog('close');
        // Datepicker wird hier immer geschlossen.
        $('.date_drop').datepicker("destroy");
        //unset($_POST'.date_drop']);
        // Seite wird neu geladen, damit Änderungen sichtbar.
        var currentURL = window.location;
        if ($("#profil-form").attr("extra") && currentURL.href != 'https://www.dieheldenderarbeit.de/profil.html') {
            var randomnumber = Math.floor(Math.random() * 100001);
            var newURL = currentURL.href.split("&rnd", 1) + '&rnd=' + randomnumber + '#' + $("#profil-form").attr("extra");
            $('#dialog-form').html("");
            window.location = newURL;
        }
        else {
            $('#dialog-form').html("");
            location.reload(true);
        }
        
        
    }
    
    // Blendet in der Detailansicht die Blöcke ein und aus.
    // toogle effekt (aus und einklappen) + die pfeile.
    // Muss direkt darunter liegen, dürfen keine Elemente dazwischen sein.
    $("#inhalt_gearpro .tx-dhda-pi1 div > img").click(function(){
        $(this).parent('#inhalt_gearpro .tx-dhda-pi1 div').children("#inhalt_gearpro .tx-dhda-pi1 div div").slideToggle("slow");
    });
    
    
    $("#inhalt_gearpro #profil .tx-dhda-pi1 div > b > img").click(function(){
        $(this).parents('#inhalt_gearpro .tx-dhda-pi1 > div').children("#inhalt_gearpro .tx-dhda-pi1 > div > div").slideToggle("slow");
    });
    
    //profil
    $(".profildetail .suchboxkat div.ueberschrift_profil > img").click(function(){
        $(this).parents('div.suchboxkat').children("div:last").slideToggle("slow");
    });
    
    // Pfeile werden geändert, je nach Status.
    $("#inhalt_gearpro .tx-dhda-pi1 div > img").toggle(function(){
        if ($(this).attr('lowSrc').length > 0) 
            $(this).attr('src', $(this).attr('lowSrc'));
    }, function(){
        if ($(this).attr('longDesc').length > 0) 
            $(this).attr('src', $(this).attr('longDesc'));
    });
    
    // Funktionen zum Löschen von Datensätzen.
    function delfile(types, info){
        // a workaround for a flaw in the demo system
        // (http://dev.jqueryui.com/ticket/4375), ignore!
        $("#dialog").dialog("destroy");
        $('.dialog-confirm_' + info).dialog({
            resizable: false,
            height: 140,
            modal: true,
            buttons: {
                'löschen': function(){
                    $.ajax({
                        url: "index.php", // Achtung mit RealURL!
                        type: "POST", // Daten per GET verschicken
                        async: false,
                        cache: false,
                        data: {
                            eID: "dhda", // die erstellte eID
                            todo: 'profil',
                            type: info,
                            file: types
                        },
                        dataType: "json", // das gibts zurück
                        // Es hat funktioniert?
                        success: function(response){
                            // Ruft Funktion zur Ausgabe der Jobliste
                            // zurück
                            // Wird erstmal nicht benötigt. War für die
                            // Entwicklungsphase
                            // $("#sql").html(response);
                            
                            var currentURL = window.location;
                            var randomnumber = Math.floor(Math.random() * 100001);
                            var newURL = currentURL.href.split("&rnd", 1) + '&rnd=' + randomnumber + '#' + info + '1';
                            $('#dialog-form').html("");
                            window.location = newURL;
                                                       
                        },
                        // Schade, es war ein Fehler
                        error: function(error){
                            // alert("Sorry, hat nicht funktioniert");
                        }
                    });
                    $(this).dialog('close');
                },
                'abbrechen': function(){
                    $(this).dialog('close');
                }
            }
        });
    };
    // Ruft das Löschen auf
    $(".dateiliste img,.profilicon span img").live("click", function(){
        var info = $(this).parents('div[id]').attr("id");
        $('.dialog-confirm_' + info).dialog('open');
        // var offset = $('.ui-dialog').offset();
        // $('.ui-dialog').css('top', (10 + offset.top) +'px');
        delfile($(this).attr("class"), info);
    });
    
    // Wieviel vom Profil ausgefüllt ist
    $(function(){
        var Val = $(".progressbar a").attr("name");
        $(".progressbar").progressbar({
            value: Val
        });
        $(".ui-progressbar-value").html("<span style=\"margin: 5px 0px 0px 5px; position: absolute; z-index: 9; float: left; color: #752C25;\">" + $(".progressbar a").attr("title") + "</span>");
    });
    var Datum = new Date();
    // Datepicker wenn class date_drop in inputfeld ist
    $("input.date_drop").live("mouseover", function(){
        $("input.date_drop").live("mousedown", function(){
            $('.date_drop').datepicker({
                changeMonth: true,
                changeYear: true,
                dateFormat: 'dd.mm.yy',
                yearRange: Datum.getFullYear() - 100 + ":" + (Datum.getFullYear() + 10)
            });
            $('.date_drop').attr('readonly', 'readonly');
            $('.date_drop').attr('autocomplete', 'off');
        });
    });
    
    
    
    jQuery(function($){
        $.datepicker.regional['de'] = {
            closeText: 'schließen',
            prevText: '&#x3c;zurück',
            nextText: 'Vor&#x3e;',
            currentText: 'heute',
            monthNames: ['Januar', 'Februar', 'März', 'April', 'Mai', 'Juni', 'Juli', 'August', 'September', 'Oktober', 'November', 'Dezember'],
            monthNamesShort: ['Jan', 'Feb', 'Mär', 'Apr', 'Mai', 'Jun', 'Jul', 'Aug', 'Sep', 'Okt', 'Nov', 'Dez'],
            dayNames: ['Sonntag', 'Montag', 'Dienstag', 'Mittwoch', 'Donnerstag', 'Freitag', 'Samstag'],
            dayNamesShort: ['So', 'Mo', 'Di', 'Mi', 'Do', 'Fr', 'Sa'],
            dayNamesMin: ['So', 'Mo', 'Di', 'Mi', 'Do', 'Fr', 'Sa'],
            weekHeader: 'Wo',
            dateFormat: 'dd.mm.yy',
            firstDay: 1,
            isRTL: false,
            showMonthAfterYear: false,
            yearSuffix: ''
        };
        $.datepicker.setDefaults($.datepicker.regional['de']);
    });
    
    
    $("input[name=bundesweit]").live("click", function(){
        toggleStatus();
    });
    function toggleStatus(){
        if ($('input[name=bundesweit]').is(':checked')) {
            $('input[name=ort3],input[name=ort2],input[name=ort1],select[name=land]').attr('disabled', true);
        }
        else {
            $('input[name=ort3],input[name=ort2],input[name=ort1],select[name=land]').removeAttr('disabled');
        }
    }
    
    
    $("select[name=land]").live("change", function(){
        if ($(this).val() == '54') {
            $('input[name=ort3],input[name=ort2],input[name=ort1]').css("display", 'block');
            $('input[name=ort3ausland],input[name=ort2ausland],input[name=ort1ausland]').css("display", 'none');
        }
        else {
            $('input[name=ort3],input[name=ort2],input[name=ort1]').css("display", 'none');
            $('input[name=ort3ausland],input[name=ort2ausland],input[name=ort1ausland]').css("display", 'block');
            
        }
    });
    
    // Bruno 23.04.2010
    // Blendet Stück/Monate bei Paket buche ein/aus
    /*
     $("select[name=pakettyp]").live("click", function(){
     if ($(this).val() > 0 && $(this).val() < 4) {
     // also Stück
     $(".paketbuchenanzahl, .paketbuchenanzahlflatrate").css('display','block');
     $("#paket_buchen").find('#paketstaffelungid').val('');
     $(".submitButton").attr("disabled", "");
     $("#preisliste").css('display','none');
     } else if ($(this).val() > 3 && $(this).val() < 7){
     // also Flatrate
     $(".paketflatrate").css('display','block');
     $(".paketbuchenanzahl, .paketbuchenanzahlflatrate").css('display','block');
     $(".submitButton").attr("disabled", "disabled");
     $("#preisliste").css('display','none');
     
     } else if ($(this).val() > 6 && $(this).val() < 10){
     $(".submitButton").attr("disabled", "disabled");
     }
     $("#paketdefinition").children('div').each(function(){
     $(this).css('display','none');
     });
     $("#paketinfo" + $(this).val()).css('display','block');
     // Schreibt die aktuelle uid aus dem select
     $("#paketinfo").val($(this).val());
     });*/
    // Klick zum Paket auf Warenkorbsymbol
    $(".paket").live("click", function(){
        $("#zurpreisliste").css('display', 'block');
        var wert = $(this).next('input').val().split(",");
        $(".submitButton").parent('div').css('display', 'block');
        if (wert[0] > 0 && [0] < 4) {
            // also Stück
            $(".paketbuchenanzahl, .paketbuchenanzahlflatrate").css('display', 'block');
            $("#paket_buchen").find('#paketstaffelungid').val('');
            $(".submitButton").attr("disabled", "");
            $("#preisliste").css('display', 'none');
        }
        else 
            if (wert[0] > 3 && wert[0] < 7) {
                $(".paketflatrate").css('display', 'block');
                $(".paketbuchenanzahl, .paketbuchenanzahlflatrate").css('display', 'block');
                $(".submitButton").attr("disabled", "disabled");
                $("#preisliste").css('display', 'none');
                
            }
            else 
                if (wert[0] > 6 && wert[0] < 10) {
                    $(".submitButton").attr("disabled", "disabled");
                }
        $("#paketdefinition").children('div').each(function(){
            $(this).css('display', 'none');
        });
        if (wert[1] > 0) {
            $("#paket_buchen").find('#paketstaffelungid').val(wert[1]);
        }
        //alert($("#paketinfo" + wert).css('display'));
        // Schreibt die aktuelle uid aus dem select
        $("#paketinfo").val(wert[0]);
        $("#paketinfo" + wert[0]).css('display', 'block');
        if (wert[0] > 3 && wert[0] < 7) {
            $(".paketbuchenanzahlflatrate").find("select").val(wert[1]);
        }
        //alert($("#paketinfo" + wert).css('display'));
    });
    
    // Klick zur gesamten Preisliste
    $("#zurpreisliste").live("click", function(){
        $("#preisliste").css('display', 'block');
        $("#zurpreisliste").css('display', 'none');
        $(".paketinfo").css('display', 'none');
        $(".submitButton").attr("disabled", "disabled");
    });
    
    $("#rauf").live("click", function(){
        var wert;
        var einzelpreis;
        wert = $(this).parents('.paketinfo').find("#anzahlpaketehidden").val();
        if (wert < 1000) {
            wert++;
        }
        $(this).parents('.paketinfo').find("#anzahlpaketehidden").val(wert);
        $(this).parents('.paketinfo').find("#anzahlpakete").html('<b>' + wert + '</b>');
        $(this).parents('.paketinfo').find(".paketgesamtpreis").find("span.gesamt").html(gesamtpreis(wert, $(this).parents('.paketinfo').find("#paketuidpreis").val()) + ' &euro;');
    });
    
    $("#runter").live("click", function(){
        var wert;
        wert = $(this).parents('.paketinfo').find("#anzahlpaketehidden").val();
        if (wert > 1) {
            wert--;
        }
        $(this).parents('.paketinfo').find("#anzahlpaketehidden").val(wert);
        $(this).parents('.paketinfo').find("#anzahlpakete").html('<b>' + wert + '</b>');
        $(this).parents('.paketinfo').find(".paketgesamtpreis").find("span.gesamt").html(gesamtpreis(wert, $(this).parents('.paketinfo').find("#paketuidpreis").val()) + ' &euro;');
    });
    
    function gesamtpreis(wert, einzelpreis){
        var gesamtpreis;
        gesamtpreis = (wert * einzelpreis);
        //alert(gesamtpreis);
        return gesamtpreis.toFixed(2);
    }
    
    // Preise Flatrate
    $(".paketbuchenanzahlflatrate a").live("click", function(){
        //$(this).parents('.paketinfo').find(".flatratepreis").html($(this).attr("title"));
        $(this).parents('.paketinfo').find(".flatratepreis").html($(this).attr("title"));
        
        
        //alert($(this).attr("value"));
        //alert($(this).parents('.paketinfo').find("#paketuidpreis").val());
    });
    
    $("select[name=paketstaffelung]").live("click", function(){
        $("#paket_buchen").find('#paketstaffelungid').val($(this).val());
        $(".submitButton").attr("disabled", "");
    });
    //$('input[name=upload]').live('click', function() {

    //});


});
