

SaveSettings = function(email, din, pc, sp, agree, hasdin, userid, fname, lname, cname) {
    if(window.Cookie) {
        var lit = { 
            email : email,
            din : din,
            pc : pc,
            sp : sp,
            agree : agree + "",
            hasdin : hasdin + "",
            userid : userid + "",
            fname : fname,
            lname : lname,
            cname : cname
        };
        
        //Cookie.CreateLiteral("instantconference-widget", lit, 365);
    }
};

LoadSettings = function() {
var email = "", din = "", pc = "", sp = "", agree = "0.0", hasdin = "", userid = "", fname = "", lname = "", cname = "";
    
    //pull information from querystring
    email = _("email", "undefined");
	din = _("din", "undefined");
	pc = _("pc", "undefined");
	sp = _("sp", "undefined");
	agree = _("agree", "undefined");
	hasdin = _("hasdin", "undefined");
	userid = _("userid", "undefined");
	fname = _("fname", "undefined");
	lname = _("lname", "undefined");
	cname = _("cname", "undefined");
	
	//pull information not in querystring from cookie
	if(window.Cookie)
	{
		lit = null; //Cookie.LoadLiteral("instantconference-widget");
		if(lit != null)
		{
		    /* load settings */
		    email = email == "undefined" ? lit.email : email;
		    din = din == "undefined" ? lit.din : din;
		    pc = pc == "undefined" ? lit.pc : pc;
		    sp = sp == "undefined" ? lit.sp : sp;
		    agree = agree == "undefined" ? lit.agree : agree;
		    hasdin = hasdin == "undefined" ? lit.hasdin : hasdin;
		    userid = userid == "undefined" ? lit.userid : userid;
		    fname = agree == "undefined" ? lit.fname : fname;
		    lname = hasdin == "undefined" ? lit.lname : lname;
		    cname = userid == "undefined" ? lit.cname : cname;
		}
	} 

	//default the values;
	if(!email || email == "undefined") email = "";
	if(!din || din == "undefined") din = "";
	if(!pc || pc == "undefined") pc = "";
	if(!sp || sp == "undefined") sp = "";
	if(!agree || agree == "undefined") agree = "0";
	if(!hasdin || hasdin == "undefined") hasdin = "";
	if(!userid || userid == "undefined") userid = "";
	if(!fname || fname == "undefined") fname = "";
	if(!lname || lname == "undefined") lname = "";
	if(!cname || cname == "undefined") cname = "";
	
	return { Email : email, DIN : din, PC : pc, SP: sp, Agree : agree, HasDIN : (hasdin == "true"), UserId : userid, FN : fname, LN : lname, CN : cname};
};

setup = function() {
    if($("device") != null) {
        if (QuickConference.QueryString.length > 0)
            window.QueryString = _LoadFromNVP(QuickConference.QueryString);
        
        var settings = LoadSettings();
    	
	    if(window.QuickConference) //make sure they are connected.
	    {
	        QuickConference.ExecutionMode = QuickConference.ExecutionModes.Browser;
    	    
	        var device 
	        if(_("start") != null)
	            device = new DeviceUI(settings, _("start"));
	        else
	            device = new DeviceUI(settings);
    	    
    	    
	        document.onkeyup = Bind(device, function(k) { 
	            if(!k) k = window.event;
	            if(k.keyCode == 13)
	                if(this._onenter)
	                    this._onenter();
	        });
	        
	        return device;
        }
    }
};

Screen = function(screenId, OnShow) {
    this._elements = Array ( exId(screenId) );
    this._OnShow = OnShow;
};

Screen.prototype.Show = function() {
    for(var i = 0; i < this._elements.length; i++)
        this._elements[i].style.display = "";
    this._OnShow();
};

Screen.prototype.Hide = function() {
    for(var i = 0; i < this._elements.length; i++)
        this._elements[i].style.display = "none";
};

