Ext.namespace('Ext.ux.plugins', 'SiteBuilder', 'SiteBuilder.widget', 'SiteBuilder.util');

Ext.override(Ext.form.ComboBox, {
    initEvents: function(){
        Ext.form.ComboBox.superclass.initEvents.call(this);
        
        this.keyNav = new Ext.KeyNav(this.el, {
            "up": function(e){
                this.inKeyMode = true;
                this.selectPrev();
            },
            
            "down": function(e){
                if (!this.isExpanded()) {
                    this.onTriggerClick();
                }
                else {
                    this.inKeyMode = true;
                    this.selectNext();
                }
            },
            
            "enter": function(e){
                this.onViewClick();
                this.delayedCheck = true;
                this.unsetDelayCheck.defer(10, this);
            },
            
            "esc": function(e){
                this.collapse();
            },
            
            "tab": function(e){
                this.onViewClick(false);
                return true;
            },
            
            scope: this,
            
            doRelay: function(foo, bar, hname){
                if (hname == 'down' || this.scope.isExpanded()) {
                    return Ext.KeyNav.prototype.doRelay.apply(this, arguments);
                }
                return true;
            },
            
            forceKeyDown: true
        });
        this.queryDelay = Math.max(this.queryDelay || 10, this.mode == 'local' ? 10 : 250);
        this.dqTask = new Ext.util.DelayedTask(this.initQuery, this);
        if (this.typeAhead) {
            this.taTask = new Ext.util.DelayedTask(this.onTypeAhead, this);
        }
        if (this.editable !== false && !this.enableKeyEvents) {
            this.el.on("keyup", this.onKeyUp, this);
        }
    },
    
    // private
    beforeBlur: function(){
        var val = this.getRawValue();
        if (this.forceSelection) {
            if (val.length > 0 && val != this.emptyText) {
                this.el.dom.value = this.lastSelectionText === undefined ? '' : this.lastSelectionText;
                this.applyEmptyText();
            }
            else {
                this.clearValue();
            }
        }
        else {
            var rec = this.findRecord(this.displayField, val);
            if (rec) {
                val = rec.get(this.valueField || this.displayField);
            }
            this.setValue(val);
        }
    },
    
    doForce: undefined // no longer in use
});

Ext.override(Ext.form.TimeField, {
    // private
    beforeBlur: function(){
        var v = this.parseDate(this.getRawValue());
        if (v) {
            this.setValue(v.dateFormat(this.format));
        }
        Ext.form.TimeField.superclass.beforeBlur.call(this);
    }
});

Ext.override(Ext.Element, {
    contains: function(){
        var isXUL = Ext.isGecko ? function(node){
            return Object.prototype.toString.call(node) == '[object XULElement]';
        }
        : Ext.emptyFn;
        
        return function(el){
            return !this.dom.firstChild || // if this Element has no children, return false immediately
            !el ||
            isXUL(el) ? false : Ext.lib.Dom.isAncestor(this.dom, el.dom ? el.dom : el);
        };
    }()
});

SiteBuilder.util.ScriptParameters = function(i){
    var qs = document.getElementsByTagName("script")[i].src.match(/\w+=\w+/g), qstring = {}, t, i = qs.length;
    while (i--) {
        t = qs[i].split("=");
        qstring[t[0]] = t[1];
    }
    return qstring;
}

SiteBuilder.util.ClearField = function(object){
    object.value = "";
}

SiteBuilder.util.SelectField = function(object){
    object.select();
}

SiteBuilder.util.OpenWindow = function(config){
    if (screen.width) {
        var winl = (screen.width - config.width) / 2;
        var wint = (screen.height - config.height) / 2;
    }
    else {
        winl = 0;
        wint = 0;
    }
    if (winl < 0) 
        winl = 0;
    if (wint < 0) 
        wint = 0;
    
    var settings = 'height=' + config.height + ',';
    settings += 'width=' + config.width + ',';
    settings += 'top=' + wint + ',';
    settings += 'left=' + winl + ',';
    settings += config.features;
    
    win = window.open(config.url, config.name, settings);
    win.window.focus();
}

