Object.extend(Number.prototype, {
    numberFormat : function(decimals) {
        var pow, nStr, x, x1, x2;
        var dot = '';
        var rgx = /(\d+)(\d{3})/;

        decimals = decimals || 0;
        pow = Math.pow(10, decimals);
        nStr = (parseFloat(Math.round(this*pow)) / pow).toString();

        if(decimals > 0) {
            dot = '.';
        }

        x = nStr.split('.');
        x1 = x[0];
        x2 = x.length > 1 ? x[1] : '';

        while(x2.length < decimals) {
            x2 += '0';
        }
        x2 = dot + x2;

        while (rgx.test(x1)) {
            x1 = x1.replace(rgx, '$1' + ',' + '$2');
        }
        return x1 + x2;

    }
});

HelpYouText = function() {
    var inactiveColor = '#777777';
    var activeColor = '#000000';

    var rmText = function(e) {
        //e = e || window.event;
        var el = e.element();
        if(el.value == this.message) {
            if(el.wasPass) {
                el.type = 'password';
            }
            el.style.color = activeColor;
            el.value = '';
        }
    }
    var addText = function(e) {
        var el = e.element();
        if(el.value == '') {
            el.style.color = inactiveColor;
            if(el.type == 'password' && !Prototype.Browser.IE) {
                el.type = 'text';
                el.wasPass = true
            }
            el.value = this.message;
        }
    }

    return function(el, msg) {

        this.message = msg;

        if(!$(el)) {
            return;
        }
        el = $(el);

        el.value = el.value || this.message;
        el.observe('focus', rmText.bindAsEventListener(this));
        el.observe('blur', addText.bindAsEventListener(this));
        if(el.value == this.message) {
            if(el.type == 'password' && !Prototype.Browser.IE) {
                el.type = 'text';
                el.wasPass = true
            }
            el.style.color = inactiveColor;
        }
    }

}();


