/**
 * JavaScript Form-Helper
 *
 * based on: Prototype 1.6
 * 
 * (c) 2008 by ServiceHome <http://www.servicehome.net>
 */

var form_helper = Class.create({
    initialize: function (id, name, action, method, enctype) {
        this.id = id;
        this.name = name;
        this.action = action;
        this.method = method;
        this.enctype = enctype;
        this.target = "";
        this.fields = "";
        
        this.dom_fields = new Array();
    },
  
    set_target: function (target) {
        this.target = target;
        
    },
  
    add_input_field: function(definition_string)  {
        var data_ar = definition_string.split("|");
        var count = data_ar.length;
        this.fields += '<input name="'+data_ar[1]+'" type="'+data_ar[0]+'" value="'+data_ar[2]+'"';
        if (count > 3) {
            this.fields += ' ' + data_ar[3];
        }
        this.fields += '>' + "\n";
        
        var field_dom = null;
        // DOM PART
        /*if (Prototype.Browser.IE) {
            field_dom = document.createElement('input name="'+data_ar[1]+'" type="'+data_ar[0]+'" id="'+data_ar[1]+'" value="'+data_ar[2]+'"');
        } else {
            field_dom = document.createElement("input");
            field_dom.setAttribute("name", data_ar[1]);
            field_dom.setAttribute("type", data_ar[0]);
            field_dom.setAttribute("id", data_ar[1]);
            field_dom.setAttribute("value", data_ar[2]);
        }*/
        field_dom = new Element('input', {
            'name': data_ar[1],
            'type': data_ar[0],
            'id': data_ar[1],
            'value': data_ar[2]
            });
        

        this.dom_fields.push(field_dom);
    },
    
    getInputFieldHtml: function (definition_string) {
        var data_ar = definition_string.split("|");
        var count = data_ar.length;
        var text = '<input type="'+data_ar[0]+'" name="'+data_ar[1]+'" value="'+data_ar[2]+'"';
        if (count > 3) {
            text += ' ' + data_ar[3];
        }
        text += '>';
        return(text);      
    },
    
    getInputFieldDOM: function (definition_string) {
        var data_ar = definition_string.split("|");
        var count = data_ar.length;
        
        var input_field = document.createElement("input");
        input_field.setAttribute("type", data_ar[0]);
        input_field.setAttribute("name", data_ar[1]);
        input_field.setAttribute("value", data_ar[2]);
        if (count > 3) {
        // geht nit
        }
        
        return(input_field);
    },
  
    add_submit_field: function () {
        this.fields += '<br/>';
        //this.add_input_field('submit|abs|Hochladen|disabled="disabled" id="uplbt" onclick="showWaitGif(\'error\'); ce_setBoxBlockState(false);"');
        
        var input = document.createElement("input");
        input.type = "submit";
        input.name = "abs";
        input.value = "Hochladen";
        input.disabled = "disabled";
        input.id = "uplbt";
        
        this.dom_fields.push(input);
    },
  
    clear: function() {
        this.id = "";
        this.name = "";
        this.action = "";
        this.method = "";
        this.enctype = "";
        this.fields = "";
    },
  
    print: function() {
        return("id=" + this.id + "\nname=" + this.name + "\naction=" + this.action + "\nmethod=" + this.method + "\nenctype=" + this.enctype);
    },
  
    create: function() {
        var html_output = "";
        html_output += this._get_form() + "\n";
        html_output += this._get_fields(); //  this.fields;
        html_output += '</form>';
      
        return(html_output);
    },
    
    createDom: function() {
        var _form = document.createElement("form");
        _form.setAttribute("id", this.id);
        _form.setAttribute("name", this.name);
        _form.setAttribute("action", this.action);
        _form.setAttribute("method", this.method);
        _form.setAttribute("enctype", this.enctype);
        _form.style.textAlign = "left";

        _form.target = "testiframe";

        for (i=0; i < this.dom_fields.length; i++){
            _form.appendChild(this.dom_fields[i]);
        }

        var _cover = new Element("div", { 
            'id': 'form_border'
        });
        _cover.appendChild(_form);
        
        return(_cover);
    },
    
    registerEvents: function () {
        
    },
    
    
    
    _get_form: function () {
        var target = (this.target != "" ? ' target="' + this.target + '"' : "");
        var form_tag = '<form onsubmit="return ce_submit_check();" id="'+this.id+'" name="'+this.name+'" action="'+this.action+'" method="'+this.method+'" enctype="'+this.enctype+'"' + target + '>';
        return(form_tag);
    },
  
    _get_fields: function () {
        return(this.fields);
    }
});

