﻿var MCView = function(controller,lang){
    var E = Eanyee,D = Eanyee.Dom,me = this;
    this.controller = controller;
    this.lang = lang;
    this.div = document.getElementById("MCDiv");
    this.div.style.position = "absolute";
    this.box = document.getElementById("MCBox");
    this.mask = document.getElementById("MCMask");
    this.ctn = document.getElementById("MCCtn");
    this.loader = document.getElementById("MCLoader");
    this.mcform = document.getElementById("MCForm");
    this.tb = document.getElementById("MCTable");
    this.tbody = document.getElementById("MCTBody");
    this.processDiv = document.getElementById("MCProcessDiv");
    this.processText = document.getElementById("MCProcessDetailsDiv");
    this.processCtn = document.getElementById("MCProcessCtn");
    this.processDone = document.getElementById("MCProcessDone");
    this.processNumber = document.getElementById("MCProcessNumber");
    this.ckAutoCreate = document.getElementById("ckAutoCreateLP");
    this.ckReload = document.getElementById("ckReload");
    this.reloadDiv = document.getElementById("reloadWiseLine");
    
    var baseUrl = this.controller.baseUrl,
        blankUrl= baseUrl + "/mediacenter/valid_blank.gif",
        validUrl = baseUrl + "/images/sign_right.gif",
        novalidUrl = baseUrl + "/images/sign_wrong.gif";
        
    //this.abort = document.getElementById("MCAbort");
    this._currentOp = 0, this._opTick, this._visible;
   
    D.addEvent(this.ckAutoCreate,"click",function(){
       me.reloadDiv.style.visibility =(me.ckAutoCreate.checked)?"visible":"hidden";
    });
    D.addEvent(document.getElementById("MCCloseBtn"),"click",function(){
        me.Hide();
    });
    
     
    D.addEvent(document.getElementById("MCReturn"),"click",function(){
        me.ImportVisible('config');
    });
    D.addEvent(document.getElementById("MCAbort"),"click",function(){
        if (me.controller.status==='importing'){
            if (!confirm("You are in the process of importing,are you sure to abort?")) return;
        }
        //me.ProcessError("Importing process is aborted.");
        me.controller.abort();
        
        me.importComplete();
    });
    
    this.showInProcess = function(){}
    
    this.showAbortOrReturn = function(v){
        if (v==='return'){
            document.getElementById("MCAbort").style.display = "none";
            document.getElementById("MCReturn").style.display = "";
        }else{
            document.getElementById("MCAbort").style.display = "";
            document.getElementById("MCReturn").style.display = "none";
        }
    }
    
    
    this.importComplete = function(importCount){
       
        if (me.ckReload.checked){
            me.ImportVisible('config');
            me.Hide(true);
            if (importCount){
                if (me._status==='hidden' || me._status==='hidding'){
                   //if (!confirm("Importing Complete,do you want to reload WiseLine?")) return false;
                }
                 if (navigator.userAgent.indexOf("MSIE")>=0){
	                window.location.reload();
	                return;
	            }
	            var _flash = document.getElementById("Flash");
	            var html = _flash.innerHTML;
	            setTimeout(function(){
	                _flash.innerHTML = html;
	            },100);
            }
        }else{
            if (importCount===undefined)  me.ProcessError("Imports abort!");
            else me.ProcessError(this.controller.lang.ImportComplete,100);
            this.showAbortOrReturn('return');
        }
    }
    
    this._Mask = function(){
        var me = this,msk = me.mask;
        var w =Math.max(document.body.offsetWidth,document.documentElement.offsetWidth);
        var h = Math.max(document.body.offsetHeight,document.documentElement.offsetHeight);
        msk.style.width = w + "px";
        msk.style.height = h + "px";
        msk.style.zIndex = 999;
    }
    var center = function(el){
        var x = document.body.scrollLeft +  (document.documentElement.clientWidth - el.offsetWidth)/2 ;
        var y = document.body.scrollTop +  (document.documentElement.clientHeight - el.offsetHeight)/2 ;
        el.style.left = x + "px";
        el.style.top = y + "px";
    }
    var centerPa = function(el){
        var pa = el.offsetParent;
        el.style.position = "absolute";
        el.style.left = pa.scrollLeft + (pa.clientWidth - el.offsetWidth) /2 + "px";
        el.style.top = pa.scrollTop + (pa.clientHeight - el.offsetHeight) /2 + "px";
    }
    var tryShowLoader = function(){
        if (me.loader){
            centerPa(me.loader);
            if (me.controller.status==='initing') return true;
            me.controller.initialize();
            return true;
        }
        return false;
    }
    this.initComplete = function(accounts,configs){
        if (accounts==null || configs == null) return;
        me.buildForm(accounts,configs);
        me.loader.parentNode.removeChild(me.loader);
        me.loader = undefined;
        me.ctn.style.display = "";        
    }
    this.account_Els =  this.remember_Els = this.webSites_Els = {};
    this.buildForm = function(accounts,configs){
        var tb = this.tbody,len = tb.rows.length;
        var account_Els = this.account_Els = {},
            remember_Els = this.remember_Els = {},
            webSites_Els = this.webSites_Els = {};
        //clear the tbody
        for(var i=0;i<len;i++) this.tbody.removeChild(this.tbody.rows[0]);
        for(var networkId in configs){
            var network = configs[networkId];
            var acount = accounts[networkId] || {};
            var row = document.createElement("tr");
            //build the media logo image
            var td = document.createElement("td");
            var img = document.createElement("img");
            img.src =  network.LogoUrl;img.border = 0;img.alt = network.Name;
            td.appendChild(img);row.appendChild(td);
            //build the media account and validate result icon
            var td = document.createElement("td");
            var span = document.createElement("span");
            span.innerHTML = this.controller.lang.Username;
            td.appendChild(span);row.appendChild(td);
            var td = document.createElement("td");
            var txt = document.createElement("input");
            account_Els[networkId] = txt;
            txt.value = acount.NetworkUserName || "";
            var valid = document.createElement("img");
            valid.style.width = valid.style.height = "20px";
            valid.src = blankUrl;
            td.appendChild(txt);td.appendChild(valid);row.appendChild(td);
            var validFunc = MCenter.AccountValidates[networkId];
            if (validFunc)D.addEvent(txt,'blur',(function(valid,txt,validFunc){
                return function(evt){
                    var acnt = txt.value.trim();
                    if (acnt==""){}
                    else {
                        validFunc(acnt,function(v,context){
                            if (v==null){
                                if (context.ERROR){
                                    valid.src = novalidUrl;
                                    valid.title = "the connect is not avalible";
                                }else{
                                      valid.src = novalidUrl;
                                    valid.title = "the account is not existing";
                                }
                            }else{
                                valid.src = validUrl;
                                valid.title = "";
                            }
                        });
                    }
                }
            })(valid,txt,validFunc));
            
            var td = document.createElement("td");
            var remember = document.createElement("input");
            remember_Els[networkId] = remember;
            remember.type = "checkbox";
            var span = document.createElement("span");
            //span.innerHTML = "Auto Imports";
            td.appendChild(remember);td.appendChild(span);row.appendChild(td);
            //only the account exactly tell not remember then set it not remember
            
            
            
            tb.appendChild(row);
            
            remember.checked = !(acount.Remember===false);
            var td = document.createElement("td");
            row.appendChild(td);
            var webSites = network.WebSites;
            var webs = [];
            for(var i=0;i<webSites.length;i++){
                var webSite = webSites[i];
                var webBox = document.createElement("input");
                webs.push(webBox);
                webBox.type = "checkbox";
                webBox.value = webSite.Name;
                var span = document.createElement("span");
                span.innerHTML = webSite.MediaType;
                td.appendChild(webBox);
                td.appendChild(span);
                if (acount.SupportTypes){
                    var key = "{" + webSite.Name + "}";
                    iwebBox.checked = (acount.SupportTypes.indexOf(key)>=0)?true:false;
                }else{
                    webBox.checked = (webSite.IsDefault)?true:false;
                }
                webBox.disabled = true;
                
            }
            webSites_Els[networkId] = webs;
            
            
        }
        
        D.addEvent(document.getElementById("goImports"),"click",function(){
            me.adjecentAccount(accounts,configs);
        });
        
        var autoCreateLp = me.ckAutoCreate;
        if (accounts.AutoCreateLifePiece === false) autoCreateLp.checked = false;else autoCreateLp.checked = true;
        //me.reloadDiv.style.visibility =(autoCreateLp.checked)?"visible":"hidden";
        
    }
    this.adjecentAccount = function(accounts,configs){
        accounts.AutoCreateLifePiece = this.ckAutoCreate.checked;
        for(var networkId in configs){
           var acntForNet = accounts[networkId];
            if (!acntForNet) accounts[networkId] = acntForNet = {};
            acntForNet.NetWorkUserName = this.account_Els[networkId].value.trim();
            
            var webs = this.webSites_Els[networkId];
            var temp = [];
            for(var i=0;i<webs.length;i++){
                var ck = webs[i];
                if (!ck.checked) continue;
                temp.push("{" + ck.value + "}");
            }
            acntForNet.SupportTypes = temp.join(",");
            
            acntForNet.Remember = this.remember_Els[networkId].checked;
            
        }//end for in configs
        me.controller.saveSetting(accounts);
    }
    
    this.Show = function(){
        //if the View's status is showing
        // meaning that view is in the process of show
        //so the function should return immediately.
        if (this._status==='showing') return;
        this._status = "showing";
        var me = this,el = me.box;
        //this._opTick has a value meaning before the op , the view is in process of show or hide
        //show we stop the process and restart the show process
        if (this._opTick) clearTimeout(me._opTick);
        D.setStyle(me.div,"display","");
        // show a div mask the client area of browser, to prevent user click the other element on the page
        me._Mask();
        D.setStyle(me.mask,"zIndex","1003");
        // make the box full opacity
        D.setOpacity(el,1);
        // make the background half opacity
        D.setOpacity(me.mask,0,5);
        var w = el.offsetWidth,h = el.offsetHeight;
        center(el);
        if (!tryShowLoader()) document.getElementById("MCCtn").style.display = "";
        //total step is 10
        var step = 0;
        var temp = function(){
            step++;
            var per = step/10;
            var h1 = h *(1 - per) /2 ;
            var w1 = w*(1 - per) /2;
            // the background step to step hide
            D.setOpacity(me.mask,0.1 + 0.4*per);
            //make the box step to step bigger.
            el.style.clip = "rect(" + h1 + "px " + (w - w1) + "px " + (h-h1) + "px " + w1 + "px)";
            if (step<10){me._opTick = setTimeout(temp,20);}
            else{
                //set the mask behind the box but above all other element
                //to let user can only operate on the MC box.
                D.setStyle(me.mask,"zIndex","999");
                el.style.clip = "rect(auto auto auto auto)";
                D.setOpacity(el,1);
                if (D.Browser.isOpera){
                    el.style.visibility = "hidden";
                    me._opTick = setTimeout(function(){el.style.visibility = "visible"; center(el);me._status = "showed";},10);
                }else{
                    D.setStyle(me.mask,"zIndex","999");
                    el.style.zIndex = "1001";
                    center(el);me._status = "showed";
                }
            }
            
        }
        temp();
    }
    this.Hide = function(v){
        var me = this,el = me.box;
        //if the View's status is showing
        // meaning that view is in the process of hidden
        //so the function should return immediately.
        if (this._status==='hidding') return;
        //if the MC is hidden , do not need to run the code ,return immediately.
        if (D.getStyle(me.div , "display") == 'none') return;
        if (v===true){
            D.setStyle(me.div , "display",'none');
            if (this._opTick) clearTimeout(me._opTick);
            this._status = "hidden";
            return;
        }
        this._status = "hidding";
        
        //this._opTick has a value meaning before the op , the view is in process of show or hide
        //show we stop the process and restart the show process
        if (this._opTick) clearTimeout(me._opTick);
        
        // make the box full opacity
        D.setOpacity(el,1);
        
        var step = 0;
        var temp = function(){
            step++;
            var per = step/5;
            
            // the background step to step hide
            D.setOpacity(el,1 - step/5);
            if (step<5){me._opTick = setTimeout(temp,120);}
            else{
                me._status = "hidden";
                me.div.style.display = "none";
            }
            
        }
        temp();
    }
    
    
    
    this.Error = function(txt,breaks){
        alert(txt);
        if (breaks) this.Hide();
    }
    me.percentNumber = 0;
    this.InitProcess = function(){
        me.percentNumber = 0;
        this.processText.innerHTML = "";
        
        this.TellPercent(0);
    }
    this.ProcessError = function(txt,per,error){
        var ret;
        if (txt.tagName){
            var el = txt;
            if (!error)  el.innerHTML = el.innerHTML + "&nbsp;&nbsp;<span class='green'>completed</span>"; 
            else el.innerHTML = el.innerHTML + "&nbsp;&nbsp;<span class='red'> not completed</span>"; 
        }else{
            var el = ret = document.createElement("div");
            el.innerHTML = txt;
            me.processText.appendChild(el);
        }
        if (per!==undefined){
            if (per==100) me.percentNumber = 100;
            else me.percentNumber += per;
            me.TellPercent(me.percentNumber);
        }
        return ret;
    }
    this.TellPercent = function(num){
        if (isNaN(num)){
            return;
        }
        this.processNumber.innerHTML = num + "%";
        this.processDone.style.width = (num * this.processCtn.clientWidth)/100  + "px";
    }
    this.ImportVisible = function(v){
        var mcForm = me.mcform;
        if (v===false){ mcForm.style.display = "none"; return;}
        //me.form.style.display = "";
        if (v=='process'){
            mcForm.style.display = "none";
            me.processDiv.style.display = "";
        }else{
             me.mcform.style.display = "";
             
            me.processDiv.style.display = "none";
        }
        
    }
}