SmTrac = function() {
    var selectedApp = null;

    return {
        init: function() {

            new HelpYouText('username', "Username");
            new HelpYouText('password', "Password");

            //            setTimeout(function() {
            //alert($('btn-application-selector'));
            if($('btn-application-selector')) {
                $('btn-application-selector').observe('click', this.addApplicationWindow.bindAsEventListener(this))
            }
            if($('btn-remove-client')) {
                $('btn-remove-client').observe('click', this.rmClient.bindAsEventListener(this))
            }
            //            }, 300);

            //            alert($$('.tracking-tbody').length);
            $$('.tracking-tbody').each(function(el) {
                var id = el.id.replace(/tracking-tbody-/, '');

                //                console.log('id:'+id);
                //                alert('id:'+id);

                this.tracking['msg'+id] = new this.clickTracking(id);

            }.bind(this));

            var addD = $('domain-add');
            if(addD) {
                addD.observe('click', this.showAddDomain.bindAsEventListener(this));
            }
        //SmTrac.addApplicationWindow.bind(SmTrac);


        //            if($('btn-add-app')) {
        //                $('btn-add-app').observe('click', function() {
        //                    Ext.getBody().mask();
        //                    var el = Ext.DomHelper.append(Ext.getBody(), {
        //                        id: 'win-add-app',
        //                        style:'width:640px;height:480px;background-color:#ffffff',
        //                        cls: 'ext-el-mask-msg',
        //                        html: 'window'
        //                    });
        //                    Ext.fly(el).center();
        //                });
        //            }

        },

        showAddDomain: function(e) {
            e.stop();
            if($('new-domain-input')) {
                var domain = $('new-domain-input').getValue();
                $('new-domain-input').remove();
                new Ajax.Request('/applications/sm_xhr.php', {
                    parameters: 't=addDomain&domain='+domain,
                    onSuccess: function (t) {
//                        console.log(t.responseJSON);
                        if(t.responseJSON.success) {
                            if($('no-domains')) {
                                $('no-domains').hide();
                            }
                            var id = t.responseJSON.id;
                            var li = new Element('li',{id:'domain-'+id, style:'display:none'}).insert(domain+"<img src=\"/images/icon_domain_remove.png\" title=\"Remove Domain\" onclick=\"SmTrac.rmDomain("+id+")\" />");
                            $('new-domain').insert({before:li});
                            li.appear();
                        }
                    }
                });

            }
            else {
                var li = $('new-domain');
                var el = new Element('input',{id:'new-domain-input', type:'text', style:'display:none;width:250px'});
                li.insert({top:el});
                el.blindDown({
                    scaleFromCenter: true,
//                    scaleX: true,
//                    scaleY: false,
                    duration:.25,
                    afterFinish: function() { el.focus(); },
                    transition: Effect.Transitions.sinoidal
                });
            }

        },
        rmDomain: function(id) {
            if(confirm('Are you sure you want to remove this domain?')) {
                new Ajax.Request('/applications/sm_xhr.php', {
                    parameters: 't=rmDomain&id='+id,
                    onSuccess: function (t) {
//                        console.log(t.responseJSON);
                        if(t.responseJSON.success) {
                            if($('domain-'+id)) {
                                $('domain-'+id).fade({
                                    afterFinish:function() {
                                        $('domain-'+id).remove();
                                        if($('no-domains') && $$('#domain-list li').length ==2) {
                                            $('no-domains').appear();
                                        }
                                    }
                                });
                            }
                        }
                    }
                });
            }
        },
        sendMessage:function(msg_id, cb) {

            if(typeof cb != "function") {
                cb = function(t) {
                    var res = t.responseJSON;
                    var msg_id = res.message_id;

                    if($('message-status-'+msg_id)) {
                        $('message-status-'+msg_id).setStyle({
                            color:res.success ? 'green' : '#ff0000'
                            });
                        $('message-status-'+msg_id).update(res.status);
                    }

                    if($('message-btn-'+msg_id)) {
                        $('message-btn-'+msg_id).hide();
                    }

                }
            }
            if($('message-status-'+msg_id)) {
                $('message-status-'+msg_id).update('<img src="../images/spinner.gif" style="vertical-align:-3px" /> Processing... ');
            }

            new Ajax.Request('/applications/sm_xhr.php', {
                parameters: 't=send&message_id='+msg_id,
                onSuccess: function() {
                    var args = arguments;
                    setTimeout(function() {
                        cb.apply(this, args);
                    }, 2000);
                }
            });
        },


        addApplicationWindow: function(e, client_id) {

            e.stop();

            Lightbox.showUrl({
                url: '/applications/html_app_selector.php',
                width: 450,
                height: 400,
                id: 'applicationDiv',
                cb: function() {

                    var appList = $$('#applicationEdit .smapps');

                    appList.each(function(el){
                        el.stopObserving('click');
                        el.observe('click', function(){
                            selectedApp = this.id.substr(6);
                            SmTrac.loadAppForm();
                            SmTrac.editApp();
                        })
                    //$('smapp_'+el.id.substr(6)+'_on').hide();
                    })

                    new Ajax.Request('/applications/sm_xhr.php', {
                        method: 'POST',
                        parameters: {
                            t:'checkClientApps'
                        },
                        onSuccess: function(response){
                            var resp = response.responseJSON;
                            var clientapps = resp.result

                            //                            console.log(clientapps);

                            clientapps.each(function(el){

                                $('smapp_'+el).addClassName('enabled-app');
                                $('smapp_'+el+'_on').show();
                            })
                            selectedApp=(clientapps[0])
                        //this.editApp()
                        //this.loadAppForm()
                        }.bind(this),
                        onFailure: function() {
                            alert("There was an error with the connection");
                        }
                    });


                }.bind(this)
            });
           
        },
        editApp:function(){
            var appList = $$('#applicationEdit .smapps')
            appList.each(function(appIcon) {
                appIcon.removeClassName('selected')
            });

            var appIcon = $('smapp_'+selectedApp);
            appIcon.addClassName('selected');
        },
      
        loadAppForm:function(){
            new Ajax.Updater('applicationForm', '/applications/apps_form.php', {
                parameters: {
                    app: selectedApp
                }
            });
        },
        modAppCofig:function(operation){
            $('applicaionEditLoader').show();
            $('applicaionEditForm').request({
                parameters: 't='+operation,
                onComplete: function(t) {
                    $('applicaionEditLoader').hide();
                    //console.log(t);
                    var resp = t.responseJSON;

                    if(!resp.success) {
                        alert(resp.reason)
                        return;
                    }

                    this.loadAppForm();

                    //                    console.log(operation);
                    //console.log(resp);
                    //                    console.log('smapp_'+resp.application_id+'_on');

                    if(operation == 'removeApp') {
                        //                        console.log('boo');
                        //                        console.log($('smapp_'+resp.application.id+'_on'))
                        if($('smapp_'+resp.application.id+'_on')) {
                            //console.log('hide fired');
                            $('smapp_'+resp.application.id+'_on').hide();
                            $('smapp_'+resp.application.id).removeClassName('enabled-app');
                        }
                        if(!$$('#applicaionEditForm .enabled-app').length) {
                            if($('no-applications-message')) $('no-applications-message').show();
                            if($('btn-add-campaign') && $('btn-add-campaign').visible()) {
                                $('btn-add-campaign').fade();
                            }
                        }
                        //                        console.log($('current-application-'+resp.application.name));

                        if($('current-application-'+resp.application.name)) {
                            $('current-application-'+resp.application.name).remove();
                        }
                    }
                    else if(operation == 'addApp' || operation == 'updateApp') {
                        if($('smapp_'+resp.application.id+'_on')) {
                            //console.log('show_fired');
                            $('smapp_'+resp.application.id+'_on').show();
                            $('smapp_'+resp.application.id).addClassName('enabled-app');
                            if($('btn-add-campaign') && !$('btn-add-campaign').visible()) {
                                $('btn-add-campaign').appear();
                            }
                            if($('no-applications-message')) $('no-applications-message').hide();
                            if($('current-application-list')) {
                                var li = new Element('LI',{
                                    style:'background-image:url('+resp.application.icon_thumbnail+')'
                                    });
                                li.id = 'current-application-'+resp.application.name;
                                li.update(resp.application.name);
                                $('current-application-list').insert(li);
                            }


                        }
                    }

                }.bind(this)
            });


        },


        enableClientAccess: function (val) {
            $$('#client-details input').invoke(val ? "enable" : "disable");
        },
        checkUserDetails: function() {

            if($('allow-client-access') && !$('allow-client-access').checked) {
                return true;
            }
            
            if($('user_password').value && $('user_password').value != $('re_user_password').value) {
                alert('The passwords entered do not match');
                return false;
            }
            if($('user_email')) {
                if(!/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i.test($('user_email').value)) {
                    alert('Please enter a valid email address' + $('user_email').value);
                    return false;
                }
            }

            return true;

        },


        charCounter: function(e, field, max, result) {
            //            console.log(e);
            field = $(field);
            result = $(result);
            var len = field.value.length;
            if(len >= max) {
                if(e.keyCode != Event.KEY_DELETE
                    && e.keyCode != Event.KEY_BACKSPACE
                    && e.keyCode != Event.KEY_UP 
                    && e.keyCode != Event.KEY_DOWN 
                    && e.keyCode != Event.KEY_LEFT 
                    && e.keyCode != Event.KEY_RIGHT
                    && e.keyCode != Event.KEY_HOME
                    && e.keyCode != Event.KEY_END
                        )
                    Event.stop(e);
            //                result.setStyle({color:'red', fontWeight:'bold'});
            }
            else {
        //                result.setStyle({color:'', fontWeight:''});
        }
        },
        updateCounterTotal: function(e, field, max, result) {
            //            console.log(e);
            var el = $(field);
            result = $(result);
            el.value = el.value.substring(0, max);
            if(el.value.length == max) {
                result.setStyle({
                    color:'red',
                    fontWeight:'bold'
                });
            }
            else {
                result.setStyle({
                    color:'',
                    fontWeight:''
                });
            }
            result.update(el.value.length);
        },

        tracking: {},

        rmClient: function() {
            if(confirm('Are you sure you want to remove this client?\n\nAll campaigns, applications and tracking data will be lost')) {
                new Ajax.Request('/applications/sm_xhr.php', {
                    parameters: 't=rmClient',
                    onSuccess: function (t) {
                        if(t.responseJSON.success) {
                            location='./sm_clients.php';
                        }
                        else {
                            alert('Delete Failed\n\n' + (t.responseJSON.reason ? t.responseJSON.reason : ''));
                        }
                    }
                });
            }
        },


        rmDept: function() {
            if(confirm('Are you sure you want to remove this department?\n\nAll campaigns, applications and tracking data will be lost.')) {
                new Ajax.Request('/applications/sm_xhr.php', {
                    parameters: 't=rmClient',
                    onSuccess: function (t) {
                        if(t.responseJSON.success) {
                            location='./sm_departments.php';
                        }
                        else {
                            alert('Delete Failed\n\n' + (t.responseJSON.reason ? t.responseJSON.reason : ''));
                        }
                    }
                });
            }
        },


        rmCampaign: function( campaign_id ) {
            if(confirm('Are you sure you want to delete this campaign?\n\n All details and tracking data will be lost.')) {
                new Ajax.Request('/applications/sm_xhr.php', {
                    parameters: 't=rmCampaign&campaign_id='+campaign_id,
                    onSuccess: function (t) {
                        if(t.responseJSON.success) {
                            location='./sm_campaigns.php';
                        }
                        else {
                            alert('Delete Failed\n\n' + (t.responseJSON.reason ? t.responseJSON.reason : ''));
                        }
                    }
                });
            }
        }

        
    }
}();