//////////////////////
//var W3CDOM = (document.createElement && document.getElementsByTagName);

//function initFileUploads() {
//    if (!W3CDOM) return;
//    var fakeFileUpload = document.createElement('div');
//    fakeFileUpload.className = 'fakefile';
//    fakeFileUpload.appendChild(document.createElement('input'));
//    var image = document.createElement('img');
//    image.src='http://agandotest.de/templates/agando/img/icon_doppelpfeil.gif';
//    fakeFileUpload.appendChild(image);
//
//    var x = document.getElementsByTagName('input');
//    for (var i=0;i<x.length;i++) {
//        if (x[i].type != 'file') continue;
//        if (x[i].parentNode.className != 'fileinputs') continue;
//        x[i].className = 'file hidden';
//        var clone = fakeFileUpload.cloneNode(true);
//        x[i].parentNode.appendChild(clone);
//        x[i].relatedElement = clone.getElementsByTagName('input')[0];
//        x[i].onchange = x[i].onmouseout = function () {
//            this.relatedElement.value = this.value;
//        }
//        //x[i].onselect = function () {	this.relatedElement.select(); }
//    }
//}
//////////////////////
//function ce_prepare_upload() {
//    
//}

/*var action = '/ajax_ce_upload.php';
var demo = new form_helper("ce_upld", "ce_upld", action, "post", "multipart/form-data");
demo.set_target("testiframe");
var form_exists = false;
 */

function createForm(form_helper_ref) {
    form_helper_ref.add_input_field('hidden|action|upload'); // type name value param
    form_helper_ref.add_input_field('hidden|field|myfile'); // type name value param
    // append info from designer
    var editor_count = designer.getEditorCount();
    var counter = 0;
    for (counter = 0; counter < editor_count; counter++) {
        var current_editor = designer.getEditorByIndex(counter);
        form_helper_ref.add_input_field('hidden|w' + counter + '|' + current_editor.destination_w);
        form_helper_ref.add_input_field('hidden|h' + counter + '|' + current_editor.destination_h);
   
        var viewport_dim = current_editor.getViewportDimension();
        form_helper_ref.add_input_field('hidden|editor_width_'+counter+'|'+ viewport_dim[0]);
        form_helper_ref.add_input_field('hidden|editor_height_'+counter+'|' + viewport_dim[1]);
    }
    form_helper_ref.add_input_field('hidden|count|' + editor_count);
    // -->
    form_helper_ref.add_input_field('file|myfile[]| | class="file" id="filefield" style="font-size: 11px;"');
    form_helper_ref.add_submit_field();

    form_exists = true;
}

function setUploadbuttonState() {
    var button = $('uplbt');
    
    if ($('cbaccept').checked) {
        button.disabled = false;
        //        Event.observe($('uplbt'), "click", function() {
        //            showWaitGif("error");
        //        });
        Event.observe($('ce_upld'), "submit", function () {
            ce_submit_check();
            //if (result) showWaitGif("error");
            showWaitGif("error");
        });
    }else {
        button.disabled = true;
    //        Event.stopObserving($('uplbt'), "click", function() {
    //            showWaitGif("error");
    //        });
    //        Event.stopObserving($('ce_upld'), "submit", function () {
    //            showWaitGif("error");
    //        });
    }
}