SiteBuilder.widget.FontToolbar = function(config){
    var config = config ||
    {};
    
    Ext.onReady(function(){
        if (Ext.get(config.attachEl)) {
        
            var tpl = new Ext.XTemplate('<div id="sbFontToolbarWrap">', ' <div id="sbFontToolbar">', '   <div id="sbFontToolbarText">Text Size</div>', '   <img id="sbDecreaseFont" src="/sbtemplates/sbcommon/images/minimize2.png" border="0" title="Decrease Font" alt="Decrease Font"/>', '   <img id="sbIncreaseFont" src="/sbtemplates/sbcommon/images/maximize2.png" border="0" title="Increase Font" alt="Increase Font"/>', ' </div>', '</div>');
            tpl.insertFirst(Ext.get(config.attachEl));
            
            Ext.get('sbDecreaseFont').on('click', function(){
                var min = 8;
                var max = 18;
                var p = Ext.DomQuery.select('p', config.attachEl);
                for (i = 0; i < p.length; i++) {
                    if (p[i].style.fontSize) {
                        var s = parseInt(p[i].style.fontSize.replace("px", ""));
                    }
                    else {
                        var s = 12;
                    }
                    if (s != min) {
                        s -= 1;
                    }
                    p[i].style.fontSize = s + "px"
                }
            }, this);
            
            Ext.get('sbIncreaseFont').on('click', function(){
                var max = 18;
                var p = Ext.DomQuery.select('p', config.attachEl);
                for (i = 0; i < p.length; i++) {
                    if (p[i].style.fontSize) {
                        var s = parseInt(p[i].style.fontSize.replace("px", ""));
                    }
                    else {
                        var s = 12;
                    }
                    if (s != max) {
                        s += 1;
                    }
                    p[i].style.fontSize = s + "px"
                }
            }, this);
        }
    }, this);
}

SiteBuilder.widget.ContentWindow = function(config, alignTo, alignWhere){
    var config = Ext.apply({
        id: 'sbPopup',
        title: 'Popup Window',
        contentEl: 'sbPopupContent',
        width: 300,
        height: 300,
        resizable: false,
        draggable: false,
        closeAction: 'destroy',
        constrain: true
    }, config ||{});
    
    Ext.onReady(function(){
        if (Ext.get(config.contentEl)) {
            var win = new Ext.Window(config).show();			
            if(config.clickAway == true){
                win.getEl().on('click', win.close())
            }						
            if (alignTo !== undefined) {
                win.alignTo(alignTo, alignWhere);
            }
        }
    });	
}

SiteBuilder.widget.Submitter = function(form, options){
    var options = options ||
    {};
    
    // Find the submit
    var submitButton = Ext.DomQuery.selectNode("input[type=submit]", form.id);
    this.submitText = submitButton.value;
    
    // Collect the labels
    var oLabel = new Object;
    oLabel['form'] = form.id;
    var nodes = Ext.DomQuery.select("label", form.id);
    for (var i = 0; i < nodes.length; i++) {
        var node = nodes[i];
        oLabel[node.attributes['for'].value + 'Label'] = node.innerHTML.toString().trim();
    };
    
    Ext.Ajax.on('beforerequest', function(){
        submitButton.value = 'Processing...';
    }, this, {
        single: true
    });
    
    Ext.Ajax.on('requestcomplete', function(){
        submitButton.value = this.submitText;
    }, this, {
        single: true
    });
    
    Ext.Ajax.request({
        method: 'post',
        url: (options.url !== undefined) ? options.url : '/forms/ajaxProcessForm.html',
        params: Ext.Ajax.serializeForm(form) + '&' + Ext.urlEncode(oLabel) + '&' + Ext.urlEncode(options) + '&sb=' + _SBCONFIG_.sbToken,
        callback: (options.callback !== undefined) ? options.callback : function(){
        },
        success: function(response, o){
            // Update element after
            if (options.update !== undefined) {
                Ext.get(options.update).update(response.responseText);
                return;
            }
            var result = Ext.decode(response.responseText);
            if (result.success == true) {
                // Redirect passed in from script
                if (options.goToAfter !== undefined) {
                    window.location = options.goToAfter;
                }
                
                // Redirect passed in from the server 
                if (result.redirect !== undefined) {
                    window.location = result.redirect;
                }
                
                // Overwrite form div with confirmation                
                if (options.showConfirm == undefined || options.showConfirm == true) {
                    // what element to show confirm in
                    var tgt = (options.confirmEl !== undefined) ? Ext.get(options.confirmEl) : form;
                    
                    if (result.confirmation != undefined) {
                        // Server confirmation message
                        Ext.DomHelper.overwrite(tgt, result.confirmation);
                    }
                    else {
                        // Default confirmation message
                        Ext.DomHelper.overwrite(tgt, '<p>Thank you! Your request has been processed.</p>');
                    }
                }
                
                if (options.showAfter !== undefined) {
                    Ext.DomHelper.overwrite(form, ' ');
                    Ext.get(options.showAfter).show();
                }
                
            }
            else {
            
                // If captcha reset it
                if (Ext.get('sbCaptchaImage')) {
                    Ext.get('sbCaptchaImage').dom.src = '/forms/captcha.html?' + Math.random();
                }
                
                // Clear previous error markers							
                var nodes = Ext.DomQuery.select("*[class*=sbFormError]", form.id);
                for (var i = 0; i < nodes.length; i++) {
                    Ext.get(nodes[i].id).removeClass('sbFormError');
                };
                
                // Build current error string				
                var str = 'Sorry, there were errors in your request:\n\n';
                for (var i in result.errors) {
                    var inputNode = Ext.DomQuery.selectNode("*[name=" + i + "]", form.id);
                    if (inputNode) {
                        // mark the input
                        Ext.get(inputNode).addClass('sbFormError');
                        
                        // get label
                        var labelNode = Ext.DomQuery.selectNode("label[for=" + i + "]", form.id);
                        
                        // add to error string
                        str += labelNode.innerHTML.toString().trim() + ': ' + result.errors[i] + '\n';
                    }
                    else {
                        // just set the error str
                        str += 'Error: ' + result.errors[i] + '\n';
                    }
                }
                alert(str);
            }
        },
        failure: function(response, options){
            var result = Ext.decode(response.responseText);
            alert('There was an error processing your request. Please contact an adminstrator.');
        }
    });
    return false;
}

