/**
 * Modul for cesar gadget code generation
 * joose.js is required - http://code.google.com/p/joose-js
 * json2.js is required - http://json.org/json2.js
 */
JooseClass("Validate", {
	methods: {
		isEmpty: function(item) {
			return (item == undefined || item == '' || item == null) ? true : false;
		},
		errorMessage: function(msg, type) {
			this.resetMessage();		
			return '<strong><span class="' + type + '">' + msg + '</span></strong>';
		},
		resetMessage: function(){
			$('msg').innerHTML = '';
		} 
	}
});

Module("Gadget", function (gad) {
	
	JooseClass("Unicode", {
        has: {
            unicode: {
                is: "ro",
                init: function () { return {"\u00e4" : "ae", "\u00c4" : "ae", "\u00fc" : "ue", "\u00dc" : "ue",
                       						"\u00f6" : "oe", "\u00d6" : "oe", "\u00df" : "ss"}}
            },
            htmlentities: {
                is: "ro",
                init: function () { return {"\u00e4" : "&auml;", "\u00c4" : "&Auml;",
                       						"\u00fc" : "&uuml;", "\u00dc" : "&Uuml;",
                       						"\u00f6" : "&ouml;", "\u00d6" : "&Ouml;",
                       						"\u00df" : "&szlig;"}}
            }
        },
        methods: {
            replaceUmlauts: function(item) {
				for(uc in this.getUnicode()) {
					var search = new RegExp(uc, "g");
					if(item.match(search)) {
						return item.replace(search, this.getUnicode()[uc]);
					}
				}
                return item;
            },
            convertUmlautsToHTMLEntities: function(item) {
				for(uml in this.getHtmlentities()) {
					var search = new RegExp(uml, "g");
					if(item.match(search)) {
						return item.replace(search, this.getHtmlentities()[uml]);
					}
				}
                return item;
            }
        }
    })

    JooseClass("Generator", {
        isa: gad.Unicode,
        has: {
			message: {is: "rw"},
            code: {is: "rw", init: $('code')},
            form: {is: "rw", init: $('generate')},
            size: {is: "rw", init: $('size')},
            link: {is: "rw", init: $('link')},
            hash: {is: "rw", init: $('hash')},
            url: {is: "ro", init: "http://www.cesar.de"},
			linksLink: {is: "rw", init: function() { return [] }},
            linksShow: {is: "rw", init: function() { return [] }},
			requiredFields: {is: "ro", init: function() { return ['size', 'link', 'code']}},
			setNull: {is: "ro", init: function() { return ['text','select-one', 'textarea']}},
			validate: {is: "ro", init: function() { return new Validate() }},
			error: {is: "rw", init: false}
        },		
        methods: {
            generateCode: function() {
                var links = this.getLink().value.split('_');
				var tmpLink = [], tmpShow = [];
				
                for(i=0;i<links.length;i += 1) {
                    tmpLink.push(this.replaceUmlauts(links[i]));
                    tmpShow.push(this.convertUmlautsToHTMLEntities(links[i]));
                }
				
				var valid = this.getValidate(); 
				if(valid.isEmpty(this.getSize().value) || valid.isEmpty(this.getLink().value)) {
					this.generateCodeError(valid);
					return;
				}
				this.setLinksLink(tmpLink);
				this.setLinksShow(tmpShow);
				this.saveGadget();
				return;
            },
			generateCodeError: function(valid) {
				var msg = 'Bitte w&auml;hlen Sie eine Gr&ouml;&szlig;e und eine Branche aus.';
				$('msg').innerHTML = valid.errorMessage(msg, 'error'); 
				
				return;
			},
            HTML: function() {
                var html = '';
                html  = "<!-- BEGIN: cesar HTML gadget - copyright cesar 2008 www.cesar.de -->\n";
                html += "<div id=\"cesarGadget\">\n";
                html += "<div id=\"gadget"+this.getSize().value+"\">\n";
                html += "<div id=\"CGtop\">\n";
                html += "<div class=\"CGinner\">\n";
                html += this.listHTML();
                html += "</div></div>\n";
                html += "<input type=\"hidden\" id=\"gadSize\" value=\""+this.getSize().value+"\">\n";
                html += "<script type=\"text/javascript\">var gadgetSize=\""+this.getSize().value+"\";var hash=\""+this.getHash().value+"\"</script>\n";
                html += "<script src=\""+this.getUrl()+"/js/gadget/cg_js.js\" type=\"text/javascript\"></script>\n";
                html += "</div></div>\n";
                html += "<!-- END: cesar HTML gadget - copyright cesar 2008, 2009, 2010 www.cesar.de -->\n";

                return html;
            },
            listHTML: function() {
                html = '';
                if(this.getSize() == '300x250') {
                    html = "<ul class=\"CG\">\n" +
                           "<li class=\"CG\"><a href=\""+this.getUrl()+"/stellenangebote-"+this.getLinksLink()[0].toLowerCase()+".htm\" title=\"Stellenangebote "+this.getLinksShow()[0]+"\" target=\"_blank\">"+this.getLinksShow()[0]+"</a></li>\n" +
                           "<li class=\"CG\"><a href=\""+this.getUrl()+"/stellenangebote-"+this.getLinksLink()[1].toLowerCase()+".htm\" title=\"Stellenangebote "+this.getLinksShow()[1]+"\" target=\"_blank\">"+this.getLinksShow()[1]+"</a></li></ul>" +
                           "<ul class=\"CG\"><li class=\"CG\"><a href=\""+this.getUrl()+"/stellenangebote-"+this.getLinksLink()[2].toLowerCase()+".html\" title=\"Stellenangebote im Bereich "+this.getLinksShow()[2]+"\" target=\"_blank\">"+this.getLinksShow()[2]+"</a></li></ul>\n";
                } else {
                    html = "<ul class=\"CG\">\n" +
                           "<li class=\"CG\"><a href=\""+this.getUrl()+"/stellenangebote-"+this.getLinksLink()[0].toLowerCase()+".htm\" title=\"Stellenangebote "+this.getLinksShow()[0]+"\" target=\"_blank\">"+this.getLinksShow()[0]+"</a></li>\n" +
                           "<li class=\"CG\"><a href=\""+this.getUrl()+"/stellenangebote-"+this.getLinksLink()[1].toLowerCase()+".htm\" title=\"Stellenangebote "+this.getLinksShow()[1]+"\" target=\"_blank\">"+this.getLinksShow()[1]+"</a></li>\n" +
                           "<li class=\"CG\"><a href=\""+this.getUrl()+"/stellenangebote-"+this.getLinksLink()[2].toLowerCase()+".html\" title=\"Stellenangebote im Bereich "+this.getLinksShow()[2]+"\" target=\"_blank\">"+this.getLinksShow()[2]+"</a></li></ul>\n";
                }
                return html;
            },
            saveGadget: function() {
				var valid = this.getValidate(); 
				var codeField = this.getCode();
				var code = this.HTML();
				var params = {"size" : this.getSize().value,
			                  "code": code,
			                  "link": this.getLink().value,
			                  "hash": this.getHash().value
			    }
			    params = JSON.stringify(params);
				var url = '/gadget-save.html?params=' + encodeURIComponent(params);
				
				new Ajax.Request(url, { 
								method: 'get', 
								onSuccess: function(transport) {	
									if(transport.responseText == 'insert') {
										codeField.value = code;
										$('msg').innerHTML = valid.errorMessage('GADGET ERFOLGREICH ERSTELLT', 'ok');
									} else if (transport.responseText == 'update') {
										codeField.value = code;
										$('msg').innerHTML = valid.errorMessage('ERSTELLTES GADGET ERFOLGREICH AKTUALISIERT', 'ok');
									} else {
										$('msg').innerHTML = valid.errorMessage('FEHLER BEIM ERSTELLEN DES GADGET', 'error');										
									}
								}
							});
            },
            resetForm: function() {
				var i,j, elem; 

                for (i=0; i < this.getForm().elements.length; i += 1) {
                    elem = this.getForm().elements[i];

                    for(j=0; j < this.getSetNull().length; j += 1) {
                        if(elem.type == this.getSetNull()[j]) elem.value = '';
                    }
                }

				this.getForm().submit();
            },
			checkRequiredFields: function() {
				var i, fields = this.getRequiredFields();
				for(i=0; i < fields; i += 1) {
					if($('#' + fields[i]) == '') return false;
				}
				
				return true;
			},
            getStatusNo: function(size) {
                status = [];
                status['219x323'] = 1;
                status['300x250'] = 2;
                status['442x208'] = 3;

                return status[size];
            },
			resetCodeField: function() {
				this.getCode().innerHTML = '';
			}
        },
		before: {
			generateCodeError: function() {
				this.resetCodeField();
			},
			saveGadget: function() {
				this.resetCodeField();
			},
			resetForm: function() {
				this.getValidate().resetMessage();
				this.getHash().value = '';
			}			
		}
    })    
});

