﻿if (typeof jajah == "undefined") var jajah = {};
if (typeof jajah.sync == "undefined") jajah.sync = {};

jajah.sync.Mgr = function() {
    //JajahDispatcher.init(this);
    //this.states = [{ t: 2, w: 250, h: 130 }, { t: 2, w: 300, h: 350}];
    this.currState = 0;
    this.stateCount = 7;
    this.phones = { ll: "", mo: "", of: "" };
    this.phoneTitles = { ll: "Home", mo: "Mobile", of: "Office" };
    this.otaCount = 0;
    this.countryCodes = ["39"];

    this.Id = {
        Email: "email",
        Pass: "password",
        Per: "permanent",
        LoginBtn: "_loginbtn",
        PhoneContainer: "syncPhoneContainer",
        PhoneTitle: "phoneTitle",
        OtherPhone: "syncPhone",
        One: "one",
        Two: "two",
        Three: "three",
        State1: "VerifyPhonesCont",
        State2: "SelectModelCont",
        State3: "ConfigSMSCont",
        State4: "UnlockYourPhoneCont",
        State5: "ManualConfigCont",
        State6: "SyncingContactsCont",
        State7: "FinishedCont",
        SelectModel: "_selectModel",
        NextBtn: "_nextBtn",
        ResendBtn: "_resendBtn",
        NoBtn: "_noBtn",
        ModelImg: "modelImg",
        InfoHTML: "manualInstructions",
        SyncHTML: "syncInstructions",
        FinalModel: "finalModel",
        FinalCarr: "finalCarrier",
        FinalNum: "finalNumber",
        TermsCB: "termsCb"

    };

    this.Text = {
        Sync: "", //go.jajah.script.link.sync
        AddNum: "", //go.jajah.script.addnum
        ErrOnlyIT: "", //go.jajah.script.error.onlyit
        ErrNum: "",
        ErrSelModel: "", //go.jajah.script.error.selectmodel
        ErrTerms: "" //go.jajah.script.error.terms
    };
}

