Server = {

    /**
     * Authentication
     */

    // Enthält Sicherheits-Token, ist false wenn nicht angemeldet.
    token: false,

    // ISO 639-1 Sprach-Kürzel
    lang: 'de',

    // Projekt/Gruppe, der ein Nutzer angehört
    // Wenn 0, dann allgemeine Gruppe
    group: 0,

    // App ID: bestimmt Aussehen und Inhalt
    appId: 'crb',

    getVersion: function(callback) {
        $.ajax({
            url: "app/version.json",
            success: callback
        });
    },

    // User hat die Bedingungen akzeptiert
    approveTerms: function(callback) {
        $.post("app/approveterms.json", {token: Server.token, terms: true}, callback, "json");
    },


    // Soll Logininformationen an Server schicken und als Antwort
    // ein Sicherheits-Token zurückbekommen.
    login: function(form, callback) {
        $(form).ajaxSubmit({
            url: "app/login.json",
            type: "post",
            dataType: "json",
            success: function(response) {
                Server.token = response.status.token;
                callback(response);
            }
        });
    },


    // Schickt Logininformationen aus FirstRun Dialog - sollte alte Files aus altem Viewer importieren
    importFilesWithOldLogin: function(form, callback) {
        $(form).ajaxSubmit({
            url: "app/oldlogin.json",
            type: "post",
            data: { token: Server.token },
            dataType: "json",
            success: function(response) {
                callback(response);
            }
        });
    },


    // Schickt zu importierendes File von der Offerta CD
    importOfferta: function(form, callback) {
        $(form).ajaxSubmit({
            //url: "app/importofferta.php",
            url: "app/importofferta.json",
            type: "post",
            data: { token: Server.token },
            dataType: "json",
            success: function(response) {
                callback(response);
            }
        });
    },


    logout: function() {
        $.post("app/logout.json", {token: Server.token}, null, "json");
    },


    /**
     * File Handling
     */

    // Holt ein JSON-Objekt vom Server, die ID bestimmt die URL
    getFileList: function(callback) {
        jQuery.getJSON("app/file_list.json", {token: Server.token, lang: Server.lang}, callback);
    },

    // Holt Konditionen zu einem SIA451-File
    getConditions: function(id, callback) {
        jQuery.getJSON("app/conditions.json", {id: id, token: Server.token, lang: Server.lang}, callback);
    },

    updateConditions: function(file_id, form, callback) {
        $(form).addToForm({id: file_id, token: Server.token});
        $(form).ajaxSubmit({
            url: "app/update_conditions.json",
            type: "post",
            dataType: "json",
            success: callback
        });
    },

    // Holt ein SIA451-File vom Server
    getFile: function(id, callback) {
					$.get("app/file.json", {id: id, token: Server.token, lang: Server.lang}, function(data, textStatus) {
						callback(JSON.parse(data));
					    }, 'text');
  //      jQuery.getJSON("app/file.json", {id: id, token: Server.token, lang: Server.lang}, callback);
    },

    // Preisarchiv holen
    getArchiveForFile: function(id, percent, callback) {
        jQuery.getJSON("app/archive.json", {id: id, percent:percent, token: Server.token, lang: Server.lang}, callback);
    },

    // Preise bearbeiten (mit Prozentsatz)
    multiplyPrices: function(id, percent, callback) {
        jQuery.getJSON("app/multiply.json", {id: id, token: Server.token, lang: Server.lang, percent: percent}, callback);
    },

    // Speichert Updates eines Files
    pushToArchive: function(fileId, percentage, callback) {
        var data = {
            token: Server.token,
            percent: percentage,
            id:fileId
        };
        $.ajax({
            data:data,
            url: "app/pushToArchive.json",
            type: "post",
            dataType: "json",
            success: callback
        });
    },

    // Download eines SIA451-Templates
    downloadFile: function(form) {
        var data = {
            token: Server.token,
            lang: Server.lang,
            group: Server.group
        };
        $.each($(form).serialize().split("&"), function(i, row) {
            var item = row.split("=");
            data[item[0]] = item[1];
        });
        $.download("app/template_download.json", data);
    },

    // Lädt ein SIA451-File auf den Server
    // Gibt eine neue File-Liste zurück, die das eben hochgeladene File enthält
    uploadFile: function(element_id, onSubmit, onComplete, onChange) {
        new AjaxUpload(element_id, {
            action: 'app/file_upload.json',
            autoSubmit: false,
            data: { token: Server.token },
            responseType: "json",
            onChange: onChange,
            onSubmit: onSubmit,
            onComplete: onComplete
        });
    },
    
    uploadBfs: function(form, onSubmit, onError) {
      form.ajaxSubmit({
  			url : 'app/file_upload.json',
  			method : 'post',
  			dataType : 'json',
  			data: { token: Server.token },
  			success: onSubmit,
  			error: onError
  		});
    },
    

    // Speichert Updates von Teilen eines Files
    archiveFileElement: function(data, callback) {
        data.token = Server.token;
        $.ajax({
            type: "POST",
            scriptCharset: "utf-8",
            contentType: "application/x-www-form-urlencoded; charset=utf-8",
            url: "app/archiveFileElement.json",
            data: data,
            success: callback,
            dataType: "json"
        });
    },

    // Speichert Updates von Teilen eines Files
    updateFileElement: function(data, callback) {
        data.token = Server.token;
        $.ajax({
            type: "POST",
            scriptCharset: "utf-8",
            contentType: "application/x-www-form-urlencoded; charset=utf-8",
            url: "app/updateFileElement.json",
            data: data,
            success: callback,
            dataType: "json"
        });
    },

    /**
     * Exportiert Datei mit <id>
     * Export startet durch setzen des HTML-Headers und sollte somit
     * direkt vom Browser gehandhabt werden.
     * Format:
     *   "01s": SIA-Originalformat
     *   "pdf": PDF-Export
     */
    exportFile: function(id, format, firma, bearbeiter, telefon, email) {
        $.download("app/file_export.json", {
            token: Server.token,
            lang: Server.lang,
            id: id,
            format: format,
            firma: firma,
            bearbeiter: bearbeiter,
            telefon: telefon,
            email: email
        });
    },

    // Speichert Updates eines Files
    updateFile: function(form, callback) {
        $(form).addToForm({token: Server.token});
        $(form).ajaxSubmit({
            url: "app/update_file.json",
            type: "post",
            dataType: "json",
            success: callback
        });
    },

    // Veröffentlicht ein File
    publishFile: function(file_id, email_confirmation, form, callback) {
        var data = {
            token: Server.token,
            file_id: file_id,
            email_confirmation: email_confirmation
        };
        $.each($(form).serialize().split("&"), function(i, row) {
            var item = row.split("=");
            data[item[0]] = item[1];
        });
        $.post("app/publish_file.json", data, callback, "json");
    },


    // Löscht ein File
    deleteFile: function(file_id, callback) {
        $.post("app/delete_file.json", {token: Server.token, file_id: file_id}, callback, "json");
    },

    // File umbenennen
    renameFile: function(file_id, new_name, callback) {
        $.post("app/rename_file.json", {token: Server.token, file_id: file_id, new_name: new_name}, callback, "json");
    },

    // File duplizieren
    duplicateFile: function(file_id, callback) {
        $.post("app/duplicate_file.json", {token: Server.token, file_id: file_id}, callback, "json");
    },

    // File verschieben
    moveFile: function(file_id, folder_id, callback) {
        $.post("app/move_file.json", {token: Server.token, file_id: file_id, folder_id: folder_id}, callback, "json");
    },

    // Ordner anlegen
    createFolder: function(folder_name, callback) {
        $.post("app/create_folder.json", {token: Server.token, folder_name: folder_name}, callback, "json");
    },

    // Ordner löschen
    deleteFolder: function(folder_id, callback) {
        $.post("app/delete_folder.json", {token: Server.token, folder_id: folder_id}, callback, "json");
    },

    // Ordner umbenennen
    renameFolder: function(folder_id, new_name, callback) {
        $.post("app/rename_folder.json", {token: Server.token, folder_id: folder_id, new_name: new_name}, callback, "json");
    },

    // Ordner verschieben/sortieren
    moveFolder: function(folder_id, position, callback) {
        $.post("app/move_folder.json", {token: Server.token, folder_id: folder_id, position: position}, callback, "json");
    },



    /**
     * Profil
     */

    // Lade eigenes Profil
    getProfile: function(callback) {
        jQuery.ajax({
            url:"app/profile.json",
            type:'post',
            data:{token: Server.token},
            success:callback,
            dataType:"json"
        });
    },

    // Registrieren und Profil erstellen
    // Soll nach erstellen gleich angemeldet werden
    createProfile: function(form, callback) {
        $(form).ajaxSubmit({
            scriptCharset: "utf-8",
            contentType: "application/x-www-form-urlencoded; charset=utf-8",
            url: "app/create_profile.json",
            type: "post",
            data:{appId: Server.appId},
            dataType: "json",
            success: callback
        });
    },

    // Speichere Updates an eigenem Profil
    updateProfile: function(form, callback) {
        $(form).addToForm({token: Server.token});
        $(form).ajaxSubmit({
            scriptCharset: "utf-8",
            contentType: "application/x-www-form-urlencoded; charset=utf-8",
            url: "app/update_profile.json",
            type: "post",
            dataType: "json",
            success: callback
        });
    },


    /**
     * BFS Formular
     */

    // Liefert Status zurück, ob Datei eingereicht oder nicht.
    getBFSStatus: function(callback) {
        $.getJSON("app/bfs_status.json", {token: Server.token}, callback);
    },

    // Holt Daten des BFS-Umfrageformulars
    getBFSForm: function(callback, file_id) {
        var data = {token: Server.token};
        if (file_id) data["file_id"] = file_id;
        $.getJSON("app/bfs_form.json", data, callback);
    },

    // Speichert Daten des BFS-Umfrageformulars (einzelne Elemente)
    saveBFSFormElement: function(id, value, callback) {
        var data = {
            token: Server.token,
            id: id,
            value: value
        };
        $.post("app/update_bfs_form.json", data, null, callback);
    },

    saveBFSForm: function(form, callback) {
        $(form).addToForm({token: Server.token});
        $(form).ajaxSubmit({
            url: "app/update_bfs_form.json",
            type: "post",
            dataType: "json",
            success: callback
        });
    },

    /**
     * Adressen
     */

    // Hole Liste an verfügbaren Adressen
    getAddressList: function(callback) {
        jQuery.getJSON("app/address_list.json", {token: Server.token}, callback);
    },

    // Erstelle eine neue Adresse
    // Liefere die ganze, aktualisierte Liste an Adressen als JSON zurück,
    // damit die bestehende dadurch ersetzt werden kann.
    createAddress: function(form, callback) {
        $(form).addToForm({token: Server.token});
        $(form).ajaxSubmit({
            url: "app/address_list.json",
            type: "post",
            dataType: "json",
            success: callback
        });
    },

    // Speichere Updates an einer Adresse
    // Liefere die ganze, aktualisierte Liste an Adressen als JSON zurück,
    // damit die bestehende dadurch ersetzt werden kann.
    updateAddress: function(form, callback) {
        $(form).addToForm({token: Server.token});
        $(form).ajaxSubmit({
            url: "app/update_address.json",
            type: "post",
            dataType: "json",
            success: callback
        });
    }
};