SiteBuilder.widget.Include = function(config){
    var config = config ||
    {};
    Ext.onReady(function(){
        Ext.Ajax.request({
            method: 'GET',
            url: config.url,
            success: function(response, options){
                Ext.get(config.target).update(response.responseText, true);
            },
            failure: function(response, options){
                var result = Ext.decode(response.responseText);
                alert('There was an error processing your request. Please contact an adminstrator.');
            },
            loadScripts: true
        });
    }, this);
}

/* Start Google globals */
var google_conversion_id = "";
var google_conversion_language = "";
var google_conversion_format = "";
var google_conversion_color = "";
var google_conversion_label = "";
/* End Google global vars */

SiteBuilder.widget.GoogleConversionTracker = function(config){
    var config = config ||
    {};
    
    google_conversion_id = config.id;
    google_conversion_language = "en_US";
    google_conversion_format = "3";
    google_conversion_color = "ffffff";
    google_conversion_label = "HuZxCP76cBDcgqbvAw";
    
    Ext.DomHelper.append(Ext.getBody(), {
        tag: 'img',
        height: '1',
        width: '1',
        src: 'http://www.googleadservices.com/pagead/conversion/' + google_conversion_id + '/?value=1.0&amp;label=Purchase&amp;script=0'
    });
    return false;
}

SiteBuilder.widget.OnClickWindow = function(config){
    if (Ext.get(config.id)) {
        Ext.get(config.id).setStyle({
            cursor: 'pointer'
        });
        Ext.get(config.id).on('click', function(){
            SiteBuilder.util.OpenWindow(config);
        });
    }
}

SiteBuilder.widget.OnClickBookmark = function(id, url, title){
    if (Ext.get(id)) {
        Ext.get(id).on('click', function(){
            if (window.sidebar) // firefox
                window.sidebar.addPanel(title, url, "");
            else 
            if (window.opera && window.print) { // opera
                var elem = document.createElement('a');
                elem.setAttribute('href', url);
                elem.setAttribute('title', title);
                elem.setAttribute('rel', 'sidebar');
                elem.click();
            }
            else
            if (document.all)// ie
                window.external.AddFavorite(url, title);
            
        });
    }
}

SiteBuilder.widget.InsertIframe = function(o){
    var o = o ||
    {};
    var config = Ext.apply({
        id: 'target',
        src: 'http://www.google.com',
        width: '300',
        height: '300',
        frameborder: '0',
        scrolling: 'no'
    }, o);
    
    if (document.getElementById(config.id)) {
        var iframe = document.createElement('iframe');
        iframe.id = config.id + '-iframe';
        iframe.src = config.src;
        iframe.width = config.width;
        iframe.height = config.height;
        iframe.frameborder = config.frameborder;
        iframe.scrolling = config.scrolling;
        document.getElementById(config.id).appendChild(iframe);
    }
}