StarKey = function(id) {
    this._element = exId(id);
    this._pulse = {
        on : $(id).src, //"btn-starkey_Arrows.gif",
        off : $(id).src, //"btn-starkey_Arrows.gif",
        cursor : 'hand'
    };
    this._enabled = {
        on : "images/ProAlliance/btn-starkey-on.gif",
        off : "images/ProAlliance/btn-starkey-off.gif",
        cursor : 'hand'
    };
    this._disabled = {
        on : "images/ProAlliance/btn-starkey-disabled.gif",
        off : "images/ProAlliance/btn-starkey-disabled.gif",
        cursor : 'default'
    }
};

StarKey.prototype.Enable = function(ptr) {
    this._element.onclick = ptr;
    this._element.style.cursor = 'pointer';
    this._element.style.display = "";
    //this._SetImages(this._enabled);
};

StarKey.prototype.Disable = function() {
    this._element.onclick = nothing;
    this._element.style.cursor = 'auto';
    this._element.style.display = "none";
    //this._SetImages(this._disabled);
};

StarKey.prototype.EnablePulse = function(ptr) {
    this._element.style.cursor = 'pointer';
    this._element.onclick = ptr;
    this._element.style.display = "";
    //this._SetImages(this._pulse);
};

StarKey.prototype._SetImages = function(settings) {
    var on = settings.on;
    var off = settings.off;
    this._element.src = off;
    this._element.style.cursor = settings.cursor;
    if (off != on)
        MakeRollOverImage(this._element, on, off);
    else {
        this._element.onmouseover = nothing;
        this._element.onmouseout = nothing;
    }
}

