var WechselwelleContainer = (function () {
    // Definiere eine Funktion mit einem Funktionsausdruck,
    // durch runde Klammern umschlossen

    function ajaxFileUpload(action, fileElementId, uploadField)
    {
//        alert(action);
        //starting setting some animation when the ajax starts and completes
        //  $("#loading")
        //  .ajaxStart(function(){
        //      $(this).show();
        //  })
        //  .ajaxComplete(function(){
        //      $(this).hide();
        //  });
        $.ajaxFileUpload
        (
        {
            url: action, 
            secureuri:false,
            fileElementId: fileElementId,
            dataType: 'json',
            success: function (data)
            {
                switch(data.status) {
                    case 'failed':
                        $('#fancybox-content .hint').html(data.message);
                        break;
                    case 'success':
                        var getImage = $(uploadField).attr('src');
                        getImage = getImage.substring(0, getImage.lastIndexOf("/")+1);
                        $(uploadField).attr('src',getImage+data.file);
                        $.fancybox.close();
                        break;
                }

            },
            error: function (data, status, e)
            {
                alert(e);
            }
        }
        )
    
        return false;
    }
    
    // pre-submit callback 
    function showRequest(formData, jqForm, options) {
        // formData is an array; here we use $.param to convert it to a string to display it 
        // but the form plugin does this for you automatically when it submits the data 
        var queryString = $.param(formData);
        blockElements();
 
        // jqForm is a jQuery object encapsulating the form element.  To access the 
        // DOM element for the form do this: 
        // var formElement = jqForm[0]; 
 
        //alert('About to submit: \n\n' + queryString); 
 
        // here we could return false to prevent the form from being submitted; 
        // returning anything other than false will allow the form submit to continue 
        return true; 
    } 
 
    // post-submit callback 
    function showResponse(responseText, statusText, xhr, form)  { 
        // for normal html responses, the first argument to the success callback 
        // is the XMLHttpRequest object's responseText property 
 
        // if the ajaxForm method was passed an Options Object with the dataType 
        // property set to 'xml' then the first argument to the success callback 
        // is the XMLHttpRequest object's responseXML property 
 
        // if the ajaxForm method was passed an Options Object with the dataType 
        // property set to 'json' then the first argument to the success callback 
        // is the json data object returned by the server 
        switch(responseText.type) {
            case 'thickbox':
                $('#fancybox-content .error').addClass('inv');
                $('#fancybox-content .formError').removeClass('formError');
                $('#fancybox-content .error').html('<!-- error -->');
                switch(responseText.status){
                    case 'success':
                        $('#fancybox-content ' + responseText.updateItem).html(responseText.message);  
                        break;
                                                
                    case 'failed':
                        $.each(responseText.errorFieldList, function() {
                        $('#fancybox-content [name="'+ this.item +'"]').addClass('formError');
                        if($('#fancybox-content .error').html() == '<!-- error -->') {
                            $('#fancybox-content .error').html(this.message);
                        } else {
                            $('#fancybox-content .error').append('<br />', this.message);  
                        }
                        $('#fancybox-content .error').removeClass('inv');
                                                    
                    });

                    break;
                }
                break;
                            
            case 'both':
                switch(responseText.status){
                case 'success':
                    openLightbox(responseText.url,responseText.title);
                    if(responseText.norender == 'yes') {
                    } else{
                        $('#contentwrapper').html(responseText.message);
                    }
                    unblockElements();
                    break;
                                                
                case 'failed':
                    $(responseText.parentElement+' .hint').html('Orange gekennzeichnete Felder sind Pflichtfelder.'); 
                    $(responseText.parentElement+' .required').removeClass('required');
                    $.each(responseText.errorFieldList, function() {
                        $(responseText.parentElement +' [name="'+ this.item +'"]').addClass('required');
                        if($(responseText.parentElement+' .hint').html() == 'Orange gekennzeichnete Felder sind Pflichtfelder.') {
                            $(responseText.parentElement+' .hint').html(this.message);    
                        } else {
                            $(responseText.parentElement+' .hint').append('<br />', this.message);  
                        } 
                    });
                    unblockElements();
                    break;                              
            }    
            break;
            case 'newthick':
                switch(responseText.status){
                case 'success':
                    openLightbox(responseText.url,responseText.title,448);
                    unblockElements();
                    break;
                                        
                case 'failed':
                    $('.hint').html('Orange gekennzeichnete Felder sind Pflichtfelder.'); 
                    $(responseText.parentElement + '.required').removeClass('required');
                    $.each(responseText.errorFieldList, function() {
                        $(responseText.parentElement +' [name="'+ this.item +'"]').addClass('required');
                        if($('.hint').html() == 'Orange gekennzeichnete Felder sind Pflichtfelder.') {
                            $('.hint').html(this.message);    
                        } else {
                            $('.hint').append('<br />', this.message);  
                        } 
                    });
                    unblockElements();
                    break;                              
            }    
            break;
                            
            case 'FormByLink':
                switch(responseText.status){
                case 'success':
                    $(responseText.parentElement + ' .hint').html(responseText.message); 
                    unblockElements();
                    break;
                                                
                case 'failed':
                    $(responseText.parentElement + ' .required').removeClass('required');
                    $(responseText.parentElement + ' .hint').html('Orange gekennzeichnete Felder sind Pflichtfelder.');
                    $.each(responseText.errorFieldList, function() {
                        $(responseText.parentElement + ' [name="'+ this.item +'"]').addClass('required');
                        if($(responseText.parentElement + ' .hint').html() == 'Orange gekennzeichnete Felder sind Pflichtfelder.') {
                            $(responseText.parentElement + ' .hint').html(this.message);    
                        } else {
                            $(responseText.parentElement + ' .hint').append('<br />', this.message);  
                        }
                                                    
                    });
                    unblockElements();
                    break;
            }
            break;

            case 'forward':
                switch(responseText.status){
                case 'success':
                    $('#contentwrapper').html(responseText.message);
                    rerenderContent('#topnav', responseText.addcontent );
                    unblockElements();
                    break;
                                                
                case 'failed':
                    $(responseText.parentElement + ' .required').removeClass('required');
                    $(responseText.parentElement + ' .hint').html('Orange gekennzeichnete Felder sind Pflichtfelder.');
                    $.each(responseText.errorFieldList, function() {
                        $(responseText.parentElement + ' [name="'+ this.item +'"]').addClass('required');
                        if(this.message != '') {
                            if($(responseText.parentElement + ' .hint').html() == 'Orange gekennzeichnete Felder sind Pflichtfelder.') {
                                $(responseText.parentElement + ' .hint').html(this.message);    
                            } else {
                                $(responseText.parentElement + ' .hint').append('<br />', this.message);  
                            }
                        }
                                                    
                    });
                    break;
            }
            break;
            case 'forwardlogout':
                switch(responseText.status){
                case 'success':
                    $('#contentwrapper').html(responseText.message);
                    rerenderContent('#topnav', responseText.addcontent );
                    unblockElements();
                    break;
                                
                case 'failed':
                    break;
            }
            break;

            default:
                if (responseText.status == 'failed'){
                    $('.hint').html(responseText.message);
                }else {
                    $('#contentwrapper').html(responseText.message);
                }
                                        
        }
        unblockElements();

    //    alert('status: ' + statusText + '\n\nresponseText: \n' + responseText + 
    //        '\n\nThe output div should have already been updated with the responseText.'); 
    } 

    function cycleContent() {
        $('#testimonials').cycle({ 
            fx:     'scrollLeft',
            speed:   800, 
            timeout: 6000, 
            pause:   1,
            cleartypeNoBg: true,
            random: true
        
        });    
        
        $('.partner').cycle({ 
            fx:     'scrollLeft',
            speed:   800, 
            timeout: 6000, 
            pause:   1,
            cleartypeNoBg: true
        });
    }
    function subNav() {
        $('a.aclick').live('click', function() {
            var target = $(this).attr('href');
            $("#footer a."+target).click();
            boxClose();
            return false;
        })
    }
    
    function thickbox() {
        $('a.thickbox').fancybox({
            'titlePosition'  : 'inside',
            'type'           : 'ajax',
            'autoDimensions' : false,
            'showCloseButton': true,
            'padding'        : 30
        });
        return false;
    }
    
    function toggleLegend() {
        $('#legend a').click(function() {
            if ( $('#legend li').hasClass('active') ) {
                $('#legend li').removeClass('active');
                $('#legend li a').text('Legende einblenden');
            }else {
                $('#legend li').addClass('active');
                $('#legend li a').text('Legende ausblenden');
            }
        })
    }
    

    function blockElements() {
        $('#contentwrapper').block({ 
            message: '<img src="../images/ajax-loader.gif" alt="bitte warten" />', 
            overlayCSS: {
                backgroundColor: '#fff'
            },
            css: {
                border: 'none'
            }
        });
    }
    
    function unblockElements() {
        $('#contentwrapper').unblock();
        //reinit some functions after ajax calls
        placeHolder();
        toolTip();
        toggleTeamOptions ();
    }
    
    function rerenderContent(el, co) {
        $(el).html(co);
    }
    
    function toggleTeamOptions (){
        $("input[name='toggleTeam']").change(function() {
            whereToGo = $(this).val();
            $("#teamgo a."+whereToGo).click();
            $('#topnav ul li.tabtwo').addClass('active');
        });
    }
    
    function toolTip() {
        $('a.addinfo').each(function(index) {
            $(this).attr('title',$(this).attr('rel'));
        });
        $("a.addinfo").tooltip({ 
            track: true, 
            showURL: false,
            showBody: " -- "
        }); 
    }
    
    function runActivated() {
        //$('.clearField').clearField();
        if ( $("#activated").size() ){
            openLightbox('profil/activated','Registrierung bestätigt!');
        }
    }
    
    function boxClose() {
        $("body").delegate("a.boxclose", "click", function(event) {
            $.fancybox.close();
        });
    }
    
    function clickButtons() {
        $("body").delegate("div.buttonwrap", "click", function(event) {
            $('input',this).submit();
        });
    }
    
    function infoboxClose() {
        $("#mapinfoboxwrapper a.close").click(function() {
            $("#mapinfoboxwrapper").hide();
        });
    }
    
    function uploadFile() {
        $("body").delegate("#file_upload_form", "submit", function(event) {
            action = $(this).attr('action');
            ajaxFileUpload(action, 'person_photo', '#profile_photo');
            return false;
        });

        $("body").delegate("#team_upload_form", "submit", function(event) {
            action = $(this).attr('action');
            ajaxFileUpload(action, 'team_upload_photo', '#team_photo');
            return false;
        });        
    }
    

    
    function placeHolder() {
        $('input[placeholder], textarea[placeholder]').placeholder();
    }
    //handle forms
    function submitForms() {
        $("body").delegate("form.asubmit", "submit", function(event) {
            // to logic here
            var formName = $(this).attr('id');
            var whereToGo = $(this).attr('action');
            var whatToUpdate = $("input.nextpage", this).val();
            var howToUpdate = $("input.resultlayout", this).val();
            
            //              alert(whatToUpdate);
            $(this).ajaxSubmit({
                // target :        whatToUpdate,   // target element(s) to be updated with server response 
                beforeSubmit :  showRequest,  // pre-submit callback 
                success :       showResponse,  // post-submit callback 
                type : 'post',
                url : whereToGo,
                dataType: 'json'
            });
            return false;
        });
    }
    
    /*
     * Used for password recovery
     **/
    function sendFormByLink() {
        $("body").delegate("a.sendForm", "click", function(event) {       
            var url = $(this).attr('href');
            var form = $(this).parents('form:first'); 
 
            $(form).ajaxSubmit({
                beforeSubmit :  showRequest,  // pre-submit callback 
                success :       showResponse,  // post-submit callback 
                type : 'post',
                url : url,
                dataType: 'json'
            });
            return false;
        });
    }
    
    //ajax link handling
    function ajaxLinks() {
        $('a.ajax').live('click', function() {
            //jason ja nein
            var target= $(this).attr('href');
            var parent = $(this).parent('li');
        
            //
            blockElements();
            $('#topnav li').removeClass('active');
            if ($(this).hasClass('tabone')){
                $("#topnav ul li.tabone").addClass('active');
            }
            if ($(this).hasClass('tabtwo')){
                $("#topnav ul li.tabtwo").addClass('active');
            }
        
            if ($(this).hasClass('tabthree')){
                $("#topnav ul li.tabthree").addClass('active');
            }
        
            $.ajax({
                url: target,
                global: false,
                type: "POST",
                'dataType': "html",
                success: function(result){                      
                    $('#contentwrapper').html(result);
                    parent.addClass('active');
                    unblockElements();
                    $.fancybox.close();
                    goToByScroll('contenta');
                }                
            });
            return false;  
        })
    }
    
    function ajaxThickboxLinks() {
        $('a.ajaxThickbox').live('click', function() {
            //jason ja nein
            var target= $(this).attr('href');
            var parent = $(this).parent('li');
        
        
            $.ajax({
                url: target,
                global: false,
                type: "POST",
                'dataType': "html",
                success: function(result){                      
                    $('#fancybox-content').html(result);
                    parent.addClass('active');
                }                
            });
            return false;  
        })
    }
    
    //ajax link handling
    function ajaxLinksJson() {
        $('a.ajaxjson').live('click', function() {
            //jason ja nein
            var target= $(this).attr('href');
            var parent = $(this).parent('li');
            //
            blockElements();
            // $('#topnav li').removeClass('active');
        
            $.ajax({
                url: target,
                global: false,
                type: "POST",
                'dataType': "json",
                success: showResponse
            });
            return false;  
        })
    }
    
    // return public interface
    return {
        // public attributes
        öffentlicheEigenschaft : "öffentlich",
        // public methods
        oeffentlicheMethode1 : function() {
        // alert("öffentlicheMethode1 wurde aufgerufen");
        }, 
        // return string void
        init : function (){
            cycleContent();
            toggleLegend();
            subNav();
            ajaxLinks();
            ajaxLinksJson();
            ajaxThickboxLinks();
            thickbox();
            submitForms();
            sendFormByLink();
            boxClose();
            runActivated()
            placeHolder();
            uploadFile();
            toolTip();
            infoboxClose();
            clickButtons();
            toggleTeamOptions();
            ajaxLinksJson()
        }
    };
})();

$(document).ready(function() {
    WechselwelleContainer.init();
//alert(domain);
    $("#power_provider").autocomplete("register/querypower");
    $("#gas_provider").autocomplete("register/querygas");
});

function toggleCompany (){

    if ( $("div.iscompany").hasClass('inv') ) {
        $("div.iscompany").removeClass('inv');
        $("#company_name").attr("disabled", false);
        $("#tip-company").removeClass('inv');
        $("#tip-person").addClass('inv');
    } else {
        $("div.iscompany").addClass('inv');
        $("#company_name").attr("disabled", true);
        $("#tip-person").removeClass('inv');
        $("#tip-company").addClass('inv');
    };
}

function goToByScroll(id){
    $('html,body').animate({
        scrollTop: $("#"+id).offset().top
        },'slow');
}