jajah.sync.Mgr.prototype = {
    init: function() {
        this.change();
        this.setState();
        preload("/images/sync/loading.gif");
    },

    change: function() {
        $M.opacity = 25;
    },

    setState: function() {
        switch (this.currState) {
            case 1: //Verify Number
                this.renderNr();
                this.setStateNum(1);
                if (this.lastState == 6) { //lastState is set from SyncingContacts.ascx (6)
                    $show(el("back1"));
                } else {
                    $hide(el("back1"));
                }
                break;
            case 2: //Select Model
                this.setStateNum(1);
                break;
            case 3: //Config SMS (Resend)
                this.setStateNum(2);
                if (this.otaCount >= 2) {
                    $hide(el(this.Id.ResendBtn + "Div"));
                    $show(el(this.Id.NoBtn + "Div"));
                }
                break;
            case 4: //Unlock your phone
                this.setStateNum(2);
                break;
            case 5: //Manual Instructions
                this.setStateNum(2);
                this.getInfoHTML();
                break;
            case 6: //Syncing Contacts
                this.setStateNum(2);
                setTimeout(function() { SyncMgr.finalDetails(); }, 400);
                this.getSyncHTML();
                break;
            case 7: //Finished
                setTimeout(function() { SyncMgr.finalDetails(); }, 400);
                this.setStateNum(3);
                break;

        }
        this.clearMsg();
        this.enableState();
        this.hideAllStates();
        $show(el(this.Id["State" + this.currState]));
        if (this.currState > 0) this.setEars();
    },

    hideAllStates: function() {
        for (var i = 1; i <= this.stateCount; i++) {
            $hide(el(this.Id["State" + i]));
        }
    },

    nextState: function(state) {
        if ($un != typeof state) {
            this.currState = state;
            this.setState();
            return;
        }
        switch (this.currState) {
            case 1: //Verify Phone
                this.getSelNum();
                break;
            case 2: //Select Model
                this.addDevice();
                break;
            case 4: //Unlock your phone (PIN)
                this.currState = 6;
                this.setState()
                break;
            default: // 3 ConfigSMS, 5 ManualInstructions, 6 SyncingContacts
                this.currState++;
                this.setState();
                break;
        }
    },

    prevState: function() {
        if (this.currState <= 1) return;
        switch (this.currState) {
            case 5:
                this.currState = 2;
                break;
            case 6:
                if (this._ota) {
                    this.currState = 4;
                } else {
                    this.currState = 5;
                }
                break;
            default:
                this.currState--;
                break;
        }

        this.setState();
    },

    enableState: function() {
        $enable(this.Id.NextBtn + this.currState);
        if (this.currState == 3) { //config sms (resend)
            $enable(this.Id.ResendBtn);
            $enable(this.Id.NoBtn);
        }
    },

    setStateNum: function(n) {
        $show(el(this.Id.One));
        $show(el(this.Id.Two));
        $show(el(this.Id.Three));
        switch (n) {
            case 1:
                setOpacity(el(this.Id.One), 100);
                setOpacity(el(this.Id.Two), 50);
                setOpacity(el(this.Id.Three), 25);
                break;
            case 2:
                $hide(el(this.Id.One));
                setOpacity(el(this.Id.Two), 100);
                setOpacity(el(this.Id.Three), 50);
                break;
            case 3:
                $hide(el(this.Id.One));
                $hide(el(this.Id.Two));
                setOpacity(el(this.Id.Three), 100);
                break;

        }
    },

    login: function() {
        this.drawLoading();
        var eml = el(this.Id.Email);
        var emlv = (eml.value != eml.data) ? eml.value : "";
        var pss = el(this.Id.Pass);
        var pssv = (pss.value != pss.data) ? pss.value : "";
        var data = { "email": emlv, "pass": pssv, "per": el(this.Id.Per).checked };
        $X.Post($X.Url.Account, "Login", data, this.onLogin.link(this)).Send();
    },

    logout: function() {
        this.drawLoading();
        $X.Post($X.Url.Account, "Logout", {}, this.onLogin.link(this)).Send();
    },

    onLogin: function(res, ok) {
        if ("ok" != res.status) {
            this.clearLoading();
            this.setMsg(res.msg);
            $enable(this.Id.LoginBtn);
        } else {
            location.reload();
        }
    },

    /* Rendering start */
    renderNr: function() {
        if (!this.phoneCont) {
            var dc = "+" + ((this.dialCode) ? this.dialCode : DestMgr.DefDC);
            //( name, typ, custom, nr, parent, replace, params )
            this.phoneCont = NrControlMgr.CreateControl("sync_cont", "destination", null, dc, this.Id.PhoneContainer, true, null);
            this.fillNumber.delay(20, this, this.phones.mo, "mo"); //delay it
        }
    },

    fillNumber: function(number, type) {
        this._selNumType = type;
        el(this.Id.PhoneTitle + "1").innerHTML = this.phoneTitles[type];
        this.fillNumberCont(number);

        var phoneNum = 2;
        for (var s in this.phones) {
            if (s != type && this.phones.hasOwnProperty(s)) {
                el(this.Id.PhoneTitle + phoneNum).innerHTML = this.phoneTitles[s];
                var phoneText = this.phones[s] ? this.phones[s] : "&lt;" + this.Text.AddNum + "&gt;";
                var href = " <a href=\"#\" onclick=\"SyncMgr.fillNumber(\'" + this.phones[s] + "\',\'" + s + "\');return false;\">" + this.Text.Sync + "</a>";
                el(this.Id.OtherPhone + phoneNum).innerHTML = phoneText + href;
                phoneNum++;
            }
        }

        this.clearMsg();
    },

    fillNumberCont: function(number) {
        if (number) {
            var tel = $Tel.Create("+" + number);
            this.phoneCont.Country.value = tel.DialCode;
            this.phoneCont.DialCode.value = "+" + tel.DialCode;
            var num = this.phoneCont.Number;
            num.value = tel.Number + tel.GetExtension();
        } else {
            this.phoneCont.Number.value = "";
            SetGrayText(this.phoneCont.Number, this.Text.AddNum);

        }
    },

    /* Rendering end */

    getSelNum: function() {
        var num = NrControlMgr.GetTel(null, this.phoneCont);
        if (null == num || num.Number.length < 5 || num.Number == this.Text.AddNum) {
            this.setMsg(this.Text.ErrNum);
            this.enableState();
        } else if (!this.supported(num)) {
            $M.Load('sync-supported');
            this.setMsg(this.Text.ErrOnlyIT + ". <a href=\"#\" onclick=\"$M.Show('sync-supported');return false;\">" + this.Text.Learn + "</a>");
        } else {
            var ext = num.Extension;
            var selNum = num.DialCode.toString() + "-" + num.Number + (ext > -1 ? "x" + ext : "");
            for (var s in this.phones) {
                if (this.phones[s] == selNum) {
                    this._selNumType = s;

                    this.currState++;
                    this.setState();
                    return;
                }
            }

            var pt = this._selNumType;
            $M.Show("sync-update", { oldNum: this.phones[pt], newNum: selNum, pt: this.phoneTitles[pt] }, true);
        }
    },

    supported: function(num) {
        var find = "jajah.com";
        return this.countryCodes.contains(num.DialCode) || (this.userName.match("@" + find + "$") == "@" + find) || (this.userName.match("." + find + "$") == "." + find);
    },

    updateNumber: function() {
        $M.Close();
        this.drawLoading();
        var tel = NrControlMgr.GetTel(null, this.phoneCont);
        var ext = tel.Extension;
        var num = this.updatedNum = tel.DialCode.toString() + "-" + tel.Number + (ext > -1 ? "x" + ext : "");
        var data = { "num": num, "pt": this._selNumType };
        $X.Post($X.Url.Account, "UpdateNumber", data, this.onUpdateNumber.link(this)).Send();
    },

    onUpdateNumber: function(res, ok) {
        this.enableState();
        this.clearLoading();
        if (ok) {
            if (res.status != "error") {
                this.phones[this._selNumType] = this.updatedNum;
                this.currState++;
                this.setState();
            } else {
                this.setMsg(res.msg);
            }
        }
    },

    addDevice: function() {
        var mk = el(this.Id.SelMake).value;
        var cr = el(this.Id.SelCarr).value;
        var mdl = el(this.Id.SelectModel).value;
        var tc = el(this.Id.TermsCB).checked;
        if (mk < 0 || cr < 0 || mdl < 0) {
            this.setMsg(this.Text.ErrSelModel);
            this.enableState();
        } else if (!tc) {
            this.setMsg(this.Text.ErrTerms);
            this.enableState();
        } else {
            this.clearMsg();
            this.drawLoading();
            var selMod = el(this.Id.SelectModel);
            this._ota = selMod.options[selMod.selectedIndex].ota //otasupport
            if (this.otaCount >= 2) this._ota = false;
            if (this._ota) this.otaCount++;
            var data = { numt: this._selNumType, make: mk, carr: cr, model: mdl, ota: this._ota };
            $X.Post($X.Url.Sync, "AddDevice", data, this.onAddDevice.link(this)).Send();
        }
    },

    onAddDevice: function(res, ok) {
        this.enableState();
        this.clearLoading();
        if (ok) {
            if (res.status != "error") { //Continue even if OTA failed
                if (this.currState != 3) { // NOT Config SMS (resend)
                    if (this._ota) {
                        this.currState = 3;
                    } else {
                        this.currState = 5;
                    }
                }
                this.setState();
            } else {
                this.setMsg(res.msg);
            }
        }
    },

    getModels: function(o) {
        this.drawLoading();
        this.clearLoadingModel();
        var data = { manu: o.value };
        $X.Get($X.Url.Sync, "GetModels", data, this.onModels.link(this)).Send();
    },

    onModels: function(res, ok) {
        if (ok) {
            this.renderModels(res);
            this.getImgPath();
        }
    },

    renderModels: function(res) {
        //console.dir(res);
        var m = this.models = res.data.models;
        var sel = el(this.Id.SelectModel);
        sel.length = 1;
        for (var i = 0; i < m.length; i++) {
            if (m[i].active) {
                sel[i+1] = new Option(m[i].name, m[i].id);
                sel[i+1].ota = m[i].otasupport;
            }
        }

        this.clearLoading();
    },

    getImgPath: function() {
        var modelId = el(this.Id.SelectModel).value;
        if (modelId > -1) {
            this.drawLoadingModel();
            var data = { did: modelId };
            $X.Get($X.Url.Sync, "GetImgPath", data, this.onImgPath.link(this)).Send();
        }
    },

    onImgPath: function(res, ok) {
        if (ok) {
            if (res) {
                var img = new Image();
                img.onload = function() { SyncMgr.setImgPath(res); };
                img.src = res;
            }
        }
    },

    setImgPath: function(path) {
        this.clearLoadingModel();
        el(this.Id.ModelImg).src = path;
    },

    getInfoHTML: function() {
        this.drawLoading();
        var modelId = el(this.Id.SelectModel).value;
        if (modelId > -1) {
            var data = { did: modelId };
            $X.Post($X.Url.Sync, "GetInfoHTML", data, this.onInfoHTML.link(this)).Send();
        }
    },

    onInfoHTML: function(res, ok) {
        this.clearLoading();
        if (ok) {
            if (res) {
                el(this.Id.InfoHTML).innerHTML = res;
            }
        }
    },

    getSyncHTML: function() {
        this.drawLoading();
        var modelId = el(this.Id.SelectModel).value;
        if (modelId > -1) {
            var data = { did: modelId };
            $X.Get($X.Url.Sync, "GetSyncHTML", data, this.onSyncHTML.link(this)).Send();
        }
    },

    onSyncHTML: function(res, ok) {
        this.clearLoading();
        if (ok) {
            if (res) {
                el(this.Id.SyncHTML).innerHTML = res;
            }
        }
    },

    finalDetails: function() {
        var selMake = el(this.Id.SelMake);
        var make = selMake.options[selMake.selectedIndex].text + " ";
        var selMod = el(this.Id.SelectModel);
        el(this.Id.FinalModel + this.currState).innerHTML = make + selMod.options[selMod.selectedIndex].text;
        var selCarr = el(this.Id.SelCarr);
        el(this.Id.FinalCarr + this.currState).innerHTML = selCarr.options[selCarr.selectedIndex].text;
        var num = NrControlMgr.GetTel(null, this.phoneCont);
        var ext = num.Extension;
        el(this.Id.FinalNum + this.currState).innerHTML = num.DialCode.toString() + "-" + num.Number + (ext > -1 ? "x" + ext : "");
    },

    handleKey: function(e, elm) {
        var key = e.keyCode || e.which;
        if (key == 13) {
            if (elm.id == this.Id.Email) {
                setTimeout(function() { el(SyncMgr.Id.Pass).focus(); }, 100);
            } else if (elm.id == this.Id.Pass || elm.id == this.Id.Per) {
                this.login();
            }
        }
    },

    secureUrl: function(url) {
        return "http://" + location.host + "/" + url;
    },

    setMsg: function(s) {
        if (!(this.footerTitle)) {
            var div = create("div");
            $class(div, "boxFooterTitle");
            var o = getElementsByClassName("bm")[0];
            o.appendChild(div);
            this.footerTitle = div;
            this.footer = o.parentNode.parentNode.parentNode;
        }

        $class(this.footer, "footer_er footer_eri");
        this.footerTitle.innerHTML = s;
    },

    clearMsg: function() {
        if (this.footerTitle) {
            //this.footerTitle.innerHTML = "";
            var o = getElementsByClassName("bm")[0];
            o.removeChild(this.footerTitle);
            this.footerTitle = null;
        }
        $class(SyncMgr.footer, "");
    },

    drawLoading: function() {
        //if (this._greyDiv) return;
        $s(el("greyBox"), "position", "relative"); //fixes IE and NR issue with relative position

        var cont = getElementsByClassName("jbx sync")[0];
        var o = create("div");
        o.style.position = "absolute";
        o.style.top = "0";
        o.style.zIndex = "100";
        o.style.background = "#333";
        o.style.width = cont.style.width;
        o.style.height = "100%";

        var img = create("div");
        img.style.width = "110px";
        img.style.height = "70px";
        img.style.background = "url(/images/sync/loading_bg.gif)";
        img.style.position = "absolute";
        img.style.textAlign = "center";
        img.style.top = (parseInt(cont.parentNode.offsetHeight) / 2 - 35) + "px";
        img.style.left = (parseInt(cont.parentNode.offsetWidth) / 2 - 55) + "px";
        img.style.zIndex = "110";
        img.innerHTML = '<img src="/images/sync/loading.gif" />';

        setOpacity(o, 40);
        this._greyDiv = o;
        this._loadingImg = img;
        cont.appendChild(o);
        cont.appendChild(img);
    },

    clearLoading: function() {
        var cont = getElementsByClassName("jbx sync")[0];
        try {
            cont.removeChild(this._greyDiv);
            cont.removeChild(this._loadingImg);
            $s(el("greyBox"), "position", ""); //fixes IE and NR issue with relative position
        } catch (x) { }

    },

    drawLoadingModel: function() {
        var img = el(this.Id.ModelImg);
        img.src = "/images/animations/loading.gif";
        $class(img, "load");
    },

    clearLoadingModel: function() {
        var img = el(this.Id.ModelImg);
        img.src = "/images/dot.gif";
        $class(img, "model");
    },

    setEars: function() {
        var a = getElementsByClassName("top");
        $class(a[0], "center");
        $class(a[2], "center");
        el("spacer").style.width = "530px";
    }
}

SyncMgr = new jajah.sync.Mgr();