DeviceUI = function(settings, start_) {
    this._star = new StarKey("starkey");
    this._settings = settings;
    this._numAccounts = 0;
    this._showAfter = new Date();
    
    this._vchecks = Array ( "", "Email Address", "First Name", "Last Name", "Company" );

    this._starClick = Bind(this, function() { this._star._element.onclick(); });
    this._screens = {
        email : new Screen( 
            "emailScreen",
            Bind(this, function() { 
                this._email = exId("lcdemail");
                this._fname = $("lcdfname");
                this._lname = $("lcdlname");
                this._cname = $("lcdcname");
                
                this._email.onfocus = Bind(this, function() { if(this._email.value == this._vchecks[1]) this._email.value = ""; });
                this._fname.onfocus = Bind(this, function() { if(this._fname.value == this._vchecks[2]) this._fname.value = ""; });
                this._lname.onfocus = Bind(this, function() { if(this._lname.value == this._vchecks[3]) this._lname.value = ""; });
                this._cname.onfocus = Bind(this, function() { if(this._cname.value == this._vchecks[4]) this._cname.value = ""; });
                
                this._email.onblur = Bind(this, function() { if(this._email.value == "") this._email.value = this._vchecks[1]; });
                this._fname.onblur = Bind(this, function() { if(this._fname.value == "") this._fname.value = this._vchecks[2]; });
                this._lname.onblur = Bind(this, function() { if(this._lname.value == "") this._lname.value = this._vchecks[3]; });
                this._cname.onblur = Bind(this, function() { if(this._cname.value == "") this._cname.value = this._vchecks[4]; });
                
                this._email.value = this._settings.Email.length > 0 ? this._settings.Email : this._vchecks[1];
                this._fname.value = this._settings.FN.length > 0 ? this._settings.FN : this._vchecks[2];
                this._lname.value = this._settings.LN.length > 0 ? this._settings.LN : this._vchecks[3];
                this._cname.value = this._settings.CN.length > 0 ? this._settings.CN : this._vchecks[4];

                this._star.EnablePulse( Bind(this, this.SaveInputs) ); 
                this._onenter = this._starClick;
            })),
        /*terms : new Screen(
            "termsScreen",
            Bind(this, function() { 
                ShowTerms = Bind(this, function() {
                    this._onenter = nothing;
                    seTrack("ShowTerms");
                    _ShowTerms();
                });
                
                HideHaze = Bind(this, function() {
                    this._onenter = this._starClick;
                    _HideTerms();
                });
            
                $("termsAccept").onclick = Bind(this, function() { HideHaze(); this._star._element.onclick(); });
                this._star.EnablePulse( Bind(this, this.CreateIfNew) ); 
                this._onenter = this._starClick;
            })),*/
        processing : new Screen(
            "processingScreen",
            Bind(this, function() { 
                var src = exId("processingimg").src;
                /*exId("processingimg").src = src + "q";*/
                this._star.Disable();
                var dt = new Date();
                /*dt.AddMilliseconds(2000);*/
                /*this._showAfter = dt;*/
                this._onenter = nothing;
            })),
        invalid : new Screen (
            "invalidEmailScreen", 
            Bind(this, function() { 
                this._email = exId("lcdemail2");
                this._fname = $("lcdfname2");
                this._lname = $("lcdlname2");
                this._cname = $("lcdcname2");
                
                /*this._fname.focus();*/
                
                this._email.onfocus = Bind(this, function() { if(this._email.value == this._vchecks[1]) this._email.value = ""; });
                this._fname.onfocus = Bind(this, function() { if(this._fname.value == this._vchecks[2]) this._fname.value = ""; });
                this._lname.onfocus = Bind(this, function() { if(this._lname.value == this._vchecks[3]) this._lname.value = ""; });
                this._cname.onfocus = Bind(this, function() { if(this._cname.value == this._vchecks[4]) this._cname.value = ""; });
                
                this._email.onblur = Bind(this, function() { if(this._email.value == "") this._email.value = this._vchecks[1]; });
                this._fname.onblur = Bind(this, function() { if(this._fname.value == "") this._fname.value = this._vchecks[2]; });
                this._lname.onblur = Bind(this, function() { if(this._lname.value == "") this._lname.value = this._vchecks[3]; });
                this._cname.onblur = Bind(this, function() { if(this._cname.value == "") this._cname.value = this._vchecks[4]; });
                
                this._email.value = this._settings.Email.length > 0 ? this._settings.Email : this._vchecks[1];
                this._fname.value = this._settings.FN.length > 0 ? this._settings.FN : this._vchecks[2];
                this._lname.value = this._settings.LN.length > 0 ? this._settings.LN : this._vchecks[3];
                this._cname.value = this._settings.CN.length > 0 ? this._settings.CN : this._vchecks[4];
                
                this._star.EnablePulse( Bind(this, this.SaveInputs) ); 
                this._onenter = this._starClick;
            })),
        dup : new Screen(
            "dupEmailScreen", 
            Bind(this, function() { 
                this._star.Disable(); 
                exId("newnumber").onclick = Bind(this, this.CreateSubAccount);
                exId("emailinfo").onclick = Bind(this, this.SendSummary);
                this._onenter = nothing;
            })),            
        sent : new Screen( 
            "emailSentScreen",
            Bind(this, function() { 
                this._star.Disable(); //Enable( Bind(this, this.Reset) );  
                this._onenter = nothing;
            })),            
        info : new Screen(
            "infoScreen",
            Bind(this, function() { 
                exId("lcdphone").replaceChild(document.createTextNode(this._settings.DIN), exId("lcdphone").firstChild);
                exId("lcdpasscode").replaceChild(document.createTextNode(this._settings.PC), exId("lcdpasscode").firstChild);                
                if(document.getElementById("lcdorg") != null)
                    exId("lcdorg").replaceChild(document.createTextNode(this._settings.SP), exId("lcdorg").firstChild);                
                if(this._numAccounts > QuickConference.MaxAccounts)
                    exId("spanAddAnother1").style.display = "none";
                    
                exId("addAnother1").onclick = Bind(this, function() { this.ShowScreen("confirm"); });
                this._star.Disable(); //Enable( Bind(this, this.Reset) ); 
                this._onenter = nothing;
            })),
        returning : new Screen(
            "returningScreen",
            Bind(this, function() { 
                exId("lcdphone2").replaceChild(document.createTextNode(this._settings.DIN), exId("lcdphone2").firstChild);
                exId("lcdpasscode2").replaceChild(document.createTextNode(this._settings.PC), exId("lcdpasscode2").firstChild);
                if(document.getElementById("lcdorg2") != null)
                    exId("lcdorg2").replaceChild(document.createTextNode(this._settings.SP), exId("lcdorg2").firstChild);                
                if(this._numAccounts > QuickConference.MaxAccounts)
                    exId("spanAddAnother2").style.display = "none";
                    
                exId("addAnother2").onclick = Bind(this, function() { this.ShowScreen("confirm"); });
                this._star.Disable(); //Enable( Bind(this, this.Reset) ); 
                this._onenter = nothing;
            })),
        subInfo : new Screen(
            "subInfoScreen",
            Bind(this, function() { 
                exId("lcdphone3").replaceChild(document.createTextNode(this._settings.DIN), exId("lcdphone3").firstChild);
                exId("lcdpasscode3").replaceChild(document.createTextNode(this._settings.PC), exId("lcdpasscode3").firstChild);
                if(document.getElementById("lcdorg3") != null)
                    exId("lcdorg3").replaceChild(document.createTextNode(this._settings.SP), exId("lcdorg3").firstChild);                
                if(this._numAccounts > QuickConference.MaxAccounts)
                    exId("spanAddAnother3").style.display = "none";
                    
                exId("addAnother3").onclick = Bind(this, function() { this.ShowScreen("confirm"); });
                this._star.Disable(); //.Enable( Bind(this, this.Reset) ); 
                this._onenter = nothing;
            })), 
        confirm : new Screen(
            "confirmScreen", 
            Bind(this, function() { 
                this._star.Disable(); 
                exId("confirmLink").onclick = Bind(this, this.CreateSubAccount);
                exId("cancelLink").onclick = Bind(this, function() { this.ShowScreen("returning"); });
                this._onenter = nothing;
            })), 
        error : new Screen(
            "errorScreen", 
            Bind(this, function() { 
                this._star.Disable(); //Enable( Bind(this, this.Reset) );  
                this._onenter = nothing;
            }))         
    };
    if(start_)
        this.ShowScreen(start_);
    else
        this.ShowCurrent();
};