SmTrac.clickTracking = function(msgId) {
    this.msgId = msgId;
    this.getTrackingData(0);
}
SmTrac.clickTracking.prototype = {
    latestTrackingId: 0,
    trackingInterval: 7,
    getTrackingData: function(from) {

        if(!$('tracking-tbody-' + this.msgId));

        if(!this.latestTrackingId && from) {
            this.latestTrackingId = from;
        }

        //console.log(this.msgId);

        //return;

        new Ajax.Request('/applications/sm_xhr.php', {
            method: 'POST',
            parameters: {
                t:'trackingData',
                msg_id: this.msgId,
                from: this.latestTrackingId
            },
            onSuccess: function(t){
                var r = t.responseJSON;
                if(r.success) {

                    //                        console.log('clicks:'+r.message.clicks);
                    //                        console.log('visitors:'+r.message.visitors);

                    $('message-clicks-'+this.msgId).update(r.message.clicks);
                    $('message-visitors-'+this.msgId).update(r.message.visitors);

                    //                        console.log($('message-cost-per-click-'+this.msgId));
                    //                        console.log(r.message.cost_per_click);
                    var costPerClick = typeof r.message.cost_per_click != "string" ? r.message.cost_per_click.numberFormat(2) : r.message.cost_per_click;
                    var costPerVisitor = typeof r.message.cost_per_visitor != "string" ? r.message.cost_per_visitor.numberFormat(2) : r.message.cost_per_visitor;

                    $('message-cost-per-click-'+this.msgId).update(costPerClick);
                    $('message-cost-per-visitor-'+this.msgId).update(costPerVisitor);


                    var tbody = $('tracking-tbody-' + this.msgId);
                    r.data.each(function(data, i) {
                        var cells;
                        var colour = (i+1)&1 ? "#ffffff" : "#fafafa";

                        if(i==0) {
                            this.latestTrackingId = data.id;
                        }

                        var tr = $(tbody.insertRow(i));
                        tr.setStyle({
                            background:colour
                        });
                        if(!Prototype.Browser.IE) tr.setOpacity(0);

                        [   data.date_text,
                        data.ip_address,
                        '<img src="' + data.browser_icon +'" style="vertical-align:-3px"/> ' + data.browser,
                        data.os
                        ].each(function(content, i) {
                            var cell = $(tr.insertCell(i));
                            if(Prototype.Browser.IE) cell.setOpacity(0);
                            cell.innerHTML = content;
                            if(Prototype.Browser.IE) cell.appear({
                                duration:2
                            });
                        });

                        if(!Prototype.Browser.IE) tr.appear({
                            duration:2
                        });
                    //                            throw $break;

                    }.bind(this));
                }

                if(this.trackingInterval) {
                    setTimeout(function() {
                        this.getTrackingData(this.msgId);
                    }.bind(this), this.trackingInterval*1000);
                }
            }.bind(this)
        });
    }
}

document.observe('dom:loaded', SmTrac.init.bind(SmTrac));
