function Template(el){
    var _this = this;

    Finder.call(this, el)

    this.iframeEditor = $(this.templateIframeId);
    this.templateBody = $(this.templateBodyId);
    //this.html = this.templateBody.innerHTML;

    this.state_form_enter();
    
}

extend(Template, Finder);

Template.prototype.baseattr = "template";

Template.prototype.attributes = {"templateBodyId" : {},
                                 "templateIframeId" : {},
                                 "templateContainerId" : {},
                                 "templateSaveId" : {}
                                }

Template.prototype.resizeInput = function(parent, input){
    if(input.nodeName.toLowerCase() != "input" ) return;

    var parent = parent;
    var el = document.createElement("SPAN");
    el.style.fontSize = input.style.fontSize;
    el.style.paddingLeft = input.style.paddingLeft;
    el.style.paddingRight = input.style.paddingRight;
    el.style.marginLeft = input.style.marginLeft;
    el.style.marginRight = input.style.marginRight;
    el.style.display = "inline-block";
    el.style.whiteSpace = "nowrap";
    el.innerHTML = input.value.replace(/\s/g, '&nbsp;');
    el.style.visibility = "hidden";
    parent.appendChild(el);
    input.style.width = el.offsetWidth + 10 + 'px';
    //HACK for IE and FF to copy the value to the html
    input.setAttribute("value", input.value);
    parent.removeChild(el);
    delete el;
}

Template.prototype.addResizeListeners = function(){
    var _this = this;
    var inputs = getNodesWithAttr(this.templateBody, "replaceInput");
    for(var x =0; x < inputs.length; x++){

        if(inputs[x]){
            _this.resizeInput(this.templateBody, inputs[x]);
            addEventListener(inputs[x], 
                             "keyup", 
                             function(e){
                                 var src = evtSrc(getEvent(e));
                                 _this.resizeInput(_this.templateBody, src);
                             } );
        }
    }
}

Template.prototype.changeSpansToInputs = function(html){
    var div = document.createElement("DIV");
    div.innerHTML = html;

    var spans = getNodesWithAttr(div, "replaceSpan");
    //var inputs = getNodesWithAttr(editDoc, "replaceInput");
    for(var x =0; x < spans.length; x++){
        var input = document.createElement("INPUT");
        input.className = "replaceInput";
        input.setAttribute("replaceInput", "true");
        input.value = getInnerText(spans[x]);
        input.setAttribute("value", getInnerText(spans[x]));
        input.setAttribute("prevTag", spans[x].nodeName);

        var parent = spans[x].parentNode;
        parent.insertBefore(input, spans[x]);
        var child = parent.removeChild(spans[x]);

    }

    return div.innerHTML;
}

Template.prototype.changeInputsToSpans = function(html){
    var div = document.createElement("DIV");
    div.innerHTML = html;

    var inputs = getNodesWithAttr(div, "replaceInput");

    for(var x =0; x < inputs.length; x++){
        var prevTag = inputs[x].getAttribute("prevTag");
        var span = document.createElement(prevTag ? prevTag : "SPAN");
        span.className = "replaceSpan";
        span.setAttribute("replaceSpan", "true");
        span.innerHTML = inputs[x].value;

        var parent = inputs[x].parentNode;
        parent.insertBefore(span, inputs[x]);
        var child = parent.removeChild(inputs[x]);

    }

    return div.innerHTML;
}

Template.prototype.getEditDoc = function(){
    return getIframeDocument(this.iframeEditor);
}

Template.prototype.hide = function(el){
    hide(el);
}

Template.prototype.show = function(el){
    show(el);
}


Template.prototype.state_save_enter = function(){
    this.show($(this.templateSaveId));
}

Template.prototype.state_save_exit = function(){
    this.hide($(this.templateSaveId));
}

Template.prototype.state_form_enter = function(){

    this.hide(this.iframeEditor);

    this.show(this.templateBody);

    //for admin
    if(this.html && true){
        this.templateBody.innerHTML = this.changeSpansToInputs(this.html);
        this.addResizeListeners();
    }


    if(this.html === undefined){
        this.templateBody.innerHTML = this.changeSpansToInputs(this.templateBody.innerHTML);
        this.html = this.templateBody.innerHTML;
        this.addResizeListeners();
    }




}