DeviceUI.prototype.SaveSettings = function() {
    SaveSettings(
        this._settings.Email, 
        this._settings.DIN, 
        this._settings.PC, 
        this._settings.Agree, 
        this._settings.HasDIN, 
        this._settings.UserId,
        this._settings.SP,
        this._settings.FN,
        this._settings.LN,
        this._settings.CN
    );
};

DeviceUI.prototype.ShowCurrent = function() {
    
    if(this._settings.HasDIN)
        this.ShowScreen("returning");
    else {
        this._settings.Agree = false;
        this.ShowScreen("email");
        /*
        
        this._settings.DIN = "1 (818) 730-9970";
        this._settings.PC = "123456";
        this._settings.SP = "9876";
        
        
        this.ShowScreen("email");*/
    }
};

DeviceUI.prototype.Reset = function() {
    window.QueryString = { };
    this._settings = LoadSettings();
    
    this.ShowCurrent();
};
//utility function to search an array for an item
var contains = function(check, list) {
    for(var i = 0; i < list.length; i++)
        if(list[i] == check)
            return true;
    return false;
}

DeviceUI.prototype.SaveInputs = function() {
    this._settings.Email = this._email.value;
    this._settings.FN = this._fname.value;
    this._settings.LN = this._lname.value;
    this._settings.CN = this._cname.value;
    this._settings.Agree = true;
    
    this.SaveSettings();
    
    $("inv_fn").style.display = "none";
    $("inv_ln").style.display = "none";
    $("inv_em").style.display = "none";
    $("inv_cn").style.display = "none";
    
    if(contains(this._settings.FN, this._vchecks)) {
        $("inv_fn").style.display = "";
        this.ShowScreen("invalid");
        $("lcdfname2").focus();
        $("lcdfname2").select();
    } else if (contains(this._settings.LN, this._vchecks)) {
        $("inv_ln").style.display = "";
        this.ShowScreen("invalid");
        $("lcdlname2").focus();
        $("lcdlname2").select();
    } else if (contains(this._settings.Email, this._vchecks) || !IsEmail(this._settings.Email)) {
        $("inv_em").style.display = "";
        this.ShowScreen("invalid");
        $("lcdemail2").focus();
        $("lcdemail2").select();
    } /*else if(contains(this._settings.CN, this._vchecks)) {
        $("inv_cn").style.display = "";
        this.ShowScreen("invalid");
        $("lcdcname2").focus();
        $("lcdcname2").select();
    }*/
    else if(!this._settings.Agree)
        this.ShowScreen("terms");
    else
        this.CreateIfNew();
};