SiteBuilder.widget.MemberDirectory = function(config){
    this.config = config ||
    {};
    
    Ext.DomHelper.append('comp-sbMemberDirectory', {
        id: 'sbMemberSelector',
        tag: 'div',
        children: [{
            id: 'sbMemberList',
            tag: 'ul'
        }]
    });
    
    var abc = Array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z');
    for (var i = 0; i < abc.length; i++) {
        var li = Ext.DomHelper.append('sbMemberList', {
            tag: 'li',
            html: abc[i]
        });
        Ext.get(li).on('click', (function(params){
            return function(){
                Ext.getCmp('panel').load({
                    method: 'post',
                    url: '/user/ajaxGetUsers.html',
                    params: params
                });
            }
        })(Ext.apply({}, config, {
            sb: _SBCONFIG_.sbToken,
            letter: abc[i]
        })), this);
    }
    
    var panel = new Ext.Panel({
        id: 'panel',
        width: '95%',
        height: 525,
        renderTo: 'comp-sbMemberDirectory',
        autoScroll: true,
        bodyStyle: {
            padding: '5px'
        }
    });
    
    panel.load({
        method: 'post',
        url: '/user/ajaxGetUsers.html',
        params: Ext.apply({}, config, {
            sb: _SBCONFIG_.sbToken,
            letter: 'A'
        })
    })
};

SiteBuilder.isValidWebsiteUser = function(){
    if (_SBCONFIG_.sbUserToolbar !== undefined) {
        return true;
    }
    return false;
}

SiteBuilder.isValidEditorUser = function(){
    if (_SBCONFIG_.sbLoginUser !== undefined) {
        return true;
    }
    return false;
}

SiteBuilder.isEditMode = function(){
    if (_SBCONFIG_.environment.substring(0, 4) == "edit") {
        return true;
    }
    return false;
}

SiteBuilder.isValidBrowser = function(){
    if (Ext.isIE8 == true || Ext.isIE7 == true || Ext.isGecko2 == true || Ext.isGecko3 == true || Ext.isSafari == true || Ext.isChrome == true) {
        return true;
    }
    return false;
}

SiteBuilder.renderWebsiteUserToolbar = function(){
    var node = Ext.DomQuery.selectNode('div[class=sbContainer]');
    var tpl = new Ext.XTemplate('<div id="sb-wrap">', '	<div id="sb-wrap-left">', '		You are logged in.', '	</div>', '	<div id="sb-wrap-right">', '		<a href="/user/logout.html">Logout</a>', '	</div>', '</div>');
    tpl.insertBefore(node, {});
}

SiteBuilder.renderBrowserWarning = function(){
    var msgTpl = new Ext.XTemplate('<h1>Unsupported Browser</h1>', 'Unfortunately, it appears you are using an unsupported browser. To access Officite\'s Site Editor please download and install one of the products listed below. Site Editor currently supports the following browsers:', '<ul>', '	<li><a href="http://www.mozilla.com/en-US/">Firefox 2+</a></li>', '	<li><a href="http://www.microsoft.com/windows/downloads/ie/getitnow.mspx">Internet Explorer 7+</a></li>', '	<li><a href="http://www.apple.com/safari/download/">Safari 4+</a></li>', '</ul>');
    
    var layer = new Ext.Layer({
        id: 'seBrowserCheck',
        cls: 'seBrowserCheck',
        constrain: true
    });
    layer.setWidth(400);
    layer.setHeight(200);
    layer.center();
    layer.update(msgTpl.apply());
    layer.show();
}


SiteBuilder.init = function(){

    mladdevents();
    
    if (SiteBuilder.isValidWebsiteUser()) {
        SiteBuilder.renderWebsiteUserToolbar();
        return;
    }
    
    if (SiteBuilder.isEditMode()) {
        if (!SiteBuilder.isValidBrowser()) {
            SiteBuilder.renderBrowserWarning();
            return;
        }
        
        if (!SiteBuilder.isValidEditorUser()) {
            Login = new Login(_SBCONFIG_);
            Login.init();
            return;
        }
        
        SiteEditor = new SiteEditor(_SBCONFIG_);
        SiteEditor.init();
        return;
    }
}

window.onload = SiteBuilder.init;