Template.prototype.state_form_exit = function(){
    this.html = this.templateBody.innerHTML;
    this.hide(this.templateBody);
}

Template.prototype.state_edit_updateHtml = function(){
    this.html = this.getEditDoc().body.innerHTML;
}

Template.prototype.state_edit_enter = function(){
    var editDoc = getIframeDocument(this.iframeEditor);

    this.hide(this.templateBody);
    this.show(this.iframeEditor);

    var _this = this;

    var isBodyReady = function(){return editDoc.body;};

    var setContent = function (){
        editDoc.designMode = "on";
        waitUntil(function(){editDoc.body.innerHTML = _this.changeInputsToSpans(_this.html);},
                  50, 
                  isBodyReady);
            /*
        waitUntil(function(){resizeIframe(_this.iframeEditor);},
                  50, 
                  isBodyReady);*/
    }

    waitUntil(function(){setContent();}, 
              50, 
              isBodyReady
             )
             
}

Template.prototype.state_edit_exit = function(){
    this.state_edit_updateHtml();
    this.hide(this.iframeEditor);
}

//remove font, style tags
Template.prototype.cleanse = function(){
    var tags = {"style" : {"type" : "delete"},
                "font" : {"type" : "slice"},
                "pre" : {"type" : "slice"},
                "span" : {"type" : "empty"},
                "em" : {"type" : "replace", "newTag" : "i"},
                "div" : {"type" : "replace", "newTag" : "p"}
               }

    try {

        var editDoc = this.getEditDoc();
        var div = this.getEditDoc().createElement("DIV");
        div.innerHTML = this.html;

        //remove elements
        for(var x in tags){
            var els = div.getElementsByTagName(x);
            for(var y=0; y<els.length; y++){
                var item = els.item(y);
                
                switch(tags[x].type){
                case "empty": //remove empty tags with whitespace
                    if(item.innerHTML.search(/\S/) > -1)
                        break;
                    //else delete the tag
                case "delete": //delete tags and all content
                    item.parentNode.removeChild(item);
                    delete item;
                    --y;
                    break;
                case "slice": //slice out node, but leave content
                    sliceNode(item);
                    delete item;
                    --y;
                    break;
                case "replace": //replace one tag with another
                    var parent = item.parentNode;
                    var newTag = editDoc.createElement(tags[x].newTag);

                    newTag.innerHTML = item.innerHTML;
                    parent.replaceChild(newTag, item);
                    --y; //decrement y since collection lenght will change after remove
                    break;
                }

                
            }

        }

        this.html = div.innerHTML;
        delete div;

    } catch (e) {
        log(e);
    }

}


Template.prototype.toggleFrames = function(currentState){
    try {
        this.currentState = this.currentState ? this.currentState : "form";
        if(this.currentState != currentState)
            eval("this.state_" + this.currentState + "_exit()");

        this.cleanse();

        eval("this.state_" + currentState + "_enter()");

        this.currentState = currentState;

    } catch(e){
        log(e);
    }

}

Template.prototype.finish = function(finishType){


    var templateText;

    switch(finishType){

    case "html" : 
        templateText = this.html;
        break;
    case "text" :
        templateText = this.html;
        break;
    case "email" :
        templateText = this.html;
        break;
    }

    var tmpForm;

    if(finishType == 'email') {
        tmpForm = $('templateEmailForm');
    } else {
        tmpForm = document.createElement("form");
        this.hide(tmpForm);
        document.body.appendChild(tmpForm)
    }
    tmpForm.action = '/save.php';
    tmpForm.method = 'POST';


    var params = {"format" : finishType,
                  "templateText" : templateText}

    for(var name in params){
        if(tmpForm[name] === undefined) {
            var input = document.createElement("input");
            input.type = "hidden";
            input.name = name;
            tmpForm.appendChild(input);
            //IE funkiness here
            if(tmpForm[name] === undefined)
                tmpForm[name] = input;
        }

        tmpForm[name].value = params[name];
    }

    var obj = {"form" : tmpForm,
               "postSubmitCallback" : function(){if(finishType == 'email') alert("Your email has been sent.");}}

    var sub = new FormSubmitter(obj);
    sub.submit();





}

Template.prototype.invoke("Template");