DeviceUI.prototype.CreateIfNew = function() {
    this.ShowScreen("processing");
    this._settings.Agree = true;
    this.SaveSettings();
    
    if(!IsEmail(this._settings.Email))
        this.ShowScreen("invalid");
    else {
        QuickConference.NewUser(
            this._settings.Email,
            this._settings.FN,
            this._settings.LN,
            contains(this._settings.CN, this._vchecks) ? "" : this._settings.CN,
            true,
            true,
            false,
            Bind(this, this.HandleNewUserResponse)
        );
    }
};

DeviceUI.prototype.CreateSubAccount = function() {
    this.ShowScreen("processing");
    if(!IsEmail(this._settings.Email))
        this.ShowScreen("invalid");
    else {
        QuickConference.NewSubAccount(
            this._settings.Email,
            Bind(this, this.HandleNewUserResponse)
        );
    }
};

DeviceUI.prototype.SendSummary = function() {
    this.ShowScreen("processing");
    
    QuickConference.SendSummary(this._settings.Email, Bind(this, function(results) { 
        if(results.Code == QuickConference.ResultCodes.Success)
            this.ShowScreen("sent");
        else {
            //exId("lcderror").replaceChild(document.createTextNode(results.Message), exId("lcderror").firstChild);
            this.ShowScreen("error");
        }
    }));
};

DeviceUI.prototype.ShowScreen = function(screenName) {
    var dt = new Date();
    if(this._showAfter > dt)
    {
        delta = this._showAfter.getTime() - dt.getTime();
        setTimeout(Bind(this, function() { this.ShowScreen(screenName); }), delta);
    }
    else {
        seTrack(screenName);
        for(var obj in this._screens)
            this._screens[obj].Hide();
        
        this._screens[screenName].Show();
    }
}

DeviceUI.prototype.HandleNewUserResponse = function(results) {
    switch(results.Code)
    {
        case QuickConference.ResultCodes.Success: //success
            
            if(results.FormattedDialInNumber) //support for backward compatibility
                this._settings.DIN = results.FormattedDialInNumber;
            else { //support for multiple dial in numbers being sent
                var cnt = parseInt(results.DialInNumber_Count);
                
                if(cnt > 0) {
                    for(var i = 0; i < cnt; i++)
                        if( results["DialInNumber" + i.toString() + "_Type"] == "Toll" )
                        {
                            this._settings.DIN = results["DialInNumber" + i.toString() + "_FormattedNumber"];
                            break;
                        }
                } else //the type is irrelevant here, we need to show whatever they gave us
                    this._settings.DIN = results["DialInNumber0_FormattedNumber"];
            }
            this._settings.PC = results.AccessCode;
            this._settings.SP = results.SubscriberPIN;
            this._settings.UserId = results.UserId;
            this._settings.SubAccountId = results.SubAccountId;
            this._settings.HasDIN = true;
            this._numAccounts++;
            this.SaveSettings();
            if(results.Type == "NewSubAccount") {
                seTrackSubInfoConversion(this._settings.UserId, GenerateTrackingPageName("subInfo"));
                this.ShowScreen("subInfo");
            } else {
                seTrackConversion(this._settings.UserId, GenerateTrackingPageName("info"));
                this.ShowScreen("info");
            }
            break;
        case QuickConference.ResultCodes.UserExists:
            this.ShowScreen("dup");
            break;
        case QuickConference.ResultCodes.InvalidEmail:
            this.ShowScreen("invalid");
            break;
        case QuickConference.ResultCodes.Undefined:
        case QuickConference.ResultCodes.InternalError:
        default:
            //exId("lcderror").replaceChild(document.createTextNode(results.Message), exId("lcderror").firstChild);
            this.ShowScreen("error");
            break;
    }

};