function toggleAcceptState() {
    var cb = $('cbaccept');
    if (cb.checked) {
        cb.checked = false;
    }else {
        cb.checked = true;
    }
    
    setUploadbuttonState();
}

//function ce_close_upload() {
//    ce_setBoxBlockState(false);
//    ce_setBoxContentFromDiv("ce_help_default");
//}

//function displayUploadForm() {
//    if (!form_exists) createForm();
//    
//    var error_div = '<div id="error" style="color: #FF0000; font-weight: bold;"></div>';
//    var form = demo._get_form();
//    var fields = demo._get_fields();
//    fields = error_div + '<input type="checkbox" id="cbaccept" value="ok" onclick="setUploadbuttonState();" /> <small style="font-weight: bold;">Ich habe die Upload-Bedingungen gelesen und akzeptiere diese!</small><br>' + fields;
//    var message = '<h3>Laden Sie ihre eigenen Bilder hoch:</h3>';
//    var submessage = $('ce_help_upload').innerHTML;
//    var close_link = ''; //<a onclick="ce_close_upload();"><div style="text-align: right; font-size: 0.8em;">Upload-Box schliessen...</div></a>';
//    
//    
//    var html = '<div>' + message + submessage + form + fields + '</form>' + close_link + '</div>';
//    //var html = form + submessage + '</form>';
//    ce_setBoxContent(html);
//    ce_setBoxBlockState(true);
//}

function getUploadForm() {
    if (!form_exists) createForm();
    
    var error_div = '<div id="error" style="color: #FF0000; font-weight: bold;"></div>';
    var form = demo._get_form();
    var fields = demo._get_fields();
    fields = error_div + '<input type="checkbox" id="cbaccept" value="ok" onclick="setUploadbuttonState();" /> <small style="font-weight: bold;">Ich habe die Upload-Bedingungen gelesen und akzeptiere diese!</small><br>' + fields;
    var message = '<h3>Laden Sie ihre eigenen Bilder hoch:</h3>';
    var submessage = $('ce_help_upload').innerHTML;
    var close_link = '<a onclick="ce_close_upload();"><div style="text-align: right; font-size: 0.8em;">Upload-Box schliessen...</div></a>';
    
    
    var html = '<div>' + message + submessage + form + fields + '</form>' + close_link + '</div>';
    //var html = form + submessage + '</form>';
    
    if ($('ce_upload_form2') == null) {
        var upload_div = document.createElement("div");
        upload_div.setAttribute("id", "ce_upload_form2");
        upload_div.style.display = "none";
            
        upload_div.innerHTML = html;
        
        $('ce_help_container').appendChild(upload_div);
    }
    
    
    return(html);
}

function ce_submit_check() {
    if (true) return true;
    // XXX
    var upload = $('filefield');
    var value = upload.value;
   
    if (value == "") {
        alert("Bitte wï¿½hlen Sie eine JPG Datei aus.");
        return(false);
    }
   
    // check ext
    var ext = ce_get_fileext(value);
    ext = ext.toLowerCase();
   
    if (ext == "") {
        alert("Kann Dateiformat nicht feststellen!");
        return(false);
    }
   
    if (ext != "jpg" && ext != "jpeg" && ext != "gif" && ext != "gif" && ext != "png") {
        alert("Nicht unterstï¿½tztes Dateiformat. Nur Jpeg, GIF und PNG. (" + ext + ")");
        return(false);
    }
   
    if ($('cbaccept').checked != true) {
        alert("Sie mï¿½ssen den Upload-Bedingungen zustimmen!");
        return(false);
    }

    return(true);
}

function ce_get_fileext(filename) {
    var ext_regex = /\.([a-zA-Z]+)$/;
    var ext = ext_regex.exec(filename);

    var result = (ext != null) ? ext[1] : "";
    return(result);
}

//document.observe("dom:loaded", function() {
//ce_setBoxContent(demo.create());
//initFileUploads();
//});