function IsEmail(test)
{
    return (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,4})+$/.test(test))
}

function ShowTerms() {
    _ShowTerms();
}

function _ShowTerms() {
    $("termsContainer").style.display = "";
    $("haze").style.display = "";
}

function _HideTerms() {
    $("termsContainer").style.display = "none";
    $("haze").style.display = "none";
}

function DeclineTerms() {
    seTrack("DeclineTerms");
    _HideTerms();
};

function CloseTerms() {
    seTrack("CloseTerms");
    _HideTerms();
};

function seTrack(pageName) {
    
    var sPage = GenerateTrackingPageName(pageName);
    
    //add omniture code here
   omniLogIt(sPage,document.domain);
    //google
    if(typeof(_doGoogleTracking) == "undefined") _doGoogleTracking = false;
    if(_doGoogleTracking && _doGoogleTracking == true) {
        if(urchinTracker)
            urchinTracker("/" + sPage);
    }
};

function GenerateTrackingPageName(screen)
{
    var sPath = window.location.pathname;
    var sPage = sPath.substring(sPath.lastIndexOf('/') + 1);
    sPage = (sPage == "" ? "default.aspx" : sPage).replace(".aspx", "-") + screen;
    
    return sPage;
}

function seTrackConversion(userId, pageName) {

    //only on NEW USER SIGNUP
    //alert(pageName);
    //add omniture code here
    omniLogIt(pageName, document.domain, "", "", userId, "", "", "", "", "", "", "", "event1", "", "", userId , "", "", "", "");
    //google
    if(typeof(_doGoogleTracking) == "undefined") _doGoogleTracking = false;
    if(_doGoogleTracking && _doGoogleTracking == true)
        $("GoogleConversionImage").src = "http://www.googleadservices.com/pagead/conversion/1059041627/imp.gif?value=1&label=signup&script=0";
};

function seTrackSubInfoConversion(userId, pageName) {
    //only on existing user creating sub account

    //add omniture code here
    omniLogIt(pageName, document.domain, "", "", userId, "", "", "", "", "", "", "", "event2", "", "", userId , "", "", "", "");

    //google
    if(typeof(_doGoogleTracking) == "undefined") _doGoogleTracking = false;
    if(_doGoogleTracking && _doGoogleTracking == true)
        $("GoogleConversionImage").src = "http://www.googleadservices.com/pagead/conversion/1059041627/imp.gif?value=1&label=signup&script=0";

};

function omniLogIt(pn, sr, ch, pt, p1, p2, p3, p4, p5, cm, st, zp, ev, pr, pur, ev1, ev2, ev3, ev4, ev5 ){
    if(typeof(s)!="undefined" ){
        var str = document.location.pathname.match("\\b([\\w\-\+\(\)_\%\&\;\!\~\^\.]+(?=\.aspx))\\b");
        str = str==null?"Default":str[0];
        s.pageName=pn?str+":"+pn:"";
        s.server=sr?sr:"";
        s.channel=ch?ch:"";
        s.pageType=pt?pt:"";
        s.prop1=p1?p1:"";
        s.prop2=p2?p2:"";
        s.prop3=p3?p3:"";
        s.prop4=p4?p4:"";
        s.prop5=p5?p5:"";
        /* Conversion Variables */
        //s.campaign=""
        //s.state=""
        //s.zip=""
        s.events=ev?ev:"";
        //s.products=""
        //s.purchaseID=""
        s.eVar1=ev1?ev1:"";//user-id
        //s.eVar2=""
        //s.eVar3=""
        //s.eVar4=""
        //s.eVar5=""
        void(s.t());
    }
};

