//service_modules.js //
window.addEventListener("click", function(event) 
{ 
    if (gCurrTab == 'Licenses' && licensesCurrTab.length == 0) {snugRightLicensesBar();}
    
}, false);

window.addEventListener('resize', function(event) 
{
    ww = window.innerWidth;
    hh = window.innerHeight;  
    hh_winExtra = (isMac==false?12:0);
}, true);

// ------------------------------------------------------------ //
function savePT_Order_Show()
{

	$$("btnSave_PT_Order").show();
	
}
// ------------------------------------------------------------ //
function savePT_Order()
{

	console.log('huh!!!???');
	
}
// ------------------------------------------------------------ //
function PushSystem(inData)
{
    //console.log("PushSystem:");
    gcPSData = inData;
    lcCall = gcPSData.Call;
    switch(lcCall) 
    {
        case "system_notice":
	if (gcEnv == inData.Env)
	{
	    webix.message({type: "error", text: '<b>'+inData.Notice_Type+'</b><br/><br/>'+inData.Message + '<br/><br/>', expire: 60000});
	    playSuccessSound();
	}
        break;
        
        case "system_info":
	if (gcEnv == inData.Env)
	{	
	    webix.message({type: "debug", text: '<b>'+inData.Notice_Type+'</b><br/><br/>'+inData.Message + '<br/><br/>', expire: 60000});
	    playSuccessSound();
	}
        break;        
        
        case "testing":
        console.log(inData);
        if ($('#showPush').length) {$("#showPush").append(JSON.stringify(inData)+'<br/>');}
        break;	
    }
} 
// ------------------------------------------------------------ //
function PushSession(inData)
{
    gcPXData = inData;
    lcCall = gcPXData.Call;
    console.log("PushSession:  " + lcCall);
    switch(lcCall) 
    {
	case "auto-link":
	webix.message({type: "debug", text: '<b>'+inData.Title+'</b><br/>'+inData.Message, expire: 2800});
	break;
	
	case "auto-fill":
	webix.message({type: "debug", text: '<b>'+inData.Title+'</b><br/>'+inData.Message, expire: 2800});
	try {ocnt = inData.Offset;} catch(err) {ocnt = 0;}
	if (ocnt > 0) {webix.message({type: "debug", text: '<b>Current Offset = '+ocnt+'</b>', expire: 4800});}
	break;	
	
	case "acct_msg":
        webix_message({type: "debug", text: '<b>'+inData.Title+'</b><br/>'+inData.Message, expire: 4700},10);
	
        case "messaging":
            console.log(inData);
            lcMsg = '';
            // events must match this current msg id
            if (contactsCurrPMMsg_ID == inData.Pkg.pmMsgID)
            {
                if (inData.Notice_Type == 'web_hook')
                {
                    Pkg = inData.Pkg;
                    if (Pkg.RecordType == 'Delivery')
                    {
                        lcMsg = 'Your email has been <b>Delivered</b>';
                    }
                    else if (Pkg.RecordType == 'Open')
                    {
                        lcMsg = 'Your email was just <b>Opened</b>';
                    }
                    else if (Pkg.RecordType == 'Bounce')
                    {
                        lcMsg = 'Ack. Your email has <b>Bounced</b>';
                    }     
                    else if (Pkg.RecordType == 'SpamComplaint')
                    {
                        lcMsg = 'Oh no. Your email was marked as <b>Spam</b>';
                    }     
                    else if (Pkg.RecordType == 'Click')
                    {
                        lcMsg = 'Yay. The reader <b>Clicked</b> on the link:<br/> ' + Pkg.OriginalLink;
                    } 
                    
                    if (lcMsg.length > 0)
                    {
                        $$("emailMsgStatus").setHTML(lcMsg);
                        setTimeout('$$("emailMsgStatus").setHTML("");',9000);                
                    }
    
                
                }
            }
            break;	
            
        case "data_track_import":
        webix_message({type: "info", text: '<b>'+inData.Title+'</b><br/>'+inData.Message, expire: 2800},4);
        break;
	
        case "data_import":
        webix_message({type: "info", text: '<b>'+inData.Title+'</b><br/>'+inData.Message, expire: 2400},4);
	if (inData.hasOwnProperty('Reload') && inData.Reload == true)
	{
	    setTimeout("location.reload();",4100);
	}
        break;	
		
        case "dashboard_start_notice":
            if (inData.Notice_Type == 'Data_Sent')
            {

                    gcLoadingDisp += inData.Message + "<br/>";
                    $$("loadingTemplate").setHTML(gcLoadingDisp);
                
                break;
            }
            else if (inData.Notice_Type == 'Ready_to_Webix')
            {
                gAllPulled = true;
                setTimeout('doSetUp()',400); 
                break;
            }
                     
            
        case "tableupdate":
            try
            {
                tds = eval('dataWH.'+inData.Data_Object+'.dataStore'); 
                tdp = eval('dataWH.'+inData.Data_Object+'.dp'); 
                record = tds.getItem(inData.id);
                tdp.off();
                if (inData.Update_Type == 'field')
                {
                    record[inData.Data_Field] = inData.Data_Value;
                }
                else
                {                    
                    if (inData.Update_Mode == 'update')
                    {
                        newObject = JSON.parse(inData.New_Object);
                        $$(inData.Data_Object.toLowerCase()+"Table").updateItem(newObject.id, newObject)
                    }
                    else if (inData.Update_Mode == 'add')
                    {
                        newObject = JSON.parse(inData.New_Object);
                        $$(inData.Data_Object.toLowerCase()+"Table").add(newObject,0)
                    }
                    else if (inData.Update_Mode == 'delete')
                    {
                        $$(inData.Data_Object.toLowerCase()+"Table").remove(newObject.id)
                    }                    
                }
                tdp.on();
                $$(inData.Data_Object.toLowerCase()+"Table").refresh();  
            }
            catch(err) {debugger;}
    }
} 
// ------------------------------------------------------------ //
function PushArtist(inData)
{
    gcPAData = inData;
    lcCall = gcPAData.Call;
    //console.log("PushArtist:  " + lcCall);
    switch(lcCall) 
    {

	case "new_announcement":
	//must refresh announcements...
	announcePage = 0;
	announceLoaded = false;
	announceShow(openMe=false); 	
	break;
	
        case "survey_update":
	lcMsg = `<b>Vetting Survey Response from:&nbsp;</b><span style="color:purple;font-weight:bold;">##name##</span><br/>
	<b>Project:&nbsp;</b>##proj##<br/><br/>
	##msg##
	<br/><br/>
	Refresh/go to this project to see their survey feedback.<br/>
	`;
	
	lcMsg = lcMsg.replaceAll("##msg##",inData.Message);
	lcMsg = lcMsg.replaceAll("##name##",inData.Artist_Name);
	lcMsg = lcMsg.replaceAll("##proj##",inData.Project_Name);
	
        //webix_message({type: "debug", text: lcMsg, expire: 7700},10);
	
        case "acct_msg":
        webix_message({type: "debug", text: '<b>'+inData.Title+'</b><br/>'+inData.Message, expire: 4700},10);
        
        case "collab_update":
        console.log(inData);        
        showCollabMsg(inData);

        case "testing":
        console.log(inData);	
        if ($('#showPush').length) {$("#showPush").append(JSON.stringify(inData)+'<br/>');}
        break;	

    }

} 
// ------------------------------------------------------------ //
function PushUser(inData)
{
    gcPUData = inData;
    lcCall = gcPUData.Call;
    //console.log("PushUser:  " + lcCall);
    switch(lcCall) 
    {

        case "acct_msg":
        webix_message({type: "debug", text: '<b>'+inData.Title+'</b><br/>'+inData.Message, expire: 1700},10);
        case "user_update":
        console.log(inData);        
        webix_message({type: "info", text: '<b>'+inData.Title+'</b><br/>'+inData.Message, expire: 1700},10);

        case "testing":
        console.log(inData);	
        if ($('#showPush').length) {$("#showPush").append(JSON.stringify(inData)+'<br/>');}
        break;	


        case "mail_connection":
        console.log(inData);	
        if (gcPUData.Status == 'Ok')
        {
            userApp.artist.Email_Access_Ok = true;
            $("#btnTestConn").prop('disabled',false);
            $("#btnSaveConn").prop('disabled',false);
            $("#mailConnMsgs").html(gcPUData.Message).show();
            setTimeout('$("#btnSaveConn").attr("disabled",false);',500);
        }
        else
        {

        }
        break;	

        case "email_confirmed":

        zoomItem('signupMsgs', "You have confirmed your email address now.<br/><br/>Please wait ... continuing to the Login page...", 'both', 'msgBoxSuccess', 3);
        setTimeout("gotoLogin();",4300);
        break;

        case "passwrd_reset":
        console.log("Pusher gave us go ahead for password reset form");
        doPWR(inData);
        break;
    }

} 
// ------------------------------------------------------------ //
function colReset()
{
    manageDTState('resetall');
}
// ------------------------------------------------------------ //
function PushEml(inData)
{
    console.log("PushEml:");
    gcPEData = inData;
    lcCall = gcPEData.Call;

    switch(lcCall) 
    {
    
        case "system_logout":
	if (inData.Env == gcEnv)
	{
	    setTimeout("location.replace('/logout/');",1000);	
	}

        break;	
	
        case "pitch_share":
        Announcer(lcCall,inData.Event,inData);
        break;
        
        case "act_logout":
        gotoModule('Catalog');
        localStorage.setItem("tmp_al", 'y');
        localStorage.setItem("alflds_u", gcPEData.alUser);
        localStorage.setItem("alflds_p", gcPEData.alPwd);          
        webix.message({type: "debug", text: '<b>'+inData.Title+'</b><br/>'+inData.Message, expire: 3000});
        setTimeout("forceLogout('install');",2400);
        
        case "reconnect_notice":
            if (inData.Completed == true)
            {
                webix.message({type: "success", text: "<b>Completed:</b><br/>Reconnecting Catalog files is now completed.", expire: 4800});
                setTimeout("location.reload();",5000);
                break;
            }
            else 
            {
                webix.message({type: "debug", text: "<b>Reconnecting File:</b><br/>Catalog file -> " + inData.Data.File_Path + inData.Data.File_Name + inData.Data.File_Ext, expire: 2500});
                break;
            }   
    }
}  

// ------------------------------------------------------------ //
function closeHelp()
{
    try {$$("helpWindowClose").show();} catch(err) {a=1;}
    try {webix.html.triggerEvent($$("helpWindowClose").getInputNode(), "MouseEvents", "click");} catch(err){a=1;}
    try {webix.html.triggerEvent($$("btnCloseMeta").getInputNode(), "MouseEvents", "click");} catch(err) {a=1;}
}
// ------------------------------------------------------------ //
function gotoCollabProject()
{
    if ($$("$kanbaneditor1")) {$(".webix_icon_button").click();}
    trow = {"cpProj_Proj_ID": gpitem.Project_ID, "cpProj_Task_ID": ""}
    cpProjGotoItem(trow);

}
// ------------------------------------------------------------ //
function PushGroup(inData)
{
    console.log("PushGroup:");
    gcPGData = inData;
    lcCall = gcPGData.Call;
    switch(lcCall) 
    {
        case "testing":
        console.log(inData);	
        if ($('#showPush').length) {$("#showPush").append(JSON.stringify(inData)+'<br/>');}
        break;	
    }
} 

// ------------------------------------------------------------ //   
function MonitorStatus(inData)
{
    console.log("MonitorStatus",inData);
    gMonitorStatus = inData.Status;
    
    if (inData.Status == 'xxx_online')
    {
        $$("tracksyncStatus").define("label",icon_tracksync_online);
        $$("tracksyncStatus").define("tooltip",'TrackSync is ONline');
        gExpecting_TS = 'active';
        
        ts_acct = inData.TrackSync_Account == undefined ? '' : inData.TrackSync_Account;
        if (ts_acct.length > 0 && ts_acct != gUser_Profile.Artist.Email)
        {
            lcMsg = `
            <b>Error:</b>&nbsp;Your TrackSync is connected to a <b>DIFFERENT</b> email account in the system!<br/>
            It is connected to:&nbsp;&nbsp;<b>##tse##</b><br/>
            `;
            lcMsg = lcMsg.replaceAll('##tse##',ts_acct);
            webix_message({type: "error", text: lcMsg, expire: 400000},15,'TrackSync-Mismatch','????');
        
        }
    }
    else
    {
        $$("tracksyncStatus").define("label",icon_tracksync_offline);
        $$("tracksyncStatus").define("tooltip","TrackSync is OFFline");
    }
    $$("tracksyncStatus").refresh();
    
    console.log("gExpecting_TS = ", gExpecting_TS);
	
	if (gMonitorStatus == 'online')
	{
		$$("btnStartTrackSync").disable();
		$$("btnCloseTrackSync").enable();
	}
	else
	{
		$$("btnStartTrackSync").enable();
		$$("btnCloseTrackSync").disable();
	}   	
	
}
// ------------------------------------------------------------ //
function dispDTCol(inDT, inCol, mde)
{
    if (mde == true)
    {
        if($$(inDT).isColumnVisible(inCol) == false) {$$(inDT).showColumn(inCol);}
    }
    else
    {
        if($$(inDT).isColumnVisible(inCol) == true) {$$(inDT).hideColumn(inCol);}
    }
}

// ------------------------------------------------------------ //
var cat_refs;
var gUser_Profile;

var apiKey = 'T1ukxQ.9yoI5Q:QTI4YBYa7caXwcAq';
var clientId = '';
var realtime = '';
var AblyRealtime = '';
var messageList = {};
var readStatus = {};
var membersList = [];
var connections = {};
var currentChat;
var currentCall;
var localStream;
var constraints = { video: { mediaSource: 'screen' }, audio: false };
var ablyConnected = false;
var kbpopup;
var l_a;
commChannel = '';gcFPRoot = '';gcArti_ID = '';appNode = 'MAIN';
// ----------------------------------------------------------------------------------------- //
async function dropApp()
{
    webix.message({type: "debug", text: "TrackSync system shutting down..", expire: 7000});
    pkge = {"Message": "Requesting APP to shut down"};
    msg = {"caller": appNode, "call": "DIE", "target": "APP", "pkge": pkge};
    await AblyRealtimeComm.publish('update', msg);
    
    setTimeout('dropTS();',2000);    
}
// ----------------------------------------------------------------------------------------- //
async function dropTS()
{
    pkge = {};
    msg = {"caller": appNode, "call": "quit_tauri", "target": "CMD", "pkge": pkge};
    await AblyRealtimeComm.publish('update', msg);   
}
// ----------------------------------------------- //
function processComms(inMsg)
{
    
    if (inMsg.data.target != appNode && inMsg.data.target != 'ALL') {return;}
    
    console.log("commsChannel msg:",inMsg);
    // ++++++++++++++++++++++++++++++++++++ //
    // processing switch:
    if (inMsg.data.call == 'closeComms' && inMsg.data.target != 'CMD')
    {
	    AblyRealtimeComm.unsubscribe();
	    AblyRealtimeComm.detach();	
	    ablyConnected = false;
	    if (appNode == 'MAIN') {response = axios.get(baseurl + 'logout/');}
    }
    // ++++++++++++++++++++++++++++++++++++ // 
    else if (inMsg.data.call == 'app_status' && inMsg.data.caller == 'APP' && inMsg.data.stage == 'response')
    {
	// we got an answer back from APP -> good
	gExpecting_TS = 'active';
	gsTimerCnt = 10;
    }
    // ++++++++++++++++++++++++++++++++++++ // 
    else if (inMsg.data.call == 'app_status')
    {
	    console.log('app_status broadcast received -> caller:', inMsg.data.caller, 'stage:', inMsg.data.stage, 'target:', inMsg.data.target, 'pkge:', inMsg.data.pkge);
	    $$("tracksyncStatus").define("label",icon_tracksync_online);
	    $$("tracksyncStatus").define("tooltip","TrackSync is ONline");
	    $$("tracksyncStatus").refresh();  
	    TSSpin('on');
    }
    // ++++++++++++++++++++++++++++++++++++ // 
    else if (inMsg.data.call == 'catalog-tag-files-update')
    {
	    console.log('catalog-tag-files-update received -> caller:', inMsg.data.caller, 'stage:', inMsg.data.stage, 'target:', inMsg.data.target, 'pkge:', inMsg.data.pkge);
	    tagFilesUpdate(inMsg);
	    TSSpin('on');
    }
    // ++++++++++++++++++++++++++++++++++++ //	    
    else if (inMsg.data.call == 'track-player-request')
    {
	console.log('pkge received -> caller:', inMsg.data.caller, 'stage:', inMsg.data.stage, 'target:', inMsg.data.target, 'pkge:', inMsg.data.pkge);
	pkge = inMsg.data.pkge
	if (pkge.Call == 'createpitch')
	{
	    forTrack_ID = pkge.Track_ID;
	    gotoModule('Catalog');
	    tmpTrack = $$("catalogTable").getItem(forTrack_ID);
	    gCurrTrack = tmpTrack;
	    setTimeout('$$("catalogTable").select(forTrack_ID);',900);
	    setTimeout("gotoTab('info');",1600);   
	    setTimeout('callPitchThisTrack();',2500);
	}
	else if (pkge.Call == 'emailtrack')
	{
	    forTrack_ID = pkge.Track_ID;
	    gotoModule('Catalog');
	    tmpTrack = $$("catalogTable").getItem(forTrack_ID);
	    gCurrTrack = tmpTrack;
	    setTimeout('$$("catalogTable").select(forTrack_ID);',900);
	    setTimeout("gotoTab('info');",1600);   
	    setTimeout('callEmailTrack();',2500);
	} 
    }
    // ++++++++++++++++++++++++++++++++++++ //	     
    
    
    
}
// ----------------------------------------------- //
function renderCommsMembers()
{
	console.log('Channel members:');
	for (ndx =0; ndx < commsMembersList.length; ndx++)
	{
		mbr = commsMembersList[ndx];
		console.log(ndx, 'clientId:',mbr.clientId, 'data:', mbr.data);
	}
}
// ----------------------------------------------- //

async function getUP(doPrepData=false,gTauri=false)
{
    //console.log("getUP():");  
        
    gUser_Profile = {};
    if (gTauri == true) {cfp = gcFP} else {cfp = '';}
    url = gcBaseURL + 'getobj/?nme=userprofile&seq=' + seq() + '&fp=' + cfp;
    await axios.get(url).then(response => 
    {
        gUser_Profile['User'] = response.data.user;
        gUser_Profile['Contact'] = response.data.contact;
        gUser_Profile['Artist'] = response.data.artist;
        gUser_Profile['Artist_Pref'] = response.data.artist_pref;
        //console.log("back from getobj for user_profile",gUser_Profile);
	//genSplit_Presets();
	
        gUser_Chime = gUser_Profile.User.Notice_Sounds;
        
        if (gUser_Profile.Artist_Pref.Fill_Data_Checks == '') 
            {fdChecks(mde='init');}
        else
            {fdMap = new Map(Object.entries(JSON.parse(gUser_Profile.Artist_Pref.Fill_Data_Checks)));}
                
        localViewSettings(mde='load',area='catalog','**current**');
        
        aseq = gUser_Profile.Artist_Pref.aseq;
        oldCustoms = (
        gUser_Profile.Artist_Pref.Track_FieldName_01 + '|' + gUser_Profile.Artist_Pref.Track_FieldName_02 + '|' + gUser_Profile.Artist_Pref.Track_FieldName_03 + '|' + 
        gUser_Profile.Artist_Pref.Track_FieldName_04 + '|' + gUser_Profile.Artist_Pref.Track_FieldName_05 + '|'  + gUser_Profile.Artist_Pref.Track_FieldName_03_Keys + '|');        

        if (gUser_Profile.User.User_Profile_Image.length > 0) {$("#profile_pic_small").attr("src",gUser_Profile.User.User_Profile_Image+uniq(0));}
        if (gUser_Profile.User.User_Profile_Image.length > 0) {$("#profile_pic_large").attr("src",gUser_Profile.User.User_Profile_Image+uniq(0));}
        if (gUser_Profile.User.User_Profile_Image.length > 0) {$("#userProfilePic").attr("src",gUser_Profile.User.User_Profile_Image+uniq(0));}

            $("#profile_email").html(gUser_Profile.User.Email);

            url2 = gcBaseURL + 'getobj/?nme=catref&seq=' + seq();
            axios.get(url2).then(response => 
            {
                cat_refs = response.data.cat_refs;  
		gBriefs = cat_refs.Briefs;
            });   
            
        bgi = "url('" + gUser_Profile.User.User_Profile_Image+uniq(0) + "')";
        $(".user_image").css('background-image',bgi);
        
        if (doPrepData == true) {setTimeout("prepData();",200);}
        setTimeout("imgUPUpdate();",3000);
	
    });
     
    //// ------------------------------------------------------------------------------------------- //
    //// set up ably connection:
    clientId = 'client-' + gUser_Profile.Artist.Arti_ID;
    realtime = new Ably.Realtime({ key: apiKey, clientId: clientId })
    AblyRealtime = realtime.channels.get('trsyncGroupChannel')
    ablyConnected = true;
    AblyRealtime.presence.subscribe('enter', function(member) {
        AblyRealtime.presence.get((err, members) => {
            membersList = members
            //console.log("ABLY:", membersList);
            renderMembers()
        })
    })
    AblyRealtime.presence.subscribe('leave', member => {
        delete(connections[member.client_id])
        if (member.client_id === currentChat) {
            currentChat = undefined
        }
        AblyRealtime.presence.get((err, members) => {
            membersList = members
            //console.log("ABLY:", membersList);
            renderMembers()
        })
    })
    
    AblyRealtime.presence.enter()    
    AblyRealtime.subscribe(`ablyWebRTC-signal/${clientId}`, msg => {
        if (!connections[msg.data.user]) {
            connections[msg.data.user] = new Connection(msg.data.user, AblyRealtime, false)
        }
        connections[msg.data.user].handleSignal(msg.data.signal)
    })
    //// ------------------------------------------------------------------------------------------- //
    // ------------------------------------------------------------------------------------------- //
    // +++++++++++++++++++++++++++++++++++++++++++++++++++++++++ //
    // area for app comms:
    	
    if (gTauri == true)
    {
	gcArti_ID = gUser_Profile.Artist.Arti_ID;
	commChannel = gcFPRoot + ':' + gcArti_ID;
	l = gcFP.split('_');
	gcFPRoot = l[0];
	commChannel = gcFPRoot + ':' + gcArti_ID;
	AblyRealtimeComm = '';
	mData = {"Node": appNode, "gcFP": gcFP};
	
	AblyRealtimeComm = realtime.channels.get(commChannel, mData);
	AblyRealtimeComm.subscribe((msg) => {processComms(msg);});	
	
	AblyRealtimeComm.presence.subscribe('enter', function(member) {
	    AblyRealtimeComm.presence.get((err, members) => {
		commsMembersList = members;
		console.log("ABLY:", commsMembersList);
		renderCommsMembers();
	    });
	});
	
	AblyRealtimeComm.presence.subscribe('update', function(member) {
	  console.log(member,member.data); 
	});		
	
	AblyRealtimeComm.presence.subscribe('leave', member => {
	    if (member.client_id === currentChat) {
		//currentChat = undefined
	    }
	    AblyRealtimeComm.presence.get((err, members) => {
		commsMembersList = members;
		console.log("ABLY:", commsMembersList);
		renderCommsMembers();
	    });
	});
	    
	AblyRealtimeComm.presence.enter();    
	AblyRealtimeComm.presence.update(mData);
    }
    
    // +++++++++++++++++++++++++++++++++++++++++++++++++++++++++ //
    
    // ------------------------------------------------------------------------------------------- //
} 

class Connection {
    constructor(remoteClient, AblyRealtime, initiator) {
        console.log(`Opening connection to ${remoteClient}`);
        this._remoteClient = remoteClient;
        this.isConnected = false;
        this._p2pConnection = new SimplePeer({
            initiator: initiator,
            trickle: false,
        });
        this._p2pConnection.on('signal', this._onSignal.bind(this));
        this._p2pConnection.on('error', this._onError.bind(this));
        this._p2pConnection.on('connect', this._onConnect.bind(this));
        this._p2pConnection.on('close', this._onClose.bind(this));
        this._p2pConnection.on('data', this._onData.bind(this));
    }

    handleSignal(signal) {
        this._p2pConnection.signal(signal);
    }

    send(msg) {
        this._p2pConnection.send(msg);
    }

    _onSignal(signal) {
        AblyRealtime.publish(`ablyWebRTC-signal/${this._remoteClient}`, {
            user: clientId,
            signal: signal,
        });
    }

    _onConnect() {
        this.isConnected = true;
        ablyConnected = true;
        console.log('connected to ' + this._remoteClient);
                    currentChat = this._remoteClient;
                                       
    }

    _onClose() {
        console.log(`connection to ${this._remoteClient} closed`);
        delete connections[this._remoteClient];
        ablyConnected = false;
    }

    _onData(data) {
    
        try 
        {
            var tmp_String = new TextDecoder().decode(data);
            var tmpJ_String = JSON.parse(tmp_String);
            if (tmpJ_String.msg_type && tmpJ_String.msg_type.length > 0)
            {
                getSimpleMsg(tmpJ_String);
                return;
            }
        }
        catch (err) 
        {
            a=1;
            receiveMessage(this._remoteClient, data)
        }

    }

    _onError(error) {
        console.log(`an error occurred ${error.toString()}`);
        ablyConnected = false;
    }
}

function showSPFTransfers()
{
    spf_w = $("#spf_transfers").width();
    spf_h = $("#spf_transfers").height();
    $("#spf_transfers").css({top: 80, left: ww - spf_w - 60, position:'absolute'});
    $("#progress").val(0);
    $("#spf_transfers").show();
}

function clearSPFTransfer()
{
    try {p.destroy();} catch(err) {a=1;}   
    //p = null;
    $("#progress").val(0);
    $("#spf_transfers").hide();
    
    if (initiator.checked == true)
    {
        lcPrompt = `

            <br/><center>If you are finished transferring files, click <b>YES</b>. <br/>This will allow you to receive file transfers from others again.</center>

        `;
        
        webix.prompt(
         {
          title: "Done Sending Files?",
          width: 550,
          text: lcPrompt,
          ok: "Yes",
          cancel: "No",
          css: "noInputHeight",
        }).then(function(result)
        {
            setTimeout(`
                //localStorage.setItem("projectReturnTo", gCurrProjectItem.id);
                location.reload();            
            `,600);
            
        }).fail(function(){
      
        });

    }
}

function getSimpleMsg(inJSON)
{
    console.log('received a simple-msg',inJSON);
    if (inJSON.msg_call == 'SJO')
    {
        // received a sender json offer
        gFTID = inJSON.user;        // this is the user id of the sender - make it our target
        
        showSPFTransfers();
        //$("#log").html('');
        tco = getCollab(gFTID);
        log('<hr/>Incoming connection from <b>' + tco.value) + '</b>';
        
        $("#incoming").text(inJSON.message);
        setTimeout('$("#btnJO").click();',100);
    }
    
    if (inJSON.msg_call == 'RJO')
    {
        // received a recipient's returning json offer
        // this is the last step in offer negotiation
        if (inJSON.user = gFTID)
        {
            $("#incoming").text(inJSON.message);
            setTimeout('$("#btnJO").click();',100);
        }
    }    
    
    a=1;
}

function sendFile(inID) {
    if (!messageList[currentChat]) {
        messageList[currentChat] = {}
    }
    var MAX_FSIZE = 400.0
    var fileInput = document.getElementById('sendfile')
    var file = fileInput.files[0];
    var fileReader = new FileReader();
    if (file) {
        var mbSize = file.size / (1024 * 1024);
        if (mbSize > MAX_FSIZE) {
            webix.message({type: "error", text: "<b>Sorry</b>  File transfers are limited to <b>400 MBytes</b> in size.", expire: 7000});
            // Reset file input
            return;
        }
        fileReader.onload = (e) => { onReadAsDataURL(e, null, file) }
        fileReader.readAsDataURL(file)
    }
}  

function setFT_Flag(mde)
{
    if (mde == 'up')
    {
        $(".webix_icon.webix_sidebar_icon.fas.fa-download").addClass('cyan_it');
        $('div[webix_tm_id="filesProjects"]').first().addClass("gold_it");
        showFileTransfers();
        
    }
    else
    {
        $(".webix_icon.webix_sidebar_icon.fas.fa-download").removeClass('cyan_it');
        $('div[webix_tm_id="filesProjects"]').first().removeClass("gold_it");
    }
}
// ------------------------------------------------------------ //
function showFileTransfers() 
{
    //$("#spf_transfers").show();
    showSPFTransfers();
}
// ------------------------------------------------------------------------------------------- //
function render() {

    if (!messageList[currentChat]) {
        return
    }
    
    var html = '';
    if (Object.keys(messageList[currentChat]).length === 0) {
        html += '<li>No files available here</li>';
        $("#ftd_list").html(html);
        return;
    }
    Object.keys(messageList[currentChat]).forEach((key) => {
        var element = messageList[currentChat][key];
        var downloadPercent = (element.chunks.join('').length / element.stringSize) * 100;
        var downloadLink = element.completed ? '<a id="dload_it" target =_blank download=' + key + ' href=' + element.downloadLink + ' > download now </a>' : 'receiving ' + downloadPercent + '%';
        
        cid = element.sender.replaceAll('client-','');
        tCollab = getCollab(cid);
        html += '<li><b> ' + tCollab.value + '&nbsp;sent:</b>&nbsp;&nbsp;' + key + '&nbsp;&nbsp;(' + formatBytes(element.stringSize) + ')&nbsp;&nbsp;' + downloadLink + ' </li>';
    });
    $("#ftd_list").html(html);

} 
// ------------------------------------------------------------------------------------------- //

function checkFTConnect()
{
    if (ablyConnected == true) {setTimeout("connectSPF(gFTID);",200);}
    
    console.log('File Transfer:  No connection yet');

    if ( ablyConnected == false && ((Date.now() - tStart) / 1000) < 60 )
        {setTimeout('checkFTConnect();',3000);}
    else
        {
            if (ablyConnected == false)
                {webix.message({type: "error", text: "<b>Error!</b>  We are unable to connect to this collaborator.  They may have logged out.", expire: 8000});}
            else
                {
                    webix.message({type: "success", text: "<b>Connected!</b>  Ready to do file transfers", expire: 5000});
                    log("<b>Connected!</b>  Ready to do file transfers",doBR=true);
                }            
        }
}

function sendFile2Collab(inID)
{
    console.log('will send file to ' + inID);
    if ($('#file').get(0).files.length === 0) 
    {
        webix.message({type: "error", text: "<b>Oops!</b>  Please select a file to send first.", expire: 7000});
        return;
    }
    
    if (inID == '' || inID == 'undefined') 
    {
        webix.message({type: "error", text: "<b>Oops!</b>  Please select an active Collaborator first.", expire: 7000});
        return;
    }    
    
    showSPFTransfers();
    $("#log").html('');
    
    gFTID = inID;
    tStart = Date.now();
    ConnectChat(inID);
    setTimeout('checkFTConnect();',1400);
}

function getCollab(inID)
{
    for (ndx2 =0; ndx2 < gUser_Profile.Artist.Collabs.length; ndx2++)
    {
        coll = gUser_Profile.Artist.Collabs[ndx2];
        if (coll.eid == inID) {return (coll);}
    }
    
    return {};
}

function getAblyMember(inID)
{
    for (ndx2 =0; ndx2 < membersList.length; ndx2++)
    {
        mbrx = membersList[ndx2];
        if (mbrx.clientId == 'client-' + inID) {return (mbrx);}
    }
    
    return {};
}

gcollabSelected = '';
function setCollabCell(inID)
{
    console.log("setCollabCell for: " + inID);
            
    gcollabSelected = inID;
    mbr = getAblyMember(inID);
    collab = getCollab(inID);
    $(".collab_cell").removeClass("collab_cell_selected");
    $("#collab_cell_"+inID).addClass("collab_cell_selected");
    if (mbr.hasOwnProperty('clientId') && mbr.action == 'present')
    {
        $("#sendfile").prop('disabled',false);
        $("#sendIt").prop('disabled',false);
        $("#sendIt").css('background','#351b5b').css('border','solid 1px #351b5b');
    }
    else
    {
        $("#sendfile").prop('disabled',true);
        $("#sendIt").prop('disabled',true);
        $("#sendIt").css('background','#dddddd').css('border','solid 1px #999999');
    }
}

function ft_Tips()
{
    for (ndx =0; ndx < gCurrProjectItem.Collaborators.length; ndx++)
    {
        ta = gCurrProjectItem.Collaborators[ndx];
        try {webix.TooltipControl.addTooltip($$("collabs_FT_" + ta.eid).$view);} catch(err) {a=1;}        
    }
}

function build_FT_Row()
{
    tcTmpl = `
        <div id="collab_cell_##id##" class="collab_cell" style="padding:7px;height:23px;" onclick="setCollabCell('##id##');">
        <span webix_tooltip='##tip##' style="font-weight:600;color:##fclr##!important;font-family:Poppins;font-size:13px;">##name##</span>
        <i style='padding-right:3px;' webix_tooltip='##tip##' class='fa-solid fa-##icon## ##color##'></i>
        <span style="font-size: 0px;">
        ##status## 
        </span>
        </div>
    `;    
    
    tcols = [];tcol = '';
    for (ndx =0; ndx < gCurrProjectItem.Collaborators.length; ndx++)
    {
        ta = gCurrProjectItem.Collaborators[ndx];
        mbr = getAblyMember(ta.eid);
        tout = '';
        if (ta.eid != gUser_Profile.Artist.Arti_ID)
        {
            tout = tcTmpl;
            //if (ta.status == 'away') 
            if (mbr.hasOwnProperty('clientId') && mbr.action == 'present')
                {
                    tout = tout.replaceAll('##color##','purple_it');
                    tout = tout.replaceAll('##fclr##','purple');
                    tout = tout.replaceAll('##status##','Online');
                    tout = tout.replaceAll('##icon##','circle-check');
                    tout = tout.replaceAll('##disabled##', '');
                    tout = tout.replaceAll('##addbg##', '');
                    lcTip = ta.first + ' ' + ta.last + ' is Available';
                    tout = tout.replaceAll('##tip##', lcTip);
                }
            else
                {                
                    tout = tout.replaceAll('##color##','grey_it');
                    tout = tout.replaceAll('##fclr##','#cacaca');
                    tout = tout.replaceAll('##status##','Away');
                    tout = tout.replaceAll('##icon##','circle-x');
                    tout = tout.replaceAll('##disabled##', 'disabled="disabled"');    
                    tout = tout.replaceAll('##addbg##', 'background:#cccccc!important;border:solid 1px #dddddd!important;');
                    lcTip = ta.first + ' ' + ta.last + ' is Away';
                    tout = tout.replaceAll('##tip##', lcTip);
                }
                
            tout = tout.replaceAll('##name##', ta.first + ' ' + ta.last);   
            tout = tout.replaceAll('##id##', ta.eid);
            tcol = {view: "template", borderless: 1, id: "collabs_FT_" + ta.eid, template: tout, gravity: 1, width: 240, height: 50, css: {"min-width": "200"},},
            tcols.push(tcol);
        }                        
    }
    if (tcols.length > 0) 
    {
        tr = [];trow = 1;trows = [];ccnt = 1;
        for (ndx2 =0; ndx2 < tcols.length; ndx2++)
        {            
            if (ccnt < 4)
            {
                ta2 = tcols[ndx2];
                tr.push(ta2);
                ccnt += 1;
            }
            else
            {
                ta2 = tcols[ndx2];
                tr.push(ta2);
                trX = {id: "ftr_" + trow, cols: tr };  
                trows.push(trX);            
                ccnt = 1; 
                trow += 1;
                tr = [];
                trX = '';
            }            
        }
        if (tr.length > 0)
        {
            trX = {id: "ftr_" + trow, cols: tr };  
            trows.push(trX);            
        }
        
        
        lcExtra = `
            <hr/>
            <input type="file" multiple class="projectsFileSelect" id="file" name="file" style="width:410px;border:1px solid #cccccc; border-radius: 6px;padding:10px;"/>
            <button type="button" id="sendIt" name="sendIt" style="cursor:pointer;margin-top:10px;width:100px;margin-left:5px;height:40px;font-weight:400;border:1px solid #351b5b;" 
            onclick="sendFile2Collab(gcollabSelected);" class="projectsFTFileSend">Send Now</button>          
        `;
        
        trXE = {view: "template", id: "ftr_extra", template: lcExtra, css:{"margin-top":"0px","border-top":"0px"},};       
        trows.push(trXE);
        webix.ui(trows, $$("collabs_FT_Row")); 
        setTimeout('ft_Tips();',600);
		setTimeout(`
			$$("collabs_FT_Row").config.width = 1200;
			$$("collabs_FT_Row").resize();
		`,1400);
    }
	else
	{	
		try
		{
			$$("ft_header_row").config.width = 1200;
			$$("ft_header_row").resize();
		} catch(err) {}
	}
	// also set the DAW type in interface...
	if (gUser_Profile.Artist.BFG == true)
	{
		if (gUser_Profile.Artist_Pref.DAW_Type.length > 0 && gUser_Profile.Artist_Pref.DAW_Type != 'Other')
		{
			try
			{
				xttmp = $$("btnDAWOpenProject").config.label;
				xttmp = xttmp.replaceAll('DAW',gUser_Profile.Artist_Pref.DAW_Type);
				xttmp = $$("btnDAWOpenProject").config.label = xttmp;
				xttmp = $$("btnDAWOpenProject").refresh();				
				var tabbar = $$("ProjectEditTabs").getTabbar();
				tabbar.config.options[1].value = gUser_Profile.Artist_Pref.DAW_Type + ' Projects';
				tabbar.hideOption("ProjectsEditDAWTab");
				tabbar.render();	
			} catch(err) {}
		}
		else
		{
			try
			{
				var tabbar = $$("ProjectEditTabs").getTabbar();
				tabbar.config.options[1].value = 'DAW Projects';
				tabbar.hideOption("ProjectsEditDAWTab");
				tabbar.render();	
			} catch(err) {}
		}
	}
	else
	{
		try
		{
			var tabbar = $$("ProjectEditTabs").getTabbar();
			tabbar.hideOption("ProjectsEditDAWTab");
		} catch(err) {}
	}
}

gFTID = '';tStart = '';
function ConnectChat(inID) {

    client_id = 'client-' + inID;
    tco = getCollab(gFTID)
    log('Connecting to <b>' + tco.value) + '</b>';
    
    if (client_id === clientId) {return;}

    currentChat = client_id;
    
    if (!connections[client_id]) {
        connections[client_id] = new Connection(client_id, AblyRealtime, true);
    }
}    


// =============================================================================== //
// old transfer methods
 

// ============================================================================== //
        
function renderMembers() {

    return;
    var list = document.getElementById('memberList')
    var online = document.getElementById('online')
    online.innerHTML = 'Users online (' + (membersList.length === 0 ? 0 : membersList.length - 1) + ')'
    var html = ''
    if (membersList.length === 1) {
        html += '<li> No member online </li>'
        list.innerHTML = html
        return
    }
    
    for (var index = 0; index < membersList.length; index++) {
        var element = membersList[index]
        if (element.clientId !== clientId) {
            var newMessage = readStatus[element.clientId] ? '<span class="label label-info">New</span>' : ''
            html += '<li><small>' + element.clientId + ' <button class="btn btn-xs btn-success" onclick=chat("' + element.clientId + '")>chat now</button> ' + newMessage + ' </small></li>'
        }
    }
    list.innerHTML = html
}

function chat(client_id) {
    if (client_id === clientId) return
        // Create a new connection
    currentChat = client_id
    if (!connections[client_id]) {
        connections[client_id] = new Connection(client_id, AblyRealtime, true)
    }
}   

// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ //
var spf;
setTimeout('spf = new window.spf.default();',6000);
var initiator;
var p; // peer
var transfer;
var files = [];
var SJO; 
var RJO;
var SJOc;
var RJOc;
var logger;
var filesDone;
var filesTot;

log = (msg,doBR=true) => {
  if (typeof msg == "object") {
  
  xmsg = (JSON && JSON.stringify ? JSON.stringify(msg, undefined, 2) : msg);
  
    if (xmsg.indexOf("ERR_DATA_CHANNEL") == -1) {logger.innerHTML += xmsg + "<br/>";}
  } else {
    logger.innerHTML += msg;
    if (doBR == true) {logger.innerHTML += "<br/>";}
  }
};

function connectSPF(gFTID)
{
    if ($("#initiator")[0].checked == true) {$("#initiator")[0].checked = false;}
    
    setTimeout('$("#initiator").click();',1200);    
}

function updateProgress (progress) {
  const pr = document.getElementById("progress");
  pr.value = progress;
  pr.innerText = progress + "%";
}

function isdone(file) {

  log("-> transfer completed.",doBR=true);
  filesDone += 1;
  console.log('file ', filesDone, ' of ', filesTot);
  
  if (file) 
  {
    lfile = "<a href='"+ URL.createObjectURL(file) +"' title= '" + file.name + "' download='"+ file.name +"'>Download Now</a>";
    log(lfile);
    tHTML = $("#log").html();
    tHTML = tHTML.replaceAll("transfer completed.<br>","transfer completed.&nbsp;&nbsp;")
    $("#log").html(tHTML);    
  }
  else
  {
    if (filesDone == filesTot)
    {
        tHTML = $("#log").html();
        tHTML = tHTML + '<br/><span style="color:purple;"><b>' + filesDone + '</b>&nbsp;file(s) sent.</span>';
        $("#log").html(tHTML);
        $("#progress").hide();
    }  
  }
}

async function spf_init () {
     
  console.log("spf_init():");
  initiator = document.getElementById("initiator");
  SJO = '';SJOc = '';$("#outgoing").text('');
  webix.message({type: "success", text: "<b>Connecting</b>  Starting connection process..", expire: 2000});

  p = new window.SimplePeer({
    initiator: initiator.checked,
    trickle: false
  });
  p.on("error", (err) => log(err));
  p.on("signal", (data) => {
    document.querySelector("#outgoing").textContent = JSON.stringify(data);
    if (initiator.checked)
    {
        // this is the sender side
        console.log('p.signal: sender side');
        SJO = JSON.parse($("#outgoing").text())
        SJOc = $("#outgoing").text();
        console.log(SJO);
        // send the SJO to the recip
        jo = JSON.stringify({ msg_type: 'simple', msg_call: 'SJO', user: gUser_Profile.Artist.Arti_ID, message: SJOc })
        connections['client-'+gFTID].send(jo);
        webix.message({type: "success", text: "<b>Connected!</b>  Arranging file transfer(s)..", expire: 3000});
    }
    else
    {
        // this is the recip side
        console.log('p.signal: recip side');
        
        RJO = JSON.parse($("#outgoing").text())
        RJOc = $("#outgoing").text();
        console.log(SJO);
        // send the RJO back to the sender
        jo = JSON.stringify({ msg_type: 'simple', msg_call: 'RJO', user: gFTID, message: RJOc })
        connections['client-'+gFTID].send(jo);
        webix.message({type: "success", text: "<b>Connected!</b>  Completing file transfer setup", expire: 3000});            
    }

  });

  p.on("connect", () => {
    log("Connection setup completed.<br/>");
    document.getElementById("afterconnect").style.display = "block";
    $("#progress").show();
    
    
    setTimeout('$("#spf_send_button").click();',400);
  });

  p.on("data", async (data) => {
    data = data.toString()
    console.log("p.data");
        
    if (data.substr(0, 5) === "file-") {
      //console.log("p.data -> this is file- data");
      tflst =  data.split('___');
      tfname = tflst[0].substring(5)
      log("File:&nbsp;&nbsp;<b>" + tfname + '</b>',doBR=true);

      const fileID = data.substr(5);
      //console.log("p.data -> fileID", fileID);
      spf.receive(p, fileID).then(transfer => {
        transfer.on("progress", updateProgress);
        transfer.on("done", isdone);
      });
      p.send("start-" + fileID);
    } else if (data.substr(0, 6) === "start-") {
      tflst =  data.split('___');
      tfname = tflst[0].substring(6)
      log("File:&nbsp;&nbsp;<b>" + tfname + '</b>');
      
      
      //console.log("p.data -> this is start- data");

      const fileID = data.substr(6)
      filesDone = 0;filesTot = document.getElementById("file").files.length;
      transfer = await spf.send(p, fileID, files[fileID]);
      transfer.on("progress", updateProgress);
      transfer.on("done", isdone);
      transfer.start();
    }
  });
}

async function send() {
  const f = document.getElementById("file").files;
  for (var i = 0; i < f.length; i++) {
    const file = f[i];
    const fileID = file.name + '___' + file.size;
    files[fileID] = file
    p.send("file-" + fileID);
  }
  
  log('<hr/>');
}

function addEListen()
{
    //console.log("addEListen():");
    document.querySelector("form").addEventListener("submit", (ev) => {
      ev.preventDefault();
    
      if (!initiator.checked) {
        spf_init();
      }
      p.signal(JSON.parse(document.querySelector("#incoming").value));
    });
}

// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ //
// ------------------------------------------------------------ //
function genImportPROWindow()
{
    title = "Import " + gUser_Profile.Artist.PRO_Name + " PRO Data";
    webix.ui({
        view: "fadeInWindow", width: ww*0.57, height: hh*0.16, position: "center", id: "importPROWindow", zIndex: 60, modal: true,
        borderless: 1,
        head:{
            view: "toolbar", id: "importPROWindowToolbar", 
            height: 50,
            borderless: 1,
            css: { "background-color":"#eeebf5"},
            cols:[
                {   view: "template", id: "importPROWindowTitle", 
                    borderless:1,
                    css: { "background-color":"#eeebf5", "padding-top":"8px", "padding-left":"10px", "font-size":"16px", "font-weight":"bold"},
                    template: title 
                },
                {},
                {   view: "icon", id: "importPROWindowCloseBtn",
                    type: "button", 
                    icon: "fas fa-close",
                    width: 40,
                    click: "$$('importPROWindow').hide();$$('importPROWindow').destructor();"
                },
                {   width: 10  },
            ]
        },
        body: {  
            view: "form", id: "importPROWindowForm", 
            width: ww, 
            height: hh,      
            scroll: true,
            elements: [
                {   view: "layout", id: "importPROSourceRows",
                    rows: [
                        {   view: "layout", id:"ImportPRO_Source_Data",
                            height: 40,
                            cols: [
                                {   width: 10 },
                                {   view: "template", template: "<span style='font-weight:bold; font-size:14px;'>Select</span>&nbsp; and <span style='font-weight:bold; font-size:14px;'>upload</span> CSV file:",
                                    width: 200,
                                    borderless: 1, 
                                    css: { "border-bottom: 1px; color":"#666666", "font-size":"12px", "padding-left":"4px", "margin-top": "0px"},
                                    height: 3,
                                },                               
                                {   view: "list",  id: "importUpload", 
                                    label: "Upload PRO file",
                                    type:"uploader",
                                    disabled: false,	
                                    width: 280,
                                    css: { "border-top-left-radius": "6px", "border-bottom-left-radius": "6px", "border-width":"1px 1px 1px!important", "border-color":"#cccccc", "height": "32px!important", "padding-top":"1px"},
                                 },  
                                 {  view: "uploader", id: "importUploadButton", 
                                    value: "<span class='far fa-search'></span>", 
                                    width: 35,
                                    tooltip: "Select",
                                    multiple: false, 
                                    autosend: false,
                                    name: "importFileUploader",
                                    css: "upload_button_left",
                                    link: "importUpload",  upload: "tmp",
                                    on: {
                                        onAfterFileAdd: function(item)
                                        {
                                            webix.message({type: "success", text: gUser_Profile.Artist.PRO_Name + " import file selected.  Uploading to server...", expire: 2000});
                                            webix.html.triggerEvent($$("importGoButton").getInputNode(), "MouseEvents", "click");
                                        },                                      
                                        onFileUpload: function(item) 
                                        {                                                               
                                            if (item.Status == 'error')
                                            {
                                                webix.message({type: "error", text: item.message, expire: 10000});
                                                gBatchFile = '';
                                            }
                                            else
                                            {
                                                webix.message({type: "success", text: item.message, expire: 4000});
                                                gBatchFile = item.BatchFile;
						$$("btnImportPRODataGo").show();
						$$("importPROWarnings").show()
                                            }
                                        },
                                        onFileUploadError: function(file, response) 
                                        {                                                                
                                            webix.message({type: "error", text: "Unable to process upload.", expire: 10000});  
                                            gBatchFile = '';
						$$("btnImportPRODataGo").hide();
						$$("importPROWarnings").hide()					    
                                        }, 
                                    },                                                                    
                                },
                                {   view: "button", id: "importGoButton", 
                                    label: "<span class='fas fa-upload'></span>",
                                    width: 65,
                                    css: "upload_button",
                                    tooltip: "Upload",
                                    click: function()
                                    {
                                        $$("importUploadButton").define("upload","/data_import/?mde=pro___" + gUser_Profile.Artist.PRO_Name + "&step=init");                                                                                        
                                        $$("importUploadButton").refresh();
                                        $$('importUploadButton').send();
                                    }
                                },                                                                                                              
                                {   width: 80 },
                                {   view: "button", id: "btnImportPRODataGo", value: 'Process Import Now', 
				    width: 160,
				    disabled: false,
				    hidden: true,
                                    click: catalogImportPROData
                                }, 
                                {   width: 20 },
                            ]
                        },
			
			{   view: "layout", id: "importPROWarnings",
			    hidden: true, borderless: 1,
			    rows: 
			    [
				{height: 10},
				//{   view: "checkbox", id: "chkDisclaimer1", name: "chkDisclaimer1", 
				    //width: ww*.4,
				    //labelWidth: 0,
				    //labelRight: "I confirm that this process will overwrite rights and publishers info under all Tracks that are located by this process.", 
				    //css:{"margin-top":"-3px!important;","padding-left": "25px"},
				    //on:
				    //{
					//onItemClick: function()
					//{
					    //if ($$("chkDisclaimer1").getValue() == 0 || $$("chkDisclaimer2").getValue() == 0)
					    //{
						//$$("btnImportPRODataGo").disable();
					    //}
					    //else
					    //{
						//$$("btnImportPRODataGo").enable();
					    //}
					//}				    
				    //},
				//},
				//{   view: "checkbox", id: "chkDisclaimer2", name: "chkDisclaimer2", 
				    //width: ww*.4,
				    //labelWidth: 0,
				    //labelRight: "I confirm that this may overwrite some rights and publisheres data that is already in the system.", 
				    //css:{"margin-top":"-3px!important;","padding-left": "25px"},
				    //on:
				    //{
					//onItemClick: function()
					//{
					    //if ($$("chkDisclaimer1").getValue() == 0 || $$("chkDisclaimer2").getValue() == 0)
					    //{
						//$$("btnImportPRODataGo").disable();
					    //}
					    //else
					    //{
						//$$("btnImportPRODataGo").enable();
					    //}
					//}				    
				    //},				    
				//},				
			    
			    ]
			},
                    ]
                }, 
            ]
        },
    }).show();
    
}
// ------------------------------------------------------------ //
function genImportWindow(importType,nextBtn='Import')
{
    title = "Import " + importType.toProperCase() + " Data";
    webix.ui({
        view: "fadeInWindow", width: ww*0.97, height: hh*0.9, position: "center", id: "importWindow", zIndex: 60, modal: true,
        borderless: 1,
        head:{
            view: "toolbar", id: "importWindowToolbar", 
            height: 50,
            borderless: 1,
            css: { "background-color":"#eeebf5"},
            cols:[
                {   view: "template", id: "importWindowTitle", 
                    borderless:1,
                    css: { "background-color":"#eeebf5", "padding-top":"8px", "padding-left":"10px", "font-size":"16px", "font-weight":"bold"},
                    template: title 
                },
                {},
                {   view: "icon", id: "importWindowCloseBtn",
                    type: "button", 
                    icon: "fas fa-close",
                    width: 40,
                    click: "$$('importWindow').hide();$$('importWindow').destructor();"
                },
                {   width: 10  },
            ]
        },
        body: {  
            view: "form", id: "importWindowForm", 
            width: ww, 
            height: hh,      
            scroll: true,
            elements: [
                {   view: "layout", id: "importSourceRows",
                    rows: [
                        {   view: "layout", id:"Import_Source_Data",
                            height: 40,
                            cols: [
                                {   width: 10 },
                                {   view: "template", template: "<span style='font-weight:bold; font-size:14px;'>Select</span>&nbsp; and <span style='font-weight:bold; font-size:14px;'>upload</span> CSV file:",
                                    width: 200,
                                    borderless: 1, 
                                    css: { "border-bottom: 1px; color":"#666666", "font-size":"12px", "padding-left":"4px", "margin-top": "0px"},
                                    height: 3,
                                },                               
                                {   view: "list",  id: "importUpload", 
                                    label: "Upload Spreadsheet",
                                    type:"uploader",
                                    disabled: false,	
                                    width: 280,
                                    css: { "border-top-left-radius": "6px", "border-bottom-left-radius": "6px", "border-width":"1px 1px 1px!important", "border-color":"#cccccc", "height": "32px!important", "padding-top":"1px"},
                                 },  
                                 {  view: "uploader", id: "importUploadButton", 
                                    value: "<span class='far fa-search'></span>", 
                                    width: 35,
                                    tooltip: "Select",
                                    multiple: false, 
                                    autosend: false,
                                    name: "importFileUploader",
                                    css: "upload_button_left",
                                    link: "importUpload",  upload: "tmp",
                                    on: {
                                        onAfterFileAdd: function(item)
                                        {
                                            webix.message({type: "success", text: importType + " import file selected.  Uploading to server...", expire: 2800});
                                            webix.html.triggerEvent($$("importGoButton").getInputNode(), "MouseEvents", "click");
                                        },                                      
                                        onFileUpload: function(item) 
                                        {                                                               
                                            if (item.Status == 'error')
                                            {
                                                webix.message({type: "error", text: item.message, expire: 10000});
                                                gBatchFile = '';
                                            }
                                            else
                                            {
                                                gImport_Source = item.sourceFields;
                                                gImport_Target = item.targetFields;
                                                genFieldsArea(item.ImportFields_HTML);
                                                webix.message({type: "success", text: item.message, expire: 4000});
                                                gBatchFile = item.BatchFile;
                                                $("#fieldsArea").removeClass('hidden');
                                            }
                                        },
                                        onFileUploadError: function(file, response) 
                                        {                                                                
                                            webix.message({type: "error", text: "Unable to process upload.", expire: 10000});  
                                            gBatchFile = '';
                                        }, 
                                    },                                                                    
                                },
                                {   view: "button", id: "importGoButton", 
                                    label: "<span class='fas fa-upload'></span>",
                                    width: 65,
                                    css: "upload_button",
                                    tooltip: "Upload",
                                    click: function()
                                    {
                                        chkval = $$("importHasHeaders").getValue();
                                        $$("importUploadButton").define("upload","/data_import/?mde=" + importType + "&step=init&hdrs="+chkval+'');                                                                                        
                                        $$("importUploadButton").refresh();
                                        $$('importUploadButton').send();
                                    }
                                },
                                {   view: "checkbox", id: "importHasHeaders", name: "importHasHeaders",
                                    labelRight: "<b>PLEASE NOTE:</b> First row <b>MUST</b> contain headers.", 
                                    value: 1, 
                                    width: 300,
                                    labelWidth:0,
				    enabled: false,
                                },                                                        
                                {   view: "select", id: "importTrackType", name: "importTrackType", label: "Track Type",
                                    width: 190, hidden: true,
                                    options: [
                                        {   id: "", value: ""},
                                        {   id: "Primary", value: "Primary" },
                                        {   id: "Alternate", value: "Alternate"},
                                        {   id: "Stem", value: "Stem" },
                                    ]
                                },                                                        
                                {   width: 80 },
                                {   view: "button", id: "btnCancelImport", value: "Cancel Import", 
                                    css: "light_button",
				    width: 130,
				    click: catalogImportNo,
                                }, 
                                {   view: "button", id: "btnImportDataGo", value: nextBtn, 
				    width: 130,
                                    click: catalogImportData
                                }, 
                                {   width: 20 },
                            ]
                        },
                    ]
                }, 
                {   view: "template", id: "importFieldsArea", template: "html->fieldsArea", height: hh-100},
            ]
        },
    }).show();
    
}
gFDMounts = [];
// ------------------------------------------------------------ //
function getMountsData(inFolder,urkey='',inclFiles=false,justExts='',numLevels=99)
{
    if (gMonitorStatus == false)
    {
	webix.message({type: "error", text: "<b>Error:</b>&nbsp;&nbsp;TrackSync must be ONLINE to use this feature", expire: 4500}); 
	return null;
    }
    
    if (urkey.length == 0) {urkey = new Date().toISOString().replaceAll('Z','') + '-' + seq();}
    gFDGroupKey = urkey;gFDDone = '';gFDGroup = [];gFDBatchDone = '';gFDBatchKey = '';gFDBatch = [];gFDMounts = [];
	inFolder = '';
    url = '/getobj/?nme=tsgetmounts&seq=' + seq();
    data = {'folder': inFolder, 'urkey': urkey, 'incl_files': inclFiles, 'just_exts': justExts, 'num_levels': numLevels};
	console.log(data);
    console.log('using urkey',urkey);
    axios.post(url, data).then(response => 
    {
		//webix.message({type: "success", text: "<b>Ok:</b>&nbsp;&nbsp;Retrieving folders root list...", expire: 15000}); 
    },
    (error) => 
    { 
	//console.log("Error:", error);
    }); 
    
    response.fldr_urkey = urkey;
    return response;
}
// ------------------------------------------------------------ //
function getFolderData(inFolder,urkey='',inclFiles=false,justExts='',numLevels=99)
{
    if (gMonitorStatus == false)
    {
	webix.message({type: "error", text: "<b>Error:</b>&nbsp;&nbsp;TrackSync must be ONLINE to use this feature", expire: 4500}); 
	return null;
    }
    
    if (urkey.length == 0) {urkey = new Date().toISOString().replaceAll('Z','') + '-' + seq();}
    gFDGroupKey = urkey;gFDDone = '';gFDGroup = [];gFDBatchDone = '';gFDBatchKey = '';gFDBatch = [];
    url = '/getobj/?nme=tsgetfolder&seq=' + seq();
    data = {'folder': inFolder, 'urkey': urkey, 'incl_files': inclFiles, 'just_exts': justExts, 'num_levels': numLevels};
	console.log(data);
    console.log('using urkey',urkey);
    axios.post(url, data).then(response => 
    {
	//console.log("getFolderData got back", response);
	//webix.message({type: "success", text: "<b>Ok:</b>&nbsp;&nbsp;Retrieving folder list...", expire: 15000}); 
    },
    (error) => 
    { 
	//console.log("Error:", error);
    }); 
    
    response.fldr_urkey = urkey;
    return response;
}
// ------------------------------------------------------------ //
function folderDataReceived()
{
    console.log('Ok, complete batch of folders all received:  gFDBatch ->');
    console.log(gFDBatch);
	projectsLoadDAW();
}
// ------------------------------------------------------------ //
function folderDataProcess(inPkge)
{
    console.log('package consolidation now');
    console.log(inPkge);
    gFDGroup = [];
    gFDGroupKey = '';
    if (inPkge.Folder_Group == gFDBatchKey && gFDBatchDone.indexOf('|'+inPkge.Folder_Num+'|') == -1)
    {
	gFDBatchDone = '|' + inPkge.Folder_Num + '|';
	if (inPkge.Folder_Count == inPkge.Folder_Num || inPkge.hasOwnProperty('Folder_Is_Stack') == true)
	{
		console.log('Batch LAST pkge #',inPkge.Folder_Num,' of ', inPkge.Folder_Count);
	    // last folder of the batch...now trigger the usage call
		if (inPkge.Contents.hasOwnProperty('End_Of_Job') == false)
		{
			gFDBatch.push(inPkge);
		}
	    setTimeout('folderDataReceived();',1000);
	}
	else
	{
	    // store this package in the batch
	    gFDBatch.push(inPkge);
		console.log('Batch pkge #',inPkge.Folder_Num,' of ', inPkge.Folder_Count);
	    // still, we are waiting for more packages
	}
    
    }
}

gFDBatch = '';gFDBatchKey = '';gFDBatchDone = '';
// ------------------------------------------------------------ //
function location_reload()
{
    //if (gUser_Profile.User.Email.indexOf('@robottworks') > -1)
    if (Import_Mode == 'Y')
    {
	console.log('reloading the NEW way');
	//repullFor();
	setTimeout("closeHelp();",1200);
	//location.reload();
    }
    else
    {
	location.reload();
    }
}
// ------------------------------------------------------------ //
function PushMonitor(inData)
{
    console.log("PushMonitor:", inData);
    inData.Session_ID = '';inData.Relay = '';
    gcPMData = inData;
    lcCall = gcPMData.Call;
	//debugger;
    
    switch(lcCall) 
    {
	case "trackview_show_track":
	
	try {if (inData.Longer == 1) {mLength = 10000;} else if (inData.Longer == 2) {mLength = 40000;} else {mLength = 4000;}} catch(err) {mLength = 4000;}
	lcMsg = inData.Message
	if (inData.Status != 'ok')
	{
		webix.message({type: "debug", text: lcMsg, expire: 3000});	
		webix.message({type: "debug", text: "<b>Oops.</b><br/>TrackView is not currently running.<br/>Trying to start it now...<b/>Once it's running, select View Metadata -> TrackView again!", expire: 20000});	
		protoLaunchTV();
	}
	break;	
	
	case "mifge-download":
	
	try {if (inData.Longer == 1) {mLength = 10000;} else if (inData.Longer == 2) {mLength = 40000;} else {mLength = 4000;}} catch(err) {mLength = 4000;}
	lcMsg = inData.Message
	webix.message({type: "debug", text: lcMsg, expire: mLength});
	break;
	
	case "converts32mp3":
	
	lcMsg = '<b>' + inData.Source_File + '</b> has been converted to an MP3';
	webix.message({type: "debug", text: lcMsg, expire: 4200});
	if (gDoConversion == 'y') {localStorage.setItem("needs_process_folders", '1');}
	
	case "folder-mounts-response":
	//debugger;
	console.log('folder-mounts-response', inData);
	gFDMounts = inData.mounts_data;
	
	case "folder-data-response":	
	//debugger;
	if (inData.Folder_Num == 1) {gFDBatchKey = inData.Folder_Group;}
	
	if (gFDBatchKey == inData.Folder_Group || (inData.For_Urkey == gFDGroupKey && gFDDone.indexOf('|'+inData.uniq+'|') == -1))
	{
		gFDDone = '|' + inData.uniq + '|';
	    if (inData.Multi_Packet == false)
	    {
		folderDataProcess(inData);
	    }
	    else
	    {
		if (inData.PNum == inData.PCount)
		{	
		    //console.log('adding from LAST partial package');
		    for (ndx =0; ndx < inData.Contents.length; ndx++)
		    {
			tt = inData.Contents[ndx]; 
			gFDGroup.push(tt);
		    }		
		    
		    deepC = _.cloneDeep(inData);
		    deepC.Contents = gFDGroup;
		    folderDataProcess(deepC);
		}
		else
		{
		    //console.log('adding from partial package');
		    for (ndx =0; ndx < inData.Contents.length; ndx++)
		    {
			tt = inData.Contents[ndx]; 
			gFDGroup.push(tt);
		    }
		}
	    }
	}
	break;
	
	case "archive_folder_set":
	if (inData.Archive_Folder.length > 0)
	{
	    lcF = "<b>TrackSync: </b>&nbsp;&nbsp;Archive Folder is:&nbsp;&nbsp" + inData.Archive_Folder;
	    webix_message({type: "info", text: lcF, expire: 2400},10,forItem='',forDesc='',send2Modal=false,call=lcCall);
	}
	else
	{
	    lcF = "<b>TrackSync: </b>&nbsp;&nbsp;Archive Folder is NOT set!";
	    webix_message({type: "error", text: lcF, expire: 4800},10,forItem='',forDesc='',send2Modal=false,call=lcCall);	
	}
	break;
	
	case "trackcachegroup":
	break;
		
        case "newuserdemo":
        console.log("newuserdemo");
        break;
		
        case "tracksync-file-error":
        console.log("tracksync-file-error",inData);
        filename = inData.File_Name.replace(/^.*[\\\/]/, '')
		filepath = inData.File_Path.replace(/^.*[\\\/]/, '')
        lcF = "<b>TrackSync: </b>&nbsp;&nbsp;TrackSync File Error:  File is refused.  Filename is greater than 130 characters. ";
        webix_message({type: "error", text: lcF, expire: 10000},2,forItem='',forDesc='',send2Modal=false,call=lcCall);
        lcF = "<b>TrackSync: <b>File = &nbsp;</b>" + filename;
        webix_message({type: "error", text: lcF, expire: 10000},2,forItem='',forDesc='',send2Modal=false,call=lcCall);	
        lcF = "<b>TrackSync: <b>Location = &nbsp;</b>" + filepath;
        webix_message({type: "error", text: lcF, expire: 10000},2,forItem='',forDesc='',send2Modal=false,call=lcCall);			
        break;   		
        
        case "new-tracks-added":
        //console.log("new-tracks-added",inData);
        filename = inData.File_Path.replace(/^.*[\\\/]/, '')
        lcF = "<b>TrackSync: </b>&nbsp;&nbsp;Preparing files -  " + inData.QSize + ' more to go.';
		
		if (inData.QSize == 0) {location.reload();}
        lcF = lcF.replace("there are <b>1</b> more","there is <b>1</b> more");
        
        webix_message({type: "info", text: lcF, expire: 1200},10,forItem='',forDesc='',send2Modal=true,call=lcCall);
        break;        
        
        case "cachemode":
        console.log("cachemode", inData);  

		tst = dataWH.Catalog.dataStore.getItem(inData.Track_ID);
		if (typeof(tst) == 'object')
		{ 		
			tst.Perm_Share_Outdated = 'N';
			dataWH.Catalog.dataStore.updateItem(inData.Track_ID,tst);	
			tst.chkCatalog = 'off';
		}		
	
	isOnline = false;
	
	if (inData.hasOwnProperty('Prev_Call') && inData.Prev_Call == 'current-state')
	{
	    isOnline = true
	    dataWH.Artist.TSCommsGood = true;	    
	}	
	if (isOnline == true)
	{
	    $$("tracksyncStatus").define("label",icon_tracksync_online);
	    $$("tracksyncStatus").define("tooltip",'TrackSync is ONline');
		$$("btnStartTrackSync").disable();
		$$("btnCloseTrackSync").enable();
	}
	else
	{
	    $$("tracksyncStatus").define("label",icon_tracksync_offline);
	    $$("tracksyncStatus").define("tooltip","TrackSync is OFFline");
		$$("btnStartTrackSync").enable();
		$$("btnCloseTrackSync").disable();
	}
	$$("tracksyncStatus").refresh();		


        gUser_Profile.Artist_Pref.Caching_Mode = inData.Cache_Status;
        if (inData.Just_Cached != undefined && inData.Cache_Status == 'OFF')
        {
            filename = inData.Just_Cached.replace(/^.*[\\\/]/, '');
			lcMsg = "<span style='font-size:12px;'>Track cached to cloud:&nbsp;<b>" + filename + "</b>.&nbsp;&nbsp;(" + inData.Files_Todo + "&nbsp;more to go)</span>";
            webix_message({type: "success", text: lcMsg, expire: 10000},10,forItem='',forDesc='',send2Modal=false,call='track-updated ' +  gUser_Profile.CacheFiles_Todo);
			
			console.log('inData = ', inData);
			storeTrackPeaks(inData.Track_ID,forceIt=true);
	    
	    if (inData.Files_Todo > 0)
	    {
		thisHTML = '<div style="padding-left:20px;border: 2px solid #ffc300; ">Cache files to go:&nbsp; <span style="color:gold;"><span style="font-size:16px;">' + inData.Files_Todo + '</span></span></div>'
		$('div[webix_tm_id="trackDataTansfer"]').html(thisHTML);
	    }
	    else
	    {
		$('div[webix_tm_id="trackDataTansfer"]').html('');
	    }
	    
	    if (inData.Files_Todo > 0) {wasTo_Do = inData.Files_Todo;}
	    console.log("was_todo",wasTo_Do,"inData.Files_Todo",inData.Files_Todo);
	    if (wasTo_Do == 1 && inData.Files_Todo == 0) 
	    {
		wasTo_Do = 0;
		webix_message({type: "success", text: "File Caching is completed.", expire: 10000},10,forItem='',forDesc='',send2Modal=false,call='track-updated ' +  gUser_Profile.CacheFiles_Todo);
		setTimeout("location.reload();",2600);    
	    }
	    if (inData.Files_Todo == 0 && filename.length > 0) {waitForQuiet = true;}
	    
		pfu = localStorage.getItem("needs_process_folders");
		if (pfu == null) {pfu = '0';}
	    if (inData.Files_Todo == 0 && pfu != '0') {setTimeout("location.reload();",4400);}
		
	    return;
        }
		
        
	if (gUser_Profile.CacheFiles_Todo != undefined)
	{
		if (inData.Files_Todo < gUser_Profile.CacheFiles_Todo)  {gUser_Profile.CacheFiles_Todo = inData.Files_Todo;}
	} 
        
        numTodo = '';
        if (gUser_Profile.CacheFiles_Todo != undefined)
        {
            numTodo = ':   <br/>Tracks requiring caching = ' + gUser_Profile.CacheFiles_Todo;
        }
        if (gMonitorStatus == 'online')
        {
            $$("tracksyncStatus").define("label",icon_tracksync_online);
            $$("tracksyncStatus").define("tooltip",'TrackSync is ONline');
        }
        else
        {
            $$("tracksyncStatus").define("label",icon_tracksync_offline);
            $$("tracksyncStatus").define("tooltip","TrackSync is OFFline");
        }
        $$("tracksyncStatus").refresh();           
        
        if (inData.Files_Todo > 0 && (inData.Cache_Status != 'OFF' || (inData.Just_Cached != undefined && inData.Just_Cached.length > 0)))
        {
            lcF = "Tracks are being cached: there are <b>" + inData.Files_Todo + "</b> more to go...";
            lcF = lcF.replace("are <b>1</b> more to go","is <b>1</b> more to go")
            webix_message({type: "info", text: lcF, expire: 1200},20,forItem='',forDesc='',send2Modal=false,call=lcCall);
        }
        else
        {
            if (inData.Files_Todo > 0 && inData.Cache_Status != 'OFF')
            {
                webix_message({type: "info", text: "Track caching is <b>completed</b>.", expire: 1200},20,forItem='',forDesc='',send2Modal=gfalse,call=lcCall);
            }
        }
        break;
        case "meta-data-update":
        console.log("Received a meta-data relay:",inData);
        MetaUpdateTrack(inData);
        break;
                
        case "tracksync-start-caching":
        tmsg = inData.Message.replace('starting','checking');
        webix_message({type: "success", text: tmsg, expire: 1200},10,forItem='',forDesc='',send2Modal=false,call=lcCall);   		
		
        break;
        
        case "image-upload-complete":
        if (inData.Date_Mode != 'update-track')
        {
	    if (Import_Mode == 'Y') {console.log('Import_Mode is Y ----- skip image upload message');break;}
            trackSyncIsProcessing();
            webix_message({type: "success", text: inData.Message, expire: 1200},10,forItem='',forDesc='',send2Modal=false,call=lcCall);        
            break;
        }
        else
        {
            console.log("skipped s3image update due to data-mode = update-track")
        }
        
        case "tracksync-start-conversions":
        trackSyncIsProcessing();
        webix_message({type: "info", text: inData.Message, expire: 1200},10,forItem='',forDesc='',send2Modal=true,call=lcCall); 
        break;     
        
        case "tracksync-out-of-date":
        if (inData.OS == 'darwin')
        {
            lcMTxt = "<b>TrackSync Software Update Required</b><br/><br/>Your TrackSync needs to be updated in order to start.<br/>Please perform this <b>software update</b> now.<br/>"
            webix_message({type: "error", text: lcMTxt, expire: 12000},10,forItem='',forDesc='',send2Modal=false); 
            softwareUpdateInfo();
        }
        break;           
        
        case "tracksync-now-quiet":
        console.log('passive count = ', passiveCount);
		if (gSyncTrackRunning == true)
		{
			setTimeout("location.reload();",2000);
		}
	
	if (Import_Mode == 'Y') 
	{
	    closeHelp();    
	    if (gTracks2Tag.length > 0) 
	    {
		trsu = setTimeout("admAutoTag('next');",1200);	
	    }
	    return;
	}
	
	dataWH.Artist.TSCommsGood = true;
	$$("tracksyncStatus").define("label",icon_tracksync_online);
	$$("tracksyncStatus").define("tooltip",'TrackSync is ONline');
	$$("tracksyncStatus").refresh();	
	
	// lagged call from cache tracks
        if (waitForQuiet == true) 
		{
			//location_reload();
			return;
		}
	
        if (syncTrackQry == true) 
        {
            syncTrackQry = false;
            webix.message({type: "debug", text: 'TrackSync response:  Processed..', expire: 2700});
            if (gCurrTab == 'Catalog') {setTimeout("catalogRefresh();",2400);}
        }
        
        if (gTS_Status == true)
        {
            if (inData.Passive == 'n' || inData.Passive == 'y')
            {
            
                if ($$("metaWindow") !== undefined &&  $$("metaWindow") .isVisible() == true) {closeMeta();}
            
                //trackSyncIsProcessing();
                if (gUser_Profile.Artist_Pref.Caching_Mode == 'OFF' || (gUser_Profile.Artist_Pref.Caching_Mode == 'ON'))
                {
                    //webix_message({type: "info", text: "<b>TrackSync<b/> has finished processing.  Refreshing...", expire: 1300},10,forItem='',forDesc='',send2Modal=true,call=lcCall); 
                }
                
                if (gUser_Profile.Artist_Pref.Caching_Mode == 'OFF' || (gUser_Profile.Artist_Pref.Caching_Mode == 'ON')) 
				{
					try {$$("helpWindow").hide();} catch(err){}
					//setTimeout("location_reload();",1600);
					
				}
                break;
            }
            else
            {
                if ($$("helpWindow") !== undefined)
                {
                    webix.html.triggerEvent($$("helpWindowClose").getInputNode(), "MouseEvents", "click");
                    setTimeout("location_reload();",1200);
                    break
                }
            }
            gTS_Status = false;
        }
        else
        {
            if (passiveCount > 0)
            {
                if ($$("helpWindow") !== undefined && $$("helpWindow").config.modal == true)
                {
                    webix.html.triggerEvent($$("helpWindowClose").getInputNode(), "MouseEvents", "click");
					setTimeout("location_reload();",900);		    
                    passiveCount = 0;
                    break
                }
            }
            else
            {
                passiveCount += 1;
                console.log('passivecount = ', passiveCount);
            }
            
            TSSpin('on');
        }
        break;
        
        case "meta-data-track":
        //console.log("meta-data-relay - a track is done:",inData);
        lagData = inData;
	if (Import_Mode == 'Y') {console.log('Import_Mode is Y -------- skip MetaUpdateTrack lag');catalogDeselect();break;}
        setTimeout('MetaUpdateTrack(lagData);',1200);
        break;
        
        case "track-transfer":
        //console.log("need to update display that its in progress:",inData);
        break;
        
        case "track-ready":
        if (inData.Play_Track == 'y' && askToPlay == 'y') {GetTrackLink(inData);}
        else {genToast('Whoohoo!',"Track ->&nbsp;<b>" + inData.TIT2_TrackName + "&nbsp;</b> has been updated in your Catalog. " ,'TR','success',350,3);   }
        gTrackUpdate = false;
        break;
        
        case 'track-play':
        //queueTrack(inData.TrackLink,inData.Track_ID);
        console.log("track-play");
        break
        
        case "current-state":
        MonitorStatus(inData);
        //console.log("current-state");
        break;	
        
        case "system-update":
        //console.log("system-update");     
        break;
                     

    }
} 
// ------------------------------------------------------------ //
function resetTSDir() 
{
    console.log("resetTSDir():");
    ConfirmIt(title='Reset TrackSync Catalog Folder', 
        description='Click <b>Ok</b> to Reset the TrackSync <b>Catalog folder</b>, so that you can select a new music folder.', 
        txtYes='Ok', txtNo='Cancel', fncForYes='resetTSDirGo', 
        fncForNo='cancelMsg', keyID=undefined, cancel_Msg='Request cancelled.');      
    
}
// ------------------------------------------------------------ //
function resetTSDirGo() 
{
    console.log("resetTSDirGo():");
    url = '/getobj/?nme=resetts&info=dir'+'&seq=' + seq();
    axios.get(url).then(response => 
    {
        console.log("resetTS got back: ", response);       
        webix.message({type: "success", text: "<b>Success</b><br/> " + response.data.Message, expire: 8000});
        $$("Artist_Pref.DAW_Cat_Folder").setValue('');
    },
    (error) => 
    { 
        console.log("Error:", error);
        webix.message({type: "error", text: "<b>Error</b><br/> " + response.data.Message, expire: 10000});
    }); 
}
syncTrackQry = false;
//------------------------------------------------------------- //
function syncTracks()
{
    syncTrackQry = true;
    getMonStatus();
    setTimeout('syncTracksGo();',1500);
}
gSyncTrackRunning = false;
// ------------------------------------------------------------ //
function syncTracksGo()
{
    console.log("syncTracksGo():");
	tmpData = gcPMData;
	gSyncTrackRunning = true;
    console.log('tmpData=',tmpData);
    if (gMonitorStatus == 'online')
    {
        webix.message({type: "debug", text: "Sending SYNC request to TrackSync..", expire: 2000});
        url = '/getobj/?nme=trackcheck&seq=' + seq() + '&cnv_orig_tid=' + tmpData['Convert_Orig_Track_ID'];
        axios.get(url).then(response => 
        {
            console.log("trackcheck got back", response);
            webix.message({type: "success", text: "<b>Success</b><br/> " + response.data.Message, expire: 5000});
	    
	    if ($$("tour1") && $$("tour1").isVisible()) 
	    {
		localStorage.setItem("tour1_running", 'y');  
	    }
        },
        (error) => 
        { 
            console.log("Error:", error);
            webix.message({type: "error", text: "<b>Error</b><br/> " + response.data.Message, expire: 10000});
        }); 
    }
    else
    {
        webix.message({type: "error", text: "<b>Error</b><br/>TrackSync is currently <b>OFFLINE</b>.  You need to restart TrackSync in order to use the Synchronize feature.", expire: 10000});
    }
}
// ------------------------------------------------------------ //
function stopSyncTracks()
{
    console.log("stopSyncTracks:");
    webix.message({type: "debug", text: "Sending STOP request to TrackSync..", expire: 2000});
    url = '/getobj/?nme=stoptrackcheck&seq=' + seq();
    axios.get(url).then(response => 
    {
        console.log("trackcheck got back", response);
        webix.message({type: "success", text: "<b>Success</b><br/> " + response.data.Message, expire: 5000});
        setTimeout("location.reload();",4000);
    },
    (error) => 
    { 
        console.log("Error:", error);
        webix.message({type: "error", text: "<b>Error</b><br/> " + response.data.Message, expire: 10000});
    }); 

}


gNoEventsFor10 = false;
// ------------------------------------------------------------ //
function resetTS()
{

	if (glCollab_Only == true)
	{
		showCollabOnlyMsg(extraxText = 'Reset TrackSync Link');
		return;
	}
	
    console.log("resetTS():");
    ConfirmIt(title='Reset TrackSync Link', 
        description='Click <b>Ok</b> to disconnect TrackSync from your current TrackStage Folder. TrackSync must be <b>running</b> to be Reset.', 
        txtYes='Ok', txtNo='Cancel', fncForYes='resetTSGo', 
        fncForNo='cancelMsg', keyID=undefined, cancel_Msg='Request cancelled.');      
    
}
// ------------------------------------------------------------ //
function resetTSGo()
{
    console.log("resetTSGo():");
    url = '/getobj/?nme=resetts&info=all'+'&seq=' + seq();
    axios.get(url).then(response => 
    {
        console.log("resetTS got back -> ", response);
        localStorage.removeItem("QTSW");
        setTimeout('showWelcome();', 3000);          
        webix.message({type: "success", text: "<b>Success</b><br/> " + response.data.Message, expire: 5000});
    },
    (error) => 
    { 
        console.log("Error:", error);
        webix.message({type: "error", text: "<b>Error</b><br/> " + response.data.Message, expire: 10000});
    }); 
}

gNoEventsFor10 = false;
// ------------------------------------------------------------ //
function MetaUpdateTrack(inData)
{
    if (inData.Track_ID == undefined) {tid = inData.Track;} else {tid = inData.Track_ID;}
    
    setTimeout("trackSyncIsProcessing();",800);
	try {$$("helpWindow").hide();} catch(err) {a=1;}
    showMsg = false;
    if (inData.PartCompleted == 's3imageupload') 
    {
        a=1;
        //showMsg = false;
    }
    if (inData.Event == 'created')
    {
        trackRePull(inData.Event, tid, showMsg, noPull=true);
    }
    else if (inData.Event == 'modified')
    {
        trackRePull(inData.Event, tid, showMsg, noPull=true);
    }
    else if (inData.Event == 'deleted')
    {
        try 
        {
            trackRePull(inData.Event, tid, showMsg, noPull=true);
        }
        catch(err) {a=1;}
    }
    else
    {
        // just the NOTICE
        tst = dataWH.Catalog.dataStore.getItem(tid);
        if (typeof(tst) == 'object')
        {
            trackRePull('modified', tid, showMsg, noPull=true);
        }
        else
        {
            trackRePull('created', tid, showMsg, noPull=true);
        }    
    }
    
    // see if update required to tag files table
    if ($$("metaWindow") != undefined && $$("metaWindow").config.hidden == false)
    {
        //dt = $$("catalogMetaTable").getItem(tid);
        //console.log(inData);
        for (ndx =0; ndx < catalogTags.length; ndx++)
        {
            tt = catalogTags[ndx]; 
            if (tid == tt.id)
            {
                tt.Tag_Done = 1; 
            }
        }
        $$("catalogMetaTable").refresh()
    }
    
    if (inData.All_Done == true)
    {
        setTimeout('webix_message({type: "success", text: "<b>Completed</b>:</br><br/>All Tracks have now been tagged with Metadata.<br/>(Images are currently being processed)", expire: 4500},10);',2000);
        //gCatRefresh = true;
		gCatRefresh = false;
        setTimeout('closeMeta();',2000);
    }
    
    catalogTotals();
    
}
gMsgLog = {}; // key = the message-text, data = object: { 'Created': datetime.now, 'PID': the-id}

// ------------------------------------------------------------ //
function CleanMsgLog(dtNow)
{
    hasDel = false;
    for (var key in gMsgLog) 
    {
        pkge = gMsgLog[key];
        if (dtNow > pkge.Kill_At)  {hasDel = true}
    }  
    if (hasDel == true)
    {
        for (var key in gMsgLog) 
        {
            pkge = gMsgLog[key];
            if (dtNow > pkge.Kill_At)  {delete gMsgLog[key];}
        }          
    }
    
    if (hasDel == true) {CleanMsgLog(dtNow);}
}
var g_msgObj;g_LastMsg = '';
// ------------------------------------------------------------ //
function webix_message(msgObj, filterTime, forItem='', forDesc='', send2Modal=false,call='')
{
    dtNow = new Date();
    CleanMsgLog(dtNow);
    dtNow2 = new Date(dtNow);
    dtNow2.setSeconds(dtNow.getSeconds() + filterTime);
    pkge = {'Created': dtNow, 'Kill_At': dtNow2, 'PID': seq(), 'text': msgObj.text, 'type': msgObj.type, 'for': forItem, 'Desc': forDesc} 
    g_msgObj = msgObj;
    
    // do not show it for write meta
    if ($$("metaWindow") !== undefined &&  $$("metaWindow") .isVisible() == true) {return;}
        
    if (send2Modal == true)
    {
        trackSyncIsProcessing();
        
        if (g_LastMsg == g_msgObj.text) {return;}
        g_LastMsg = g_msgObj.text;
        switch(call) 
        {
            case "tracksync-now-quiet":
            setTimeout("catalogAddTimelineMsg('', g_msgObj.text);",300);
            return;
            
            case "tracksync-start-caching" :
            setTimeout("catalogAddTimelineMsg('TrackSync', g_msgObj.text);",300);
            return;                       
            
            case "tracksync-start-conversions":
            setTimeout("catalogAddTimelineMsg('', g_msgObj.text);",300);            
            return;
            
            case "image-upload-complete":
            setTimeout("catalogAddTimelineMsg('TrackSync', g_msgObj.text);",300);            
            return;
            
            case "cachemode":
            setTimeout("catalogAddTimelineMsg('Processing', g_msgObj.text);",300);
            return;
            
            case "new-tracks-added":
            setTimeout("catalogAddTimelineMsg('Please Wait', g_msgObj.text);",300);            
            return;
            
            case "track-created":
            setTimeout("catalogAddTimelineMsg('TrackSync', g_msgObj.text);",300);            
            return;        
            
            case "track-updated":
            setTimeout("catalogAddTimelineMsg('TrackSync', g_msgObj.text);",300);            
            return;   
            
            case "track-modified":
            setTimeout("catalogAddTimelineMsg('TrackSync', g_msgObj.text);",300);            
            return;       
            
            case "track-deleted":
            setTimeout("catalogAddTimelineMsg('TrackSync', g_msgObj.text);",300);            
            return;               
        
        }
    }

    if (gMsgLog[msgObj.text] == undefined)
    {
        gMsgLog[msgObj.text] = pkge;
        gMsgList.unshift(pkge);
        webix.message(msgObj);
    }
    else
    {

    }
}
gjnk = '';
// ------------------------------------------------------------ //
function trackRePull(evtType, inID, showMsg, noRepull=false)
{
    if (inID == undefined) {return;}
    
    dataWH.Catalog.dp.config.autoupdate = false;
            
    url = '/getobj/?nme=trackEdit' + '&id=' + inID + '&seq=' + seq();
	console.log('inID=', inID);
    axios.get(url).then(response => 
    {
        console.log("track repull got back", response);
        //$$("GRP1_Grouping").setValue( response.data.track.GRP1_Grouping);
        if (evtType == 'modified' || evtType == 'moved')
        {
            tst = dataWH.Catalog.dataStore.getItem(inID);
            if (typeof(tst) == 'object')
            {        
                dataWH.Catalog.dataStore.updateItem(inID,response.data.track);
				
                if (showMsg == true) {webix_message({type: "success", text: "Track updated: " + response.data.track.File_Name+response.data.track.File_Ext, expire: 1200},10,forItem='',forDesc='',send2Modal=true,call='track-modified');} 
                
                webix_message({type: "success", text: "Track updated: " + response.data.track.File_Name+response.data.track.File_Ext, expire: 1200},10,forItem='',forDesc='',send2Modal=false,call='track-modified');
				
                if (response.data.track.Source_Track_Deleted == 'N') {$$("catalogTable").removeRowCss(inID, "src_deleted");}
				
				if (response.data.track.Tags_Pending == 'N') 
					{$$("catalogTable").removeRowCss(inID, "tags_pending");}
				else
					{$$("catalogTable").addRowCss(inID, "tags_pending");}

					if (tst.Tags_Pending == 'Y' && tst.Tags_Pending.indexOf('tags_pending') == -1)
					{						
						tst.$css = tst.$css + ' tags_pending';
					}
					else
					{
						tst.$css = tst.$css.replaceAll('tags_pending','');
					}					
				}
        }
        else if (evtType == 'created')
        {
            tst = dataWH.Catalog.dataStore.getItem(inID);
            if (typeof(tst) == 'object')
            {        
				if (tst.Tags_Pending == 'Y' && tst.Tags_Pending.indexOf('tags_pending') == -1)
				{					
					tst.$css = tst.$css + ' tags_pending';
				}
				else
				{
					tst.$css = tst.$css.replaceAll('tags_pending','');
				}
                dataWH.Catalog.dataStore.updateItem(inID,response.data.track);
				console.log('ok - updating datastore - created');
				tst.chkCatalog = 'off';
				showMsg = false;
                if (showMsg == true) {webix_message({type: "success", text: "Track created: " + response.data.track.File_Name+response.data.track.File_Ext, expire: 1200},10,forItem='',forDesc='',send2Modal=true,call='track-updated');}
				
				webix_message({type: "success", text: "Track created: " + response.data.track.File_Name+response.data.track.File_Ext, expire: 1200},10,forItem='',forDesc='',send2Modal=false,call='track-created');
                
                if (response.data.track.Source_Track_Deleted == 'N') {$$("catalogTable").removeRowCss(inID, "src_deleted");}
            }  
            else
            {
				a=1;
				console.log('skipped it cuz still pending');
				showMsg = false;
                dataWH.Catalog.dataStore.add(response.data.track);
				console.log('ok - updating datastore - added');
				gjnk = response.data.track.Track_ID;
				setTimeout('$$("catalogTable").select(gjnk);',240);
                if (showMsg == true) {webix_message({type: "success", text: "Track added: " + response.data.track.File_Name+response.data.track.File_Ext, expire: 1200},10,forItem='',forDesc='',send2Modal=true,call='track-created');}
				
				webix_message({type: "success", text: "Track added: " + response.data.track.File_Name+response.data.track.File_Ext, expire: 1200},10,forItem='',forDesc='',send2Modal=false,call='track-added');
				
                if (response.data.track.Source_Track_Deleted == 'N') {$$("catalogTable").removeRowCss(inID, "src_deleted");}
            }
        }
        else if (evtType == 'deleted')
        {
            tst = dataWH.Catalog.dataStore.getItem(inID);
            if (typeof(tst) == 'object')
            {        
				showMsg = false;
                dataWH.Catalog.dataStore.updateItem(inID,response.data.track);
                $$("catalogTable").addRowCss(inID, "src_deleted");
                if (showMsg == true) {webix_message({type: "error", text: "Track deleted: " + response.data.track.File_Name+response.data.track.File_Ext, expire: 1200},120,forItem='',forDesc='',send2Modal=true,call='track-deleted');}
				
				webix_message({type: "error", text: "Track deleted: " + response.data.track.File_Name+response.data.track.File_Ext, expire: 1200},120,forItem='',forDesc='',send2Modal=false,call='track-deleted');
				
            }
        }
        else
        {
            a = 1;
        }
        
    },
    (error) => 
    { 
        console.log("Error:", error);
    });       
}
// ------------------------------------------------------------ //
function sizeInMB(sizeInBytes)
{
    out = (sizeInBytes / (1024*1024)).toFixed(2);
    return out;
}

function formatRate(inType,inBits)
{
    if (inType == 'b') 
    {   out = (inBits / 1000).toFixed(0);}
    else {out = (inBits / 1000).toFixed(3);}
    
    if (inBits == 0) {out = '';}
    return out;
}
// ------------------------------------------------------------ //
function autolog()
{
    lAL = localStorage.getItem("tmp_al");
    if (lAL == null) {lAL = '';}
    lU = localStorage.getItem("alflds_u");
    lP = localStorage.getItem("alflds_p");
    if (lU == null) {lU = '';}
    if (lP == null) {lP = '';}
    
    if (lAL == 'n') {return;}
    
    lcEml = $$("loginEmail").setValue(lU);
    lcPwd = $$("loginPassword").setValue(lP);
    localStorage.setItem("tmp_al", '');
    localStorage.setItem("alflds_u", '');
    localStorage.setItem("alflds_p", '');
    
    //do the auto login here
    goLogin(n2fa='true',next='install');
    
}
// ------------------------------------------------------------ //
function DefaultParticipant(mde)
{

    if (mde == 3)
    {
        $$("Target.First_Name").setValue(gUser_Profile.Artist.First_Name);
        $$("Target.Last_Name").setValue(gUser_Profile.Artist.Last_Name);
        $$("Target.Company_Name").setValue(gUser_Profile.Artist.Publisher_Name);
        $$("Target.PRO_Name").setValue(gUser_Profile.Artist.Publisher_PRO);
        $$("Target.IPI_Num").setValue(gUser_Profile.Artist.Publisher_PRONum);
        $$("Target.First_Name").setValue(gUser_Profile.Artist.First_Name);
        $$("Target.Last_Name").setValue(gUser_Profile.Artist.Last_Name);
    }
    if (mde == 1)
    {
        $$("Contributor.Company_Name").setValue(gUser_Profile.Artist.Publisher_Name);
        $$("Contributor.First_Name").setValue(gUser_Profile.Artist.First_Name);
        $$("Contributor.Last_Name").setValue(gUser_Profile.Artist.Last_Name);
    } 
    if (mde == 2)
    {
        //$$("Right_Holder.Company_Name").setValue(gUser_Profile.Artist.Publisher_Name);
        $$("Right_Holder.PRO_Name").setValue(gUser_Profile.Artist.PRO_Name);
        $$("Right_Holder.IPI_Num").setValue(gUser_Profile.Artist.CAEIPI_Number);
        $$("Right_Holder.First_Name").setValue(gUser_Profile.Artist.First_Name);
        $$("Right_Holder.Last_Name").setValue(gUser_Profile.Artist.Last_Name);
        $$("Right_Holder.Holder_Phone").setValue(gUser_Profile.User.Cell_Number);
        $$("Right_Holder.Holder_Email").setValue(gUser_Profile.Artist.Email);	
    }    
}
// ------------------------------------------------------------ //
function userLogout()
{
    webix.message({type: "debug", text: 'Logging Off...', expire: 2200})
    setTimeout("location.replace('/logout/?next=welcome');",1200);
}
// ------------------------------------------------------------ //
function forceLogout(next='')
{
    console.log("forceLogout():");
    gPusher.disconnect();
    try {AblyRealtime.realtime.close();} catch(err) {a=1;}
    if (next=='welcome') {setTimeout("location.replace('/logout/?next=welcome');",1000);}
    else {setTimeout("location.replace('/logout/?next=install');",1000);}
    
}
var screenTimer = 0;
var screenInterval;
// ------------------------------------------------------------ //
function timerScreenCap() 
{
    if (recIsPaused == false) {screenTimer = screenTimer + 1;}
    timeLeft = gUser_Profile.Artist.Max_Screen_Cap - screenTimer;
    $$("recMini_Time").setHTML(formatMinSec(timeLeft));
    if (screenTimer > gUser_Profile.Artist.Max_Screen_Cap) {recorderAction('stop');}      
}
     
var lastIdleDT = new Date();
$(window).focus(function() 
{
	console.log('checkAwaken():');
	checkAwaken('focus');
});
// ------------------------------------------------------------ //
function checkAwaken(src='timer')
{
	var now = new Date();
	var diffMs = (now - lastIdleDT);
	var diffMins = Math.round(((diffMs % 86400000) % 3600000) / 60000);
	if (diffMins > 60)
	{
		if (src == 'timer')
		{
			console.log('timerIncrement: refresh required');
			location.reload();
		}
		else
		{
			console.log('window focus event: refresh required');
			location.reload();
		}
	}
	lastIdleDT = new Date();
	
	if (($$("helpWindow")) == 'object')
	{
		setTimeout('$$("helpWindowClose").show();',800);
	}
}
// ------------------------------------------------------------ //
function timerIncrement() 
{
    idleTime = idleTime + 1;
    console.log("timerIncrement ---> Idle time:", idleTime);    
    if (idleTime > 240) {forceLogout();} 
	
	checkAwaken('timer');
	
	lastIdleDT = new Date();	
}
        
if (gcPageTitle != 'TrackStage | Welcome' && gcPageTitle != 'TrackStage:  Welcome')
{
    if (gcDAW != 'y')
    {
        //console.log("timeout feature is engaged");
        var idleInterval = setInterval(timerIncrement, 60000);
    }
}

//Zero the idle timer on mouse movement.
$(this).mousemove(function (e) {
    idleTime = 0;		    
});
//Zero the idle timer on keypress
$(this).keypress(function (e) {
    idleTime = 0;
});
// ------------------------------------------------------------ //
function toTitleCase(str) {
  return str.replace(
    /\w\S*/g,
    function(txt) {
      return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
    }
  );
}



function copyTextToClipboard(text) {
  var textArea = document.createElement("textarea");


  textArea.style.position = 'fixed';
  textArea.style.top = 0;
  textArea.style.left = 0;

  textArea.style.width = '2em';
  textArea.style.height = '2em';

  textArea.style.padding = 0;

  textArea.style.border = 'none';
  textArea.style.outline = 'none';
  textArea.style.boxShadow = 'none';

  textArea.style.background = 'transparent';

  textArea.value = text;

  document.body.appendChild(textArea);
  textArea.focus();
  textArea.select();

  try {
    var successful = document.execCommand('copy');
    var msg = successful ? 'successful' : 'unsuccessful';
    console.log('Copying text command was ' + msg);
  } catch (err) {
    console.log('Oops, unable to copy');
  }

  document.body.removeChild(textArea);
}
// ------------------------------------------------------------ //
function copyly2cb()
{

    tkw = $$("Lyrics").getValue();
    lf = tkw.indexOf('Tags/Data:');
    if (lf > 0)
    {
        tkw = tkw.substring(0,lf);
    }

    if (tkw.length > 0) 
    {
        tkw = tkw.replaceAll("Lyrics:<br><br><br>","");
        tkw = tkw.replaceAll("Lyrics:<br><br>","");
        tkw = tkw.replaceAll("Lyrics:<br/","");
        tkw = tkw.replaceAll("Lyrics:","");
        tkw = tkw.replaceAll("<br/>","##nl##");
        tkw = tkw.replaceAll("<br>","##nl##");
        tkw = tkw.replaceAll("<div>","##nl##");
        tkw = tkw.replace(/(<([^>]+)>)/g, "");
        tkw = tkw.replaceAll('##nl##','\n')
        copyTextToClipboard(tkw);
        webix_message({type: "success", text: "<b>Ok:</b> Track Lyrics have been copied to the clipboard!", expire: 3000},6);       
    }
    else
    {
        webix_message({type: "error", text: "<b>Oops:</b> There is nothing here to copy to the clipboard.", expire: 10000},6);  
    }
    return;
}
// ------------------------------------------------------------ //
function printLyrics()
{
    url = '/getobj/?mde=editform&id='+gCurrTrack.Track_ID+'&nme='+'printlyrics&seq='+seq();
    window.open(url);

}
// ------------------------------------------------------------ //
function contactsSave(rollout=false)
{
    lcText = "<span style='line-height:2;'>Would you like to update ALL Contact References with these changes?</span>";
    webix.confirm(
     {     
      title: "<span style='line-height:2.5;'>Update All?</span>",
      text: lcText,
      ok: "Save to All",
      cancel: "Just Save",
      width:380,
    }).then(function(result)
    {
        contactsSaveGo(rollout=true)
        
    }).fail(function(){

	contactsSaveGo(rollout=false)       

    }); 
}
// ------------------------------------------------------------ //
function contactsSaveGo(rollout=false)
{
    
    if ($$("contactsEditForm").validate() == true)
    {
	bm = $$("Contact.Birth_Month").getValue();
	bd = $$("Contact.Birth_Day").getValue();
	$$("Contact.Birthday").setValue(bm + ', ' + bd);
	if (rollout == true) {$$("Contact.Rollout").setValue('y');}    // switch to rollout changes
	
	contact_data = $$("contactsEditForm").getValues();
	dataWH.Contacts.dataStore.updateItem(contact_data.Contact.Cont_ID,contact_data.Contact);
	dataWH.Contacts.dp.save(contactsCurrID.row,'update');	
    } 
    else
    {
	webix_message({type: "error", text: "<b>Error:</b>&nbsp;Please correct any errors and retry", expire: 3000},1,'Contacts Update',$$("contactsEditForm").elements['Contact.Email'].data.value);
    }    

};
// ------------------------------------------------------------ //
function contactsCancel()
{
    $$("contactsEditForm").parse(gCurrContact);
};
// ------------------------------------------------------------ //
function copyslnk2cb(lnk)
{
    tocb = lnk;
    if (tocb.length > 0) 
    {
        copyTextToClipboard(tocb);
        webix_message({type: "success", text: "<b>Ok:</b><br/> The link has been copied to the clipboard!", expire: 7000},6);       
    }
    else
    {
        webix_message({type: "error", text: "<b>Oops:</b><br/> There is no link to copy", expire: 4000},6);  
    }
    return;    
}
// ------------------------------------------------------------ //
function copysl2cb()
{
    tocb = gCurrPitch.Pitch.Full_Share_Link;
    if (tocb.length > 0) 
    {
        copyTextToClipboard(tocb);
        webix_message({type: "success", text: "<b>Ok:</b><br/> The Share Link has been copied to the clipboard!", expire: 6000},6);       
    }
    else
    {
        webix_message({type: "error", text: "<b>Oops:</b><br/> There is no Share Link to copy", expire: 8000},6);  
    }
    return;    
}
// ------------------------------------------------------------ //
function testsharelink()
{
    tocb = gCurrPitch.Pitch.Full_Share_Link;
    if (tocb == undefined)
    {
	tocb = gCurrPitch.Pitch.Pitch_Link_URL;    
    }

    if (tocb.length > 0) 
    {	
	tocb = tocb + '?notrack=y';
        webix_message({type: "debug", text: "<b>Ok:</b><br/> Loading Share Link page for testing...", expire: 3000},6);  
	window.open(tocb,'_blank');
    }
    else
    {
        webix_message({type: "error", text: "<b>Oops:</b><br/> There is no Share Link to copy", expire: 8000},6);  
    }
    return;    
}
// ------------------------------------------------------------ //
function copyAgglink()
{
    tocb = gCurrTarget.Target.Target_Agreement;
    if (tocb.length > 0) 
    {
        copyTextToClipboard(tocb);
        webix_message({type: "success", text: "<b>Ok:</b><br/> The link has been copied to the clipboard!", expire: 6000},6);       
    }
    else
    {
        webix_message({type: "error", text: "<b>Oops:</b><br/> There is no link to copy", expire: 8000},6);  
    }
    return;    
}
// ------------------------------------------------------------ //
function copyUplink()
{
    tocb = gCurrTarget.Target.Target_Submit_URL;
    if (tocb.length > 0) 
    {
        copyTextToClipboard(tocb);
        webix_message({type: "success", text: "<b>Ok:</b><br/> The link has been copied to the clipboard!", expire: 6000},6);       
    }
    else
    {
        webix_message({type: "error", text: "<b>Oops:</b><br/> There is no link to copy", expire: 8000},6);  
    }
    return;    
}
// ------------------------------------------------------------ //
function copykw2cb()
{
    tkw = $$("TMOO_Keywords").getValue();
    tge = $$("TCON_Genre").getValue();
    sl = $$("Sounds_Like").getValue();
    if (tkw.length > 0)
    {
        if (tge.length > 0) {tkw = tkw + ',' + tge;}
    }
    else
    {
        if (tge.length > 0) {tkw = tge;}
    }
    
    if (sl.length > 0) {tkw = tkw + ',' + sl;}
    
    if (tkw.length > 0) 
    {
        copyTextToClipboard(tkw);
        webix_message({type: "success", text: "<b>Ok:</b> All Keywords have been copied to the clipboard!", expire: 3000},6);       
    }
    else
    {
        webix_message({type: "error", text: "<b>Oops:</b> There is nothing here to copy to the clipboard.", expire: 10000},6);  
    }
    return;
}
// ------------------------------------------------------------ //
function doesFileExist(urlToFile) {
    var xhr = new XMLHttpRequest();
    xhr.open('HEAD', urlToFile, false);
    xhr.send();
     
    if (xhr.status == "404" || xhr.status == "403") {
        return false;
    } else {
        return true;
    }
}

gLastCatTog = 'shrink';
function catalogTogAll2()
{
    if (gLastCatTog == 'shrink') {gLastCatTog = 'expand';} else {gLastCatTog = 'shrink';}
    
    catalogExpandAllSubs(gLastCatTog);
}

function catalogTogAll(forceTo='')
{
    if (forceTo == '')
    {
        if (dataWH.Catalog.Settings.expandedList.length > 0)
        {
            dataWH.Catalog.Settings.expandedList = [];
            catalogFilter(dataWH.Catalog.Settings.filterText);
        }
        else
        {
            $$("catalogTable").data.each(function(obj)
            {          
                if (obj.Primary_Track == true && obj.Subs_Count > 0) 
                {
                    dataWH.Catalog.Settings.expandedList.push(obj.Track_ID);
                }
            }); 
            catalogFilter(dataWH.Catalog.Settings.filterText);
        }
    }
    else
    {
        if (forceTo == 'open')
        {
            $$("catalogTable").data.each(function(obj)
            {          
                if (obj.Primary_Track == true && obj.Subs_Count > 0) 
                {
                    dataWH.Catalog.Settings.expandedList.push(obj.Track_ID);
                }
            }); 
            catalogFilter(dataWH.Catalog.Settings.filterText);        
        }
        else
        {
            dataWH.Catalog.Settings.expandedList = [];
            catalogFilter(dataWH.Catalog.Settings.filterText);        
        }
    
    }
}

// ------------------------------------------------------------ //
function getDefTask(inID)
{
    arr = gUser_Profile.Artist_Pref.Default_Activities_Data;
    for (ndx =0; ndx < arr.length; ndx++)
    {
        tObj = arr[ndx];
        if (tObj.id == inID) {return tObj;}        
    }
    return {};
}
// ------------------------------------------------------------ //
function defShareLink(obj)
{
    if (obj.ShareLink_Active == false && obj.ShareLink_Base.length == 0)
    {
        bsn = obj.First_Name.trim() + '-' + obj.Last_Name.trim();
        bsn = bsn.toLowerCase();
        bsn = bsn.replaceAll('   ',' ').replaceAll('  ',' ');    
        $$("Artist.ShareLink_Base").setValue(bsn);
    }
}
// ------------------------------------------------------------ //
function UPDefTasksTogItem(id,item)
{
    obj = getDefTask(id);
    if (obj.Deleted == 'N') {obj.Deleted = 'Y'} else {obj.Deleted = 'N';}
    $$("UPDefTasks").refresh();
}
// ------------------------------------------------------------ //
function UPDefTasksTogIcon(obj,item)
{
    html = "<div class='webix_secondary'>";
    if (item == 'deleted')
    {
        html += `<div style='background:transparent;' title='Delete this task' onclick='UPDefTasksTogItem("##cts##","##item##");' class='webix_table_checkbox custom_toggle'>`;
        if (obj.Deleted == 'N') {html += icon_deleted_no;}
        else {html += icon_deleted_yes;}  
    }    

    html += "</div></div>";
    html = html.replace('##cts##',obj.id+'').replace('##item##',item);
    return html;
}
// ------------------------------------------------------------ //
function UPNewTask()
{
    console.log('UPNewTask');
    newEntry = 
    {
        id: seq(),
        projstep: "",
        anum: "-new-", 
        acat: "",
        adesc: "add your task description here",
        Deleted: 'N',
    };  
    nid = $$("UPDefTasks").add(newEntry);
    $$("UPDefTasks").select(nid);
    $$("UPDefTasks").showItem(nid);
    $$("UPDefTasks").editRow(nid);    
}

rmode = 'n';
async function UPSaveTasks()
{
    console.log('UPSaveTasks');
    arr = gUser_Profile.Artist_Pref.Default_Activities_Data;
    $$("UPDefTasks").eachRow(function(row)
    { 
        var rec = $$("UPDefTasks").getItem(row);
        fnd = getDefTask(rec.id);
        
        xx = fnd.acat;        
        if (xx == undefined)
        {
            gUser_Profile.Artist_Pref.Default_Activities_Data.push(rec);
        }

    });    
    
    url = '/data_profile/?mde=storedeftasks&redef=' + rmode + '&seq=' + seq();
    //for (ndx =0; ndx < arr.length; ndx++)
    //{
        //tObj = arr[ndx];
        //if (tObj.anum) == '-1'   
    //}      
    pkge = {'Default_Activities': arr};
    response = await axios.post(url, pkge);

    gRes = response;
    resData = response.data; 

    if (resData.status == 'error')
    {
        webix.message({type: "error", text: "<b>Error:</b>&nbsp;&nbsp;"+resData.message, expire: 10000});
    }
    else
    {
        gUser_Profile.Artist_Pref.Default_Activities_Data = resData.Default_Activities_Data;
        gUser_Profile.Artist_Pref.Dev_Default_Activities = resData.Dev_Default_Activities;
        try
        {
          $$("UPDefTasks").clearAll();
          $$("UPDefTasks").parse(gUser_Profile.Artist_Pref.Default_Activities_Data);
        }
        catch(err) {a=1;}          
        webix.message({type: "success", text: "<b>Success:</b>&nbsp;&nbsp;"+resData.message, expire: 1500});
        if (rmode == 'y') {setTimeout("UPReloadTasks();",1700);}
    }    
    
  rmode = 'n';
}
function UPResetTasks()
{
    rmode = 'y';
    UPSaveTasks();
}

function UPReloadTasks()
{
    console.log('UPReloadTasks');
    {setTimeout("location.reload();",800);}
}

function pEditWinSet()
{

    $$("$kanbaneditor1").define("width",kww);
    $$("$kanbaneditor1").define("height",khh);
    $$("$kanbaneditor1").resize();
    $('div[view_id="$kanbaneditor1"]').height(710);
}


function projectsACTSNew()
{
    newEntry = 
    {
        Act_ID: '0',
        Status: "Pending", 
        Category: "Development",
        Description: "New Task",
        Notes: '...',
        Due_Date: '',   
        Deleted: 'N',
    };  
    nid = $$("projectsACTS").add(newEntry);
    $$("projectsACTS").select(nid);
    $$("projectsACTS").showItem(nid);
    $$("projectsACTS").editRow(nid);
}

function projectsCardExtra(item)
{

  out = '';
  const d = new Date();
    
  if (item.Overdue_Task.length > 0)
  {
    out += '<br/><span style="color:darkOrange;font-weight:normal;font-size:0.80em;background:rgba(255, 255, 255, 0.9);border-radius:5px;padding:2px;">Task: ' + item.Overdue_Task + '</span>';
  }
  if (item.Deadline_Short.length > 0)
  {
    ds = 'Due: ' + item.Deadline_Short;
    
    if ((item.Deadline_Date < d && item.Data_Entry_Level < 101) || (item.Deadline_Passed == true && item.Data_Entry_Level < 100 && item.Deadline_Date < d))
    {clr = 'darkRed';} 
    else 
    {
        clr = '#888888';
        //if (item.Deadline_Passed == false && item.Data_Entry_Level == 100) {ds = '';} 
    }
    out += '<br/><span style="color:' + clr + ';font-weight:normal;font-size:0.80em;background:rgba(255, 255, 255, 0.9);border-radius:5px;padding:2px;">' + ds + '</span>';
  }  
  
  return out;
}

function projectsPctCompleted(obj)
{
    out ='';
    all = 0;done = 0;
    ophase = '';otype = '';
    
    if (gACTS.length == 0) {arr = obj.Activities;} else {arr = gACTS;}
    for (ndx =0; ndx < arr.length; ndx++)
    {
        o = arr[ndx];
        if (o.Related_ID == obj.Proj_ID) 
        {       
          ophase = obj.Project_Phase;
          otype = obj.Project_Status;
          if (o.Status != 'Ignore') {all += 1;}                
          if (o.Status == 'Complete') {done += 1;}
        }        
    } 
    if (ophase == 'Concept') {return [];}
    else
    {
      if (all == 0) {return ['NEW'];}
      else
      {
        dv = done / all;
        pct = Math.round(dv*100);
        out = pct + '% (' + done + '/' + all + ')';
        return [out];
      }
    }
    
}
cat_refs = '';

function projectsGetArtistProjOrder(inPID)
{
    // load artist's personal projects order into each record
      for (ndx =0; ndx < cat_refs.Project_Col_Order.length; ndx++)
      {
          o = cat_refs.Project_Col_Order[ndx];  
          if (o.pI == inPID) {return o.pN;}

      }    
    return 0;
}

function projectsResort()
{
  // sort each kanban column ... 
  arr = ('0,' + gUser_Profile.Artist_Pref.Dev_Steps + ',10').split(',');

  for (ndx =0; ndx < arr.length; ndx++)
  {
        stp = parseInt(arr[ndx]); 
        stat = devStep2Status(stp);
        $$("projectsKB").queryView({view: "kanbanlist", status: stat}).sort({dir: "asc", by: "Project_Col_Order", as: "int"}); 
  }      
}

function projectsAfterLoad()
{
  //console.log('this is projectsafterload');
  $$("projectsKB").data.each(function(obj)
  {
        obj.text = obj.Project_Name + projectsCardExtra(obj);
        atag = projectsPctCompleted(obj);
        obj.tags = atag;
        pc = parseInt(obj.Project_Color) - 1;
        obj.color = cat_refs.Project_Colors[pc]['color'];
        obj.Project_Col_Order = projectsGetArtistProjOrder(obj.Proj_ID);
        
        $$("projectsKB").refresh(obj.id);

  });
  
  // ------------------------------------------------------------ //
  url2 = '/kbdata/?mde=catref&seq=' + seq();
  axios.get(url2).then(response => 
  {
      cat_refs = response.data.cat_refs
      //console.log("back from catref",cat_refs);     
      arr = response.data.cat_refs.Default_Genre.results;
      for (ndx =0; ndx < arr.length; ndx++)
      {
          o = arr[ndx];  
          o.value = o.text;
          delete o.text;
      }

      setTimeout("projectsResort();",200);    
      
      if (projectIsNew == true)
      {
        $$("projectsKB").queryView({view: "kanbanlist", status: 'Concept'}).sort({dir: "asc", by: "Project_Col_Order", as: "int"});
      }
  });      
}
  
projectIsNew = false;
async function projectsNew()
{

    if (glCollab_Only == true)
	{
		showCollabOnlyMsg(extraxText = 'Add A New Project');
		return;
	}
	
    gACTS = []; gDOCS = [];gVET = [];gVSUsers = [];
    gProjOtherCollabs_Vals = [];
    gProjOtherCollabs_List = [];
    gProjCollabsInvited_Vals = [];
    gProjCollabsInvited_List = [];  
    
    try {$$("Other_Collabs_View").setValue('');} catch(err){a=1;}
    try {$$("Collabs_Invited_View").setValue('');} catch(err){a=1;}
	
    url = '/kbdata/?mde=editform&id=00000000000&newrec=y&seq='+seq();
    await axios.get(url).then(response => 
    {
        objData = response.data;
        gCurrProjectItem = objData.Data;
	
        projectsEditLevel = 'full-edit'; // read-only, assigned-task, full-edit
        projectsEditMain = true;
        projectsEditAssigned = true;
        newEntry = objData.Data;
        webix.message({type: "success", text: "<b>Success:</b>&nbsp; Your NEW Creative project has been <b>ADDED</b> to Concepts.", expire: 4000});
        projectIsNew = true;
        projectsRefresh(clearFirst=false);
	$$("col_Concepts").expand();
        return;
    },
    (error) => 
    { 
	if (error.response.status == 502)
	{
	    webix_message({type: "error", text: "<b>Error:</b>&nbsp;TrackStage is currently offline.  Please try back in a few minutes.", expire: 10000},1);
	    return;	
	}
	
        webix.message({type: "error", text: "<b>Error:</b>&nbsp; Unable to add NEW Creative project.", expire: 10000});
    });     
}
// ------------------------------------------------------------------------------------- //
async function Inform_Collabs(includeMsg)
{
    url = '/kbdata/?mde=tellothers&seq='+seq();
    data = {"Proj_ID": gCurrProjectItem.Proj_ID, "Include_Msg": includeMsg}
    await axios.post(url, data).then(response => 
    {
        webix.message({type: "success", text: "<b>Success:</b>&nbsp; Your collaborators have been informed of changes.", expire: 6000});
        return;
    },
    (error) => 
    { 
	if (error.response.status == 502)
	{
	    webix_message({type: "error", text: "<b>Error:</b>&nbsp;TrackStage is currently offline.  Please try back in a few minutes.", expire: 10000},1);
	    return;	
	}    
    
        webix.message({type: "error", text: "<b>Error:</b>&nbsp; Unable to contact server.", expire: 10000});
    });
}
// ------------------------------------------------------------------------------------- //
function projectsBeforeAndAfter(meth, resp, id, details,tellOthers=false,includeMsg='')
{
  //console.log('projectsBeforeAndAfter:', meth, resp, id, details);

  if (meth == 'before')
  {
    try 
    {
        gProjOtherCollabs_Vals = $$("Other_Collabs_View").getValue();
        gProjCollabsInvited_Vals = $$("Collabs_Invited_View").getValue();
    }
    catch(err) {a=1;}
    resp.data.Field_Misc_Bin = JSON.stringify({'Collabs_Invited_View': gProjCollabsInvited_Vals, 'Other_Collabs_View': gProjOtherCollabs_Vals, 'gDragOrder': gDragOrder});

    kbCardAccess = false;
    try {$$("projectsACTS").editStop();} catch(err) {a=1;}
    
    if (gProjectClock.length > 0) 
    {
        if ($$(gProjectClock).getValue() == 1)
        {
            webix.html.triggerEvent($$(gProjectClock).getInputNode(), "MouseEvents", "click");
        }
        gCurrProjectItem[gProjectClock] = $$(gProjectClock).config.dataValue;
        resp.data[gProjectClock] = $$(gProjectClock).config.dataValue;
        gProjectClock = '';
        
    }
    
    if (resp.operation == 'delete')
    {
	forArti = resp.data.Arti_ID;
        if (forArti != gUser_Profile.Artist.Arti_ID)
        {
             webix.message({type: "error", text: "<b>Error:</b>&nbsp; Not allowed to DELETE Creative Project.", expire: 10000});
            return false;
        }
    }
    if (resp.operation == 'update')
    {
        try
        {notesVal = $$("Project_Area_Notes").getValue();} catch(err) {notesVal = null;}
        if (notesVal != null)
        {
            if      (resp.data.Project_Status == 'Concept')        {resp.data.Concept_Notes = notesVal;}
            else if (resp.data.Project_Status == 'Composition')    {resp.data.Compose_Notes = notesVal;}
            else if (resp.data.Project_Status == 'Arrangement')    {resp.data.Arrange_Notes = notesVal;}
            else if (resp.data.Project_Status == 'Production')     {resp.data.Produce_Notes = notesVal;}
            else if (resp.data.Project_Status == 'Edits')          {resp.data.Edits_1_Notes = notesVal;}
            else if (resp.data.Project_Status == 'Mixing')         {resp.data.Mix_Notes = notesVal;}
            else if (resp.data.Project_Status == 'Versions')       {resp.data.Edits_2_Notes = notesVal;}
            else if (resp.data.Project_Status == 'Mastering')      {resp.data.Master_Notes = notesVal;}
            else if (resp.data.Project_Status == 'Administration') {resp.data.Admin_Notes = notesVal;}
            else if (resp.data.Project_Status == 'Release')        {resp.data.Release_Notes = notesVal;}
            else if (resp.data.Project_Status == 'Archive')        {resp.data.Archive_Notes = notesVal;}   
        }
        
        try
        {deadVal = $$("Area_Deadline_Date").getValue();} catch(err) {deadVal = null;}
        if (deadVal != null)
        {
            if      (resp.data.Project_Status == 'Concept')        {resp.data.Concept_Deadline = deadVal;}
            else if (resp.data.Project_Status == 'Composition')    {resp.data.Compose_Deadline = deadVal;}
            else if (resp.data.Project_Status == 'Arrangement')    {resp.data.Arrange_Deadline = deadVal;}
            else if (resp.data.Project_Status == 'Production')     {resp.data.Produce_Deadline = deadVal;}
            else if (resp.data.Project_Status == 'Edits')          {resp.data.Edits_1_Deadline = deadVal;}
            else if (resp.data.Project_Status == 'Mixing')         {resp.data.Mix_Deadline = deadVal;}
            else if (resp.data.Project_Status == 'Versions')       {resp.data.Edits_2_Deadline = deadVal;}
            else if (resp.data.Project_Status == 'Mastering')      {resp.data.Master_Deadline = deadVal;}
            else if (resp.data.Project_Status == 'Administration') {resp.data.Admin_Deadline = deadVal;}
            else if (resp.data.Project_Status == 'Release')        {resp.data.Release_Deadline = deadVal;}
            else if (resp.data.Project_Status == 'Archive')        {resp.data.Archive_Deadline = deadVal;}   
        }        
    
        if (gCurrProjectItem.hasOwnProperty('id') == false) {gCurrProjectItem = resp.data;projectsEditLevel = gCurrProjectItem.Project_Edit_Level} // for comments
        
        if (projectsEditLevel == 'read-only' && gCurrProjectItem.Arti_ID != gUser_Profile.Artist.Arti_ID)
        {
             webix.message({type: "error", text: "<b>Error:</b>&nbsp; Not allowed to UPDATE Creative Project record.", expire: 10000});
             setTimeout("kbCardAccess = true;",600);
             setTimeout("projectsRefresh();",800);
             return false;
        }
    }    
    if (resp.data.Project_Status != 'Concept' && $$("projectsACTS") != undefined)
    {
      $$("projectsACTS").eachRow(function(row)
      { 
          var rec = $$("projectsACTS").getItem(row);
          fnd = getActivity(rec.id);
          
          xx = fnd.Arti_ID;        
          if (xx == undefined)
          {
            gACTS.push(rec);
          }
  
      });    
      resp.data.Activities = gACTS;
    }
    resp.data.Documents = gDOCS;    
    justTracks();
  }
  
  if (meth == 'after')
  {  
    gDragOrder = {} 
    if (resp.Call == 'delete')
    {
      webix.message({type: "success", text: "<b>Success:</b>&nbsp; Your Creative project has been <b>DELETED</b>.", expire: 4600});
      if (kbCardAccess == false) {kbCardAccess = true;}
    }
    else if (resp.Call == 'insert')
    {
      webix.message({type: "success", text: "<b>Success:</b>&nbsp; Your Creative project has been <b>ADDED</b>.", expire: 4600});
    }        
    else 
    {
    
      gACTS = resp.newObj.Activities;
      
      gCurrProjectItem.Proj_ID.comments = resp.newObj.comments;
      kbItem = $$("projectsKB").data.getItem(gCurrProjectItem.Proj_ID);

      kbItem.comments = resp.newObj.comments;
      kbItem.Other_Collabs = resp.newObj.Other_Collabs;
      kbItem.Collabs_Invited = resp.newObj.Collabs_Invited;
      
      card = $$("projectsKB").getItem(id);
      card.Project_Time = resp.newObj.Project_Time;
      card.Overdue_Task = resp.newObj.Overdue_Task;
      card.Deadline_Short = resp.newObj.Deadline_Short;
      card.Data_Entry_Level = resp.newObj.Data_Entry_Level;
      card.Deadline_Passed = resp.newObj.Deadline_Passed;
      card.text = card.Project_Name + projectsCardExtra(card);  

      aarr = projectsPctCompleted(card);
      card.tags = aarr;
      if (card.Project_Color.length > 3) {card.Project_Color = '1';}
      pc = parseInt(card.Project_Color) - 1;
      card.color = cat_refs.Project_Colors[pc]['color']

      $$("projectsKB").refresh(id);

      if (isMoving == true) {isMoving = false;projectsRefresh(clearFirst=false);}
      webix.message({type: "success", text: "<b>Success:</b>&nbsp; Your Creative project has been saved.", expire: 3200});
      kbCardAccess = true;
      if (resp.newObj.Data_Entry_Level == 100 && resp.Next_Stage != '' && resp.Next_Stage != resp.newObj.Project_Status)
      {
        //webix.confirm(
        //{
          //title:"Stage Completed",
          //ok: "Yes", cancel: "No",
          //text: "Do you want to advance this Creative Project to the <b>" + resp.Next_Stage + "</b> stage?"
        //})
          //.then(function()
          //{
              //item = $$("projectsKB").getItem(resp.newObj.id);
              //projectsUpdateStatus(item,resp.Next_Stage);
              //$$("projectsKB").refresh(resp.newObj.id);
              //setTimeout("location.reload();",900);
          //})    
      }
      
    }
    
    // ask to inform collaborators?
    collab_message = '';
    tell_collabs = false;
    if (checkForCollabs() == true)
    {
        webix.prompt(
         {
          title: "Inform Collaborators?",
            width: 500,
            text: 'Include Note',
          ok: "Yes",
          cancel: "No",
          input: {
            placeholder: "Send a note to all..",
          },
          width:500,
        }).then(function(result)
        {
            collab_message = result;
            tell_collabs = true;    
            Inform_Collabs(collab_message);

            
        }).fail(function(){
            collab_message = '';
            tell_collabs = false; 
      
        });          
    }    
  }
  
}
// ------------------------------------------------------------ //
function projectsFilter()
{

  filtOn = $$("projectsSearchFld").getValue().toLowerCase();
  
    if (filtOn == '') 
	{webix.html.removeCss($$("projectsSearchFld").getNode(), "pasted_data");}
    else 
	{webix.html.addCss($$("projectsSearchFld").getNode(), "pasted_data");}    
  
          
  $$("projectsKB").filter(function(task)
  {
      fnd = (task.Project_Notes.toLowerCase().indexOf(filtOn) > -1 || task.Project_Name.toLowerCase().indexOf(filtOn) > -1 || task.Project_TCON_Genre.toLowerCase().indexOf(filtOn) > -1);
      if (fnd == true) return fnd;
      
      if ($$("swSrchTasks").getValue() == 1)
      {
        arr = task.Activities;
        for (ndx =0; ndx < arr.length; ndx++)
        {
            o = arr[ndx];
            //console.log(o.Project_Name)
            if (o.Notes.toLowerCase().indexOf(filtOn) > -1 || o.Description.toLowerCase().indexOf(filtOn) > -1)   {return true;}  
        } 
      }
      
      if ($$("swSrchDocs").getValue() == 1)  
      {
        arr = task.Documents;
        for (ndx =0; ndx < arr.length; ndx++)
        {
            o = arr[ndx];
            //console.log(o.Project_Name)
            if (o.projNotes.toLowerCase().indexOf(filtOn) > -1 || o.projFile_Name.toLowerCase().indexOf(filtOn) > -1)   {return true;}  
        } 
      }
      
  });
}

gACTS = []; gDOCS = [];gVET = [];gVSUsers = [];
// ------------------------------------------------------------ //
function betterRemoveMsg(newTxt)
{
    khhh = $(".webix_popup_text").first().find('span').html();
    if (khh != undefined)
    {
      khhh = khhh.replace('The card will be deleted permanently, are you sure?','Permanently delete this <br/><b>Creative Project</b> now?'); 
      $('.webix_popup_text').first().find('span').html(khhh);
    }
}

// ------------------------------------------------------------ //
async function projectsPullForm(editor,obj,noFormRequired=false)
{
    
    arr = cat_refs.Default_Genre.results;
    for (ndx =0; ndx < arr.length; ndx++)
    {
        o = arr[ndx];  
        o.value = o.text;
        delete o.text;
    }
      
    loadcnt += 1;
    url = '/kbdata/?mde=editform&id=' + obj.id + '&seq='+seq();
    //console.log("projectsPullForm",loadcnt);
    gACTS = [];
    
    if (noFormRequired == false)
    {
	theForm = editor.getForm();
	webix.ui([], theForm);
	theForm.refresh();  

    }
    
    gProjOtherCollabs_Vals = [];
    gProjOtherCollabs_List = [];
    gProjCollabsInvited_Vals = [];
    gProjCollabsInvited_List = [];        
    
    await axios.get(url).then(response => 
    {
        frmContents = eval(response.data.Form_Contents);
        objData = response.data;
        gACTS = eval(objData.Activities);
        gDOCS = eval(objData.Data.Documents);
	gVET = justTracks();
        gCurrProjectItem = objData.Data;
	
	if (noFormRequired == true) {return;}
	
        projectsEditMain = true;
        projectsEditAssigned = true;
        projectsEditLevel = obj.Project_Edit_Level;
        if (obj.Project_Edit_Level == 'read-only' && obj.Arti_ID != gUser_Profile.Artist.Arti_ID)
        {
            projectsEditMain = false;
            projectsEditAssigned = false;        
        }
        else if (obj.Project_Edit_Level == 'project-lead' && obj.Arti_ID != gUser_Profile.Artist.Arti_ID && obj.Key_Arti_ID != gUser_Profile.Artist.Arti_ID)
        {
            projectsEditMain = false;
            projectsEditAssigned = false;         
        }
        else if (obj.Project_Edit_Level == 'assigned-task' && obj.Arti_ID != gUser_Profile.Artist.Arti_ID)
        {
            projectsEditMain = false;
            projectsEditAssigned = true;           
        }
        
        if (obj.Key_Arti_ID == gUser_Profile.Artist.Arti_ID)
        {
            projectsEditMain = true;
            projectsEditAssigned = true;            
        }       
            
        cLst = gCurrProjectItem.Other_Collabs_Long.split('\n');
        for (ndx =0; ndx < cLst.length; ndx++)
        {
            tCollab = cLst[ndx];
            if (tCollab.length == 0) {continue;}
            cLst2 = tCollab.split('|');
            tID = cLst2[1].replaceAll('  ',' ').replaceAll(' ','').replaceAll('(','').replaceAll(')','');
            cLst3 = cLst2[0].split('<');
            tEmail = cLst3[0].trim();
            tName = cLst3[1].replaceAll('<','').replaceAll('>','').trim();
            if ((','+gProjOtherCollabs_Vals+',').indexOf(','+tID+',') == -1)
            {
                gProjOtherCollabs_Vals.push(tID);
                tItem = {id: tID, title: tName, eml: tEmail};
                gProjOtherCollabs_List.push(tItem);
            }
        }        
        
        cLst = gCurrProjectItem.Collabs_Invited_Long.split('\n');
        for (ndx =0; ndx < cLst.length; ndx++)
        {
            tCollab = cLst[ndx];
            if (tCollab.length == 0) {continue;}
            cLst2 = tCollab.split('|');
            tID = cLst2[1].replaceAll('  ',' ').replaceAll(' ','').replaceAll('(','').replaceAll(')','');
            cLst3 = cLst2[0].split('<');
            tEmail = cLst3[0].trim();
            tName = cLst3[1].replaceAll('<','').replaceAll('>','').trim();
            
            if ((','+gProjCollabsInvited_Vals+',').indexOf(','+tID+',') == -1)
            {
                gProjCollabsInvited_Vals.push(tID);
                tItem = {id: tID, title: tName, eml: tEmail};
                gProjCollabsInvited_List.push(tItem); 
            }                                             
        }           
                
    },
    (error) => 
    { 
        frmContents = {view: "template", template: "Error pulling form contents"};
    }); 

    //console.log('objData', objData);
    if (noFormRequired == true) {return;}

    theForm = editor.getForm();
	if (gCurrProjectItem.Project_Phase != 'Concept') 
	{
		theForm.config.height = hh - 176;
		theForm.resize();
		theForm.resizeChildren();
	}
	else
	{
		setTimeout('$(".webix_view.webix_window.webix_kanban_editor").height(hh-50);',600);
		console.log('trying');
		theForm.resize();
	}
	
    webix.ui(frmContents, theForm);
    theForm.refresh();
    obj.Data_Entry_Level = objData.Data_Entry_Level;
    obj.Project_Notes = objData.Data.Project_Notes;
    obj.Project_Name = objData.Data.Project_Name;
    obj.Deadline_Date = objData.Data.Deadline_Date;
    obj.Project_TCON_Genre = objData.Data.Project_TCON_Genre;
    
    if      (obj.Project_Status == 'Concept')        {obj.Project_Area_Notes = objData.Data.Concept_Notes;$$("Project_Area_Notes").config.label = 'Concept Notes';}
    else if (obj.Project_Status == 'Composition')    {obj.Project_Area_Notes = objData.Data.Compose_Notes;$$("Project_Area_Notes").config.label = 'Composition Notes';}
    else if (obj.Project_Status == 'Arrangement')    {obj.Project_Area_Notes = objData.Data.Arrange_Notes;$$("Project_Area_Notes").config.label = 'Arrangement Notes';}
    else if (obj.Project_Status == 'Production')     {obj.Project_Area_Notes = objData.Data.Produce_Notes;$$("Project_Area_Notes").config.label = 'Production Notes';}
    else if (obj.Project_Status == 'Edits')          {obj.Project_Area_Notes = objData.Data.Edits_1_Notes;$$("Project_Area_Notes").config.label = 'Editing Notes';}
    else if (obj.Project_Status == 'Mixing')         {obj.Project_Area_Notes = objData.Data.Mix_Notes;$$("Project_Area_Notes").config.label = 'Mixing Notes';}
    else if (obj.Project_Status == 'Versions')       {obj.Project_Area_Notes = objData.Data.Edits_2_Notes;$$("Project_Area_Notes").config.label = 'Versioning Notes';}
    else if (obj.Project_Status == 'Mastering')      {obj.Project_Area_Notes = objData.Data.Master_Notes;$$("Project_Area_Notes").config.label = 'Mastering Notes';}
    else if (obj.Project_Status == 'Administration') {obj.Project_Area_Notes = objData.Data.Admin_Notes;$$("Project_Area_Notes").config.label = 'Admin Notes';}
    else if (obj.Project_Status == 'Release')        {obj.Project_Area_Notes = objData.Data.Release_Notes;$$("Project_Area_Notes").config.label = 'Release Notes';}
    else if (obj.Project_Status == 'Archive')        {obj.Project_Area_Notes = objData.Data.Archive_Notes;$$("Project_Area_Notes").config.label = 'Archive Notes';}
    
    if      (obj.Project_Status == 'Concept')        {obj.Area_Deadline_Date = objData.Data.Concept_Deadline;$$("Area_Deadline_Date").config.label = 'Concept Deadline';}
    else if (obj.Project_Status == 'Composition')    {obj.Area_Deadline_Date = objData.Data.Compose_Deadline;$$("Area_Deadline_Date").config.label = 'Compose Deadline';}
    else if (obj.Project_Status == 'Arrangement')    {obj.Area_Deadline_Date = objData.Data.Arrange_Deadline;$$("Area_Deadline_Date").config.label = 'Arrange Deadline';}
    else if (obj.Project_Status == 'Production')     {obj.Area_Deadline_Date = objData.Data.Produce_Deadline;$$("Area_Deadline_Date").config.label = 'Production Deadline';}
    else if (obj.Project_Status == 'Edits')          {obj.Area_Deadline_Date = objData.Data.Edits_1_Deadline;$$("Area_Deadline_Date").config.label = 'Editing Deadline';}
    else if (obj.Project_Status == 'Mixing')         {obj.Area_Deadline_Date = objData.Data.Mix_Deadline;$$("Area_Deadline_Date").config.label = 'Mixing Deadline';}
    else if (obj.Project_Status == 'Versions')       {obj.Area_Deadline_Date = objData.Data.Edits_2_Deadline;$$("Area_Deadline_Date").config.label = 'Versioning Deadline';}
    else if (obj.Project_Status == 'Mastering')      {obj.Area_Deadline_Date = objData.Data.Master_Deadline;$$("Area_Deadline_Date").config.label = 'Mastering Deadline';}
    else if (obj.Project_Status == 'Administration') {obj.Area_Deadline_Date = objData.Data.Admin_Deadline;$$("Area_Deadline_Date").config.label = 'Admin Deadline';}
    else if (obj.Project_Status == 'Release')        {obj.Area_Deadline_Date = objData.Data.Release_Deadline;$$("Area_Deadline_Date").config.label = 'Release Deadline';}
    else if (obj.Project_Status == 'Archive')        {obj.Area_Deadline_Date = objData.Data.Archive_Deadline;$$("Area_Deadline_Date").config.label = 'Archive Deadline';}    
    
    theForm.parse(obj);
    theForm.refresh();
    //setTimeout("$$('Project_Area_Notes').refresh();",250);
    //setTimeout("$$('Area_Deadline_Date').refresh();",250);

    if (projectsEditMain == true)
    {
        
        if ($$("btnACTSNew") != undefined) {$$("btnACTSNew").config.disabled = false;$$("btnACTSNew").refresh();} 
        if ($$("Project_Notes") != undefined) {$$("Project_Notes").config.readonly = false;$$("Project_Notes").refresh();}     
        if ($$("projectsUpload_Doc") != undefined) {$$("projectsUpload_Doc").config.hidden = false;$$("Project_Notes").refresh();}    
        if ($$("projectsDocNote") != undefined) {$$("projectsDocNote").config.readonly = false;$$("projectsDocNote").refresh();}          
        if ($$("Project_Name") != undefined) {$$("Project_Name").config.readonly = false;$$("Project_Name").refresh();}
        if ($$("Deadline_Date") != undefined) {$$("Deadline_Date").config.readonly = false;$$("Deadline_Date").refresh();}  
        if ($$("Project_TCON_Genre") != undefined) {$$("Project_TCON_Genre").config.readonly = false;$$("Project_TCON_Genre").refresh();}
        if (obj.Arti_ID == gUser_Profile.Artist.Arti_ID)
        {
            if ($$("Project_Key_Arti_ID") != undefined) {$$("Project_Key_Arti_ID").config.readonly = false;$$("Project_Key_Arti_ID").refresh();}
            if ($$("Project_Edit_Level") != undefined) {$$("Project_Edit_Level").config.readonly = false;$$("Project_Edit_Level").refresh();} 
        }
        else
        {
            if ($$("Project_Key_Arti_ID") != undefined) {$$("Project_Key_Arti_ID").config.readonly = true;$$("Project_Key_Arti_ID").refresh();}  
            if ($$("Project_Edit_Level") != undefined) {$$("Project_Edit_Level").config.readonly = true;$$("Project_Edit_Level").refresh();} 
        }        
    }
    else
    {
        if ($$("btnACTSNew") != undefined) {$$("btnACTSNew").config.disabled = true;$$("btnACTSNew").refresh();} 
        if ($$("Project_Notes") != undefined) {$$("Project_Notes").config.readonly = true;$$("Project_Notes").refresh();}     
        if ($$("projectsUpload_Doc") != undefined) {$$("projectsUpload_Doc").config.hidden = true;$$("Project_Notes").refresh();}    
        if ($$("projectsDocNote") != undefined) {$$("projectsDocNote").config.readonly = true;$$("projectsDocNote").refresh();}          
        if ($$("Project_Name") != undefined) {$$("Project_Name").config.readonly = true;$$("Project_Name").refresh();}
        if ($$("Deadline_Date") != undefined) {$$("Deadline_Date").config.readonly = true;$$("Deadline_Date").refresh();}  
        if ($$("Project_TCON_Genre") != undefined) {$$("Project_TCON_Genre").config.readonly = true;$$("Project_TCON_Genre").refresh();}
        if (obj.Arti_ID == gUser_Profile.Artist.Arti_ID)
        {
            if ($$("Project_Key_Arti_ID") != undefined) {$$("Project_Key_Arti_ID").config.readonly = false;$$("Project_Key_Arti_ID").refresh();}
            if ($$("Project_Edit_Level") != undefined) {$$("Project_Edit_Level").config.readonly = false;$$("Project_Edit_Level").refresh();} 
        }
        else
        {
            if ($$("Project_Key_Arti_ID") != undefined) {$$("Project_Key_Arti_ID").config.readonly = true;$$("Project_Key_Arti_ID").refresh();} 
            if ($$("Project_Edit_Level") != undefined) {$$("Project_Edit_Level").config.disabled = true;$$("Project_Edit_Level").refresh();} 
        }        
    }  
    
    if (projectIsNew == true)
    
    {
        $$("projectsDocUploadButton").disable();$$("projectsDocUploadButton").refresh();   
        $$("projectsDocNote").config.readonly = true;$$("projectsDocNote").refresh();   
        projectIsNew = false;    
    }

    try
    {
       
      if ($$("projectsACTS") != undefined) {$$("projectsACTS").clearAll();$$("projectsACTS").parse(gACTS);}
    }
    catch(err) {a=1;}   
    
    if ($$("projectsACTS") != undefined)
    {
        $$("projectsACTS").eachRow(function(row)
        {
                arec = $$("projectsACTS").getItem(row);
                if (arec.Assigned_User == gUser_Profile.Artist_Pref.aseq)
                {
                        $$("projectsACTS").addRowCss(row, "actsCollab");
                }
        });
    }
    
    try
    {
      if ($$("projectsDOCS") != undefined) {$$("projectsDOCS").clearAll();$$("projectsDOCS").parse(gDOCS);}
    }
    catch(err) {a=1;}   
    
    if (loadcnt > 1)
    {
        try
        {    
            setTimeout('try {$$("Project_Key_Arti_ID").getPopup().getList().parse(gCurrProjectItem.Collaborators);} catch(err) {}',500);
            setTimeout('try {$$("Project_Key_Arti_ID").setValue(gCurrProjectItem.ka2);} catch(err){}',500);   
            setTimeout('$$("$kanbaneditor1").show();',500);
            setTimeout("$$('Project_Area_Notes').refresh();",500);
            setTimeout("$$('Area_Deadline_Date').refresh();",500); 
	    try {setTimeout('$$("projectsDocUpload").clearAll();',900);} catch(err) {a=1;}	    
            
            setTimeout(`
            if (gCurrProjectItem.Arti_ID != gUser_Profile.Artist.Arti_ID)
            {
				try
				{
					$$("btnCollabInvite").disable();
					$$("btnCollabLookup").disable();
				} catch(err) {}
        
            }
            else
            {
				try
				{
					$$("btnCollabInvite").enable();
					$$("btnCollabLookup").enable(); 
				}
				catch(err) {}
            }
                build_FT_Row();
                
            `,500);
            
            setTimeout('loadcnt = 0;',2200);
        }
        catch(err) {a=1;}
    }
      
}
// ------------------------------------------------------------ //
function getActivity(inID)
{
      for (ndx =0; ndx < gACTS.length; ndx++)
      {
          tObj = gACTS[ndx];
          if (tObj.Act_ID == inID) {return tObj;}        
      }
      return {};
}
// ------------------------------------------------------------ //
function getDoc(inID)
{
      for (ndx =0; ndx < gDOCS.length; ndx++)
      {
          tObj = gDOCS[ndx];
          if (tObj.Doc_ID == inID) {return tObj;}        
      }
      return {};
}
// ------------------------------------------------------------ //
function projectsVettingSurveyGo()
{

    if (glCollab_Only == true)
	{
		showCollabOnlyMsg(extraxText = 'Vetting Survey');
		return;
	}

    cardID = $$("projectsKB").getSelectedId();
    if (cardID == null)
    {
	if (gcPAData != null && gcPAData != '' && gcPAData.hasOwnProperty("Project_ID"))
	{
	    $$("projectsKB").select(gcPAData.Project_ID);
	    cardID = $$("projectsKB").getSelectedId();
	}
    }
    if (cardID != null)
    {
	cpProj_tCard = $$("projectsKB").getItem(cardID);
	gCurrProjectItem = cpProj_tCard;    
	// gets data elements of project
	projectsPullForm('',cpProj_tCard,true)		
	vettingSurveyPull();
    }
    else
    {
	webix.message({type: "error", text: "<b>Error:</b>&nbsp;&nbsp;Please select a Project first", expire: 10000});
    }

}
// ------------------------------------------------------------ //
function projectsActionItem(id,item)
{
    tACT = getActivity(id);
    if (tACT.Description == 'Release to vetting group' && tACT.Deleted == 'N')
    {                                       
        if (tACT.Status != 'Ignore')
        vettingSurveyPull();
    }
    else
    {
        webix.message({type: "error", text: "<b>Error:</b>&nbsp;&nbsp;Task ACTION is not allowed.", expire: 10000});
    }
}
// ------------------------------------------------------------ //
function projectsTogItem(id,item)
{
    tACT = getActivity(id);
    if (tACT.hasOwnProperty('Act_ID') && tACT.Assigned_User == gUser_Profile.Artist_Pref.aseq) {tEditOK = true;} else {tEditOK = false;}
    if (projectsEditMain || (projectsEditLevel == 'assigned-task' && tEditOK))
    {                                       
        if (tACT.Deleted == 'N') {tACT.Deleted = 'Y'} else {tACT.Deleted = 'N';}
        $$("projectsACTS").refresh();
    }
    else
    {
        webix.message({type: "error", text: "<b>Error:</b>&nbsp;&nbsp;Task DELETION is not allowed.", expire: 10000});
    }
}
// ------------------------------------------------------------ //
function projectsTogIcon(obj,item)
{
    html = "<div class='webix_secondary'>";
    if (item == 'deleted')
    {
        html += `<div style='background:transparent;' title='Delete this task' onclick='projectsTogItem("##cts##","##item##");' class='webix_table_checkbox custom_toggle'>`;
        if (obj.Deleted == 'N') {html += icon_deleted_no;}
        else {html += icon_deleted_yes;}  
    }    
    if (item == 'action')
    {
        if (obj.Description == 'Release to vetting group' && obj.Status != 'Ignore' && gUser_Profile.Artist.Email.indexOf('@robottworks.com') > -1)
        {
            html += `<div style='background:transparent;' title='Vetting Survey' onclick='projectsActionItem("##cts##","##item##");' class='webix_table_checkbox custom_toggle'>`;
            icon_action = icon_go = "<span class='webix_icon fas fa-list-check' style='cursor:pointer;color:darkOrange;font-size:14px;margin-right:6px;'></span>";
            html += icon_action;
        }
        else
        {
            html = '';
        }    
    }    
    
    html += "</div></div>";
    html = html.replace('##cts##',obj.id+'').replace('##item##',item);
    return html;
}
// ------------------------------------------------------------ //
function projectsTogDocIcon(obj)
{
    if (projectsEditMain)
    {
        html = "<div class='webix_secondary'>";
        html += `<div style='background:transparent;' title='Delete this file' onclick='projectsTogDocItem("##cts##");' class='webix_table_checkbox custom_toggle'>`;
    
        if (obj.Deleted == 'N') {html += icon_deleted_no;}
        else {html += icon_deleted_yes;}  
          
        html += "</div></div>";
        html = html.replace('##cts##',obj.id+'');
        return html;
    }
    else
    {
        a=1;  
    }
}
// ------------------------------------------------------------ //
function projectsTogDocItem(id)
{

  if (projectsEditMain)
  {
    obj = getDoc(id);
    if (obj.Deleted == 'N') {obj.Deleted = 'Y'} else {obj.Deleted = 'N';}
    $$("projectsDOCS").refresh();
  }
  else
  {
        webix.message({type: "error", text: "<b>Error:</b>&nbsp;&nbsp;Document DELETION is not allowed.", expire: 10000});    
  }
}

// ------------------------------------------------------------ //
function projectsShowIcon(obj)
{
    html = "<div class='webix_secondary'>";
    html += `<div style='background:transparent;' title='View File' onclick='projectsShowDoc("##cts##");' class='webix_table_checkbox custom_toggle'>`;
    {html += icon_doc_view;}  
    html += "</div></div>";
    html = html.replace('##cts##',obj.URL + '^^^' + obj.profFull_File);
    return html;

}
// ------------------------------------------------------------ //
function justTracks()
{
    gVET = []; 
    for (ndx =0; ndx < gDOCS.length; ndx++)
    {
        jtrk = gDOCS[ndx];
	ff = jtrk.profFull_File.toLowerCase();
	if (ff.endsWith('.mp3') || ff.endsWith('.wav'))
	{
	    fl = jtrk.profFull_File.split('~');
	    fn = fl[1];
	    ul = jtrk.URL.split('/');
	    u = ul[ul.length-1]
	    tv = {"id": u, "value": fn};
	    gVET.push(tv);
	}	
    }
    return gVET;
}
turl = '';
gTmpDocObj = '';pcdm_id = 'MAIN';
// ------------------------------------------------------------ //
function projectsShowDoc(toURL)
{

    var lst = toURL.split('^^^')
    toURL2 = lst[0]
    toInfo = lst[1]
    if (gTauri == false)
    {
	window.open(toURL2,'_blank');  	
    }
    else
    {
	pkge = {"document": toURL2, "info": toInfo, "stack": "projectsShowDoc", "doc_or_link": "doc"};
	amsg = genAblyMsg("projects-open-document", inTarget="CMD", inStage="broadcast", inID="",inPrev_ID="", inPkge=pkge, autoSend=true)
    }
  
}
// ------------------------------------------------------------ //
function projectsColVis(mode,inID)
{
    projectsCloseCard();
    if (mode == 'showactive')
    {
        projectsVisAll('','show');  
        try {$$("col_Concepts").collapse();}
        catch(err) {a=1;}  
        try {$$("col_Archive").collapse();}
        catch(err) {a=1;}         
    }
    else if (mode == 'showjust1')
    {
        
        try {$$("col_" + inID).expand();}
        catch(err) {a=1;}        
        projectsVisAll(inID);
        try {$$("col_" + inID).expand();}
        catch(err) {a=1;}
    }
    
    else if (mode == 'showthis1')
    {
        try {$$("col_" + inID).expand();}
        catch(err) {a=1;}
    }
    else if (mode == 'hidethis1')
    {
        try {$$("col_" + inID).collapse();}
        catch(err) {a=1;}  
    }
    
    // maintain persistent filter
    
    try {keptProjectsFilter = webix.storage.local.get("projectsTextFilter");} catch(err) {keptProjectsFilter = '';}
    if (keptProjectsFilter == null) {keptProjectsFilter = '';}

    if (gHoldProjectsTextFilter.length > 0)
    {
        $$("projectsSearchFld").setValue(gHoldProjectsTextFilter);
        dataWH.Projects.Settings.filterText = gHoldProjectsTextFilter;
        projectsFilter(dataWH.Projects.Settings.filterText);    
    }
    else if (keptProjectsFilter.length > 0)
    {
        $$("projectsSearchFld").setValue(keptProjectsFilter);
        dataWH.Projects.Settings.filterText = keptProjectsFilter;
        projectsFilter(dataWH.Projects.Settings.filterText);
    }    
    
}
// ------------------------------------------------------------ //
function projectsAllColsVisible()
{
    //console.log("projectsAllColsVisible():");
    allvisible = true;
    arr = gUser_Profile.Artist_Pref.Dev_Steps.split(',');
    for (ndx =0; ndx < arr.length; ndx++)
    {
        stp = parseInt(arr[ndx]); 
        stat = devStep2Status(stp);
        stat = stat.replaceAll(' ','_').replaceAll('Edits','Editing_1').replaceAll('Versions','Editing_2');
        if ($$("col_" + stat).config.collapsed == true) {allvisible = false;}
    }
    
    return allvisible;
}
// ------------------------------------------------------------ //
function projectsVisAll(excep='',mode='hide')
{
    arr = gUser_Profile.Artist_Pref.Dev_Steps.split(',');
    for (ndx =0; ndx < arr.length; ndx++)
    {
        stp = parseInt(arr[ndx]); 
        stat = devStep2Status(stp);
        stat = stat.replaceAll(' ','_').replaceAll('Edits','Editing_1').replaceAll('Versions','Editing_2');
        if (stat != excep)
        {
            try
            {
                if (mode == 'show') {$$("col_" + stat).expand();} else {$$("col_" + stat).collapse();}
            }
            catch(err) {a=1;}
        }
        else
        {
            a=1;
        }
    }
}
// ------------------------------------------------------------ //
function projectsCloseCard()
{

    if (dataWH.hasOwnProperty('Projects'))
    {
	try 
	{
	    webix.html.triggerEvent($$("$icon3").getInputNode(), "MouseEvents", "click");
	}
	catch(err) {a=1;}
    }
}
// ------------------------------------------------------------ //
function projectsRefresh(clearFirst=false)
{
    gACTS = [];gDOCS = [];gVET = [];
    projectsCloseCard();
    $$("projectsKB").showProgress({hide: true, type: "top"});
    if (clearFirst == true) 
    {
        $$("projectsKB").clearAll();        
    }    
    
    $$("projectsKB").load('/kbdata/');
}



gTransTracks = [];catalogCurrOrigID = '';gCurrOrigTrack = {};
// ------------------------------------------------------------ //
function genTrackTransferWindow()
{

    if ($$("trackTransferWin") == undefined)
    {    
        gTransTracks = gUser_Profile.Artist.Orig_Acct_Tracks;
        gotoTab('info');
        lft = $('div[view_id="catalogTabsHide"]').offset().left;
        
        wtt = 860;
        htt = 540;
        wlft = lft - 40 - wtt;
        wtop = hh - htt - 40;
        webix.ui({
            view: "window", 
            width: wtt, 
            height: htt, 
            move: true,
            position: "center", 
            id: "trackTransferWin", 
            css: {"background-color":"#000000"},
            zIndex: 60,
            head:{
                view: "toolbar", id: "trackTransferWinToolbar", 
                css:"install_window",
                cols:[
                    {   view: "label", id: "trackTransferWinTitle", 
                        label: "Transfer in Track Data (Prev Account)",
                        height: 40,
                        borderless: 1,
                        css:{ "padding-left":"20px" }
                    },
                    {},
                    {   view: "icon", 
                        type: "button",
                        borderless: 1,
                        icon: "fas fa-close",
                        width: 40, 
                        click: "$$('trackTransferWin').hide();"
                    },
                    { width: 20 }
                ]
            },
            body: {  
                scroll: true, select: true,
                width: ww, 
                height: hh,  
                id: "trackTransferWinBody",
                view:"form",
                id:'trackTransferWinForm',      
                elements:
                [
                {view: "layout",
                    rows:
                    [
                        {   view: "template", id: "transfer_notes", 
                            template: "Select a Track from your previous account below.<br/>Then dbl-click the row, or press the <b>Transfer In</b> button to load in the old track."
                            },
                        {
                            view: "datatable", id: "catalogTransferTracks", select: true, height: 400,
                            css: { "margin-bottom": "10px", "margin-right": "10px"},
                            resizeColumn: {headerOnly: true, size: 10}, 
                            hover: "catalogDTHover", 
                            dragColumn: true,
                            drag: true,
                            tooltip:
                            {
                                overflow: true,
                                maxWidth: 400,
                            },                            
                            scheme: {
                                $change:function(item){
                                    if (item.Primary_Track == true)
                                        {item.$css = "trackPri";}
                                    else if (item.Primary_ELink.length > 1)
                                        {item.$css = "trackLnk";}
                                    else 
                                        {item.$css = "trackNon";}
                                        
                                    if (item.Tags_Pending == "Y") {item.$css += ' tags_pending';}
                                    if (item.Source_Track_Deleted == "Y") {item.$css += ' src_deleted';}
                                }
                            },
                            on:{
                            
                                "onItemClick":function(id, e, trg)
                                {
                                    catalogCurrOrigID = id;
                                    gCurrOrigTrack = getOldTrack(catalogCurrOrigID.row);
                                    realTrackOID = $$("Track_ID_Original").getValue();
                                    nRealOID = parseInt(realTrackOID) || 0;
                                    //console.log(catalogCurrOrigID);
                                    if (nRealOID == 0)
                                    {
                                        $$("btnTransferIn").enable();
                                    }
                                    else
                                    {
                                        $$("btnTransferIn").disable();
                                        $$("btnTransferUndo").disable();
                                    }

                                },   
                                "onItemDblClick":function(id, e, trg)
                                {
                                    catalogCurrOrigID = id;
                                    gCurrOrigTrack = getOldTrack(catalogCurrOrigID.row);
                                    realTrackOID = $$("Track_ID_Original").getValue();
                                    nRealOID = parseInt(realTrackOID) || 0;
                                    //console.log(catalogCurrOrigID);
                                    if (nRealOID == 0)
                                    {
                                        $$("btnTransferIn").enable();
                                        setTimeout('webix.html.triggerEvent($$("btnTransferIn").getInputNode(), "MouseEvents", "click");',400);
                                    }
                                    else
                                    {
                                        $$("btnTransferIn").disable();
                                        webix.message({type: "error", text: "<b>Error:</b>&nbsp;&nbsp;Your current Track was loaded in with previous account data before.  Blank out the <b>Orig. Track ID</b> in order to load in again.", expire: 8000});
                                    }

                                },                                 
                            },                            
                             columns:
                             [
                                 //{   id:"trnsPrimary", 
                                     //header: "<span  style='cursor:grab;' class='far fa-trash'></span>", 
                                     //tooltip: "Delete this Task",
                                     //template: function(obj) {return UPDefTasksTogIcon(obj,"deleted")}, 
                                     //minwidth: 35,
                                     //maxWidth: 35,
                                 //}, 
                                 {   id: "Track2_ID", header: "Orig. ID", 
                                     fillspace: 0, 
                                     minWidth: 25, 
                                     drag: "source",
                                     sort: "string" 
                                 },                                  
                                 {   id: "TIT2_TrackName", header: "Track Name", 
                                     fillspace: 0, 
                                     minWidth: 140, 
                                     tooltip: "#TIT2_TrackName#",                                          
                                     sort: "string" 
                                 }, 								 
                                 {   id: "File_Name", header: "File Name", 
                                     fillspace: 1, 
                                     minWidth: 100, 
                                     tooltip: "#File_Name#",                                     
                                     sort: "string" 
                                 }, 
                                 {   id: "Run_Length", header: "Length", 
                                     css: {"text-align": "center"},
                                     fillspace: 1, 
                                     minWidth: 48, 
                                     tooltip: "#Run_Length#", 
                                     template: function(obj){return formatMinSec(obj.Run_Length)},
                                     sort: "string" 
                                 }, 								 
                                 {   id: "TCON_Genre", header: "Genre",
                                     fillspace: 3, 
                                     minWidth: 60, 
                                     tooltip: "#TCON_Genre#",
                                     sort: "string" 
                                 },    
                                 {   id: "COMM_3_Desc", header: "Description",
                                     fillspace: 3, 
                                     minWidth: 150, 
                                     tooltip: "#COMM_3_Desc#",
                                     sort: "string" 
                                 },   
                                 {   id: "TMOO_Keywords", header: "Keywords",
                                     fillspace: 3, 
                                     minWidth: 200, 
                                     tooltip: function(obj){return LimitTo(Spacer(obj.TMOO_Keywords),500)},                                     
                                     sort: "string" 
                                 },    
                                 {   id: "File_Ext", header: "Ext", 
                                     fillspace: 1, 
                                     minWidth: 40, 
                                     tooltip: "#File_Ext#",                                     
                                     sort: "string" 
                                 },                                  
                             ],
                             complexData: true,
                             data: gTransTracks,								    
                        },
                        
                    ]
                }

// --------------------------------------------------------------------------- //


// --------------------------------------------------------------------------- //
                  
                ]
                
            }                       
        }).show({x: wlft, y: wtop});
        
    }
    else
    {
        //kill it
        $$("trackTransferWin").destructor();
        //rebuild it
        setTimeout('genTrackTransferWindow();',500);
    }

}

// --------------------------------------------------------------------------- //
function ArtistAccountLevel(obj)
{

    oVal = gUser_Profile.Artist.Account_Level;
    if (oVal.value == 'Pro') {return 'PRO: includes Dashboard, Full Catalog (TrackSync) and Creative Projects.';}
    else if (oVal.value == 'Creator') {return '<b>Creator</b>:&nbsp;includes Dashboard, Manual Catalog, and Creative Projects.';}
    else {return '<b>Artist</b>:&nbsp;includes Dashboard and Manual Catalog.';}
}
// --------------------------------------------------------------------------- //
function catalogRemoveTrackClass(inClass)
{
    webix.html.removeCss( $$("Track_ID_Original").getNode(), inClass);
    webix.html.removeCss( $$("TIT2_TrackName").getNode(), inClass);
    webix.html.removeCss( $$("File_Name").getNode(), inClass);
    webix.html.removeCss( $$("TALB_CDTitle").getNode(), inClass);
    webix.html.removeCss( $$("TCOM_Composer").getNode(), inClass);
    webix.html.removeCss( $$("TPE1_Artist").getNode(), inClass);
    webix.html.removeCss( $$("TPE2_AlbumArtist").getNode(), inClass);
    webix.html.removeCss( $$("TPUB_Publisher").getNode(), inClass);
    webix.html.removeCss( $$("GRP1_Grouping").getNode(), inClass);
    webix.html.removeCss( $$("COMM_3_Desc").getNode(), inClass);
    webix.html.removeCss( $$("Tempo").getNode(), inClass);
    webix.html.removeCss( $$("Key").getNode(), inClass);
    webix.html.removeCss( $$("TBPM_BPM").getNode(), inClass);
    webix.html.removeCss( $$("Date_Released").getNode(), inClass);
    webix.html.removeCss( $$("TDRC_Year").getNode(), inClass);
    webix.html.removeCss( $$("PRO_WorkNum").getNode(), inClass);
    webix.html.removeCss( $$("ISWC_Num").getNode(), inClass);
    webix.html.removeCss( $$("ISRC_Num").getNode(), inClass);
    webix.html.removeCss( $$("Copyright").getNode(), inClass);
    webix.html.removeCss( $$("Volume").getNode(), inClass);
    webix.html.removeCss( $$("TRCK_TrackNum").getNode(), inClass);
    webix.html.removeCss( $$("Source").getNode(), inClass);
    webix.html.removeCss( $$("Trk_Custom_01").getNode(), inClass);
    webix.html.removeCss( $$("Trk_Custom_02").getNode(), inClass);
    webix.html.removeCss( $$("Trk_Custom_03").getNode(), inClass);
    webix.html.removeCss( $$("Trk_Custom_04").getNode(), inClass);
    webix.html.removeCss( $$("Trk_Custom_05").getNode(), inClass);

}

// --------------------------------------------------------------------------- //
function catalogUndoOldValues()
{

    $$("Track_ID_Original").setValue('');
    webix.html.removeCss( $$("Track_ID_Original").getNode(), "bgCornSilk");
    
    $$("TIT2_TrackName").setValue(gCurrTrack.TIT2_TrackName);
    webix.html.removeCss( $$("TIT2_TrackName").getNode(), "bgCornSilk");
    
    $$("File_Name").setValue(gCurrTrack.File_Name);
    webix.html.removeCss( $$("File_Name").getNode(), "bgCornSilk");
    
    $$("TALB_CDTitle").setValue(gCurrTrack.TALB_CDTitle);
    webix.html.removeCss( $$("TALB_CDTitle").getNode(), "bgCornSilk");
    
    $$("TCOM_Composer").setValue(gCurrTrack.TCOM_Composer);
    webix.html.removeCss( $$("TCOM_Composer").getNode(), "bgCornSilk");
    
    $$("TPE1_Artist").setValue(gCurrTrack.TPE1_Artist);
    webix.html.removeCss( $$("TPE1_Artist").getNode(), "bgCornSilk");
    
    $$("TPE2_AlbumArtist").setValue(gCurrTrack.TPE2_AlbumArtist);
    webix.html.removeCss( $$("TPE2_AlbumArtist").getNode(), "bgCornSilk");
    
    $$("TPUB_Publisher").setValue(gCurrTrack.TPUB_Publisher);
    webix.html.removeCss( $$("TPUB_Publisher").getNode(), "bgCornSilk");
    
    $$("GRP1_Grouping").setValue(gCurrTrack.GRP1_Grouping);
    webix.html.removeCss( $$("GRP1_Grouping").getNode(), "bgCornSilk");
    
    $$("COMM_3_Desc").setValue(gCurrTrack.COMM_3_Desc);
    webix.html.removeCss( $$("COMM_3_Desc").getNode(), "bgCornSilk");
    
    $$("Tempo").setValue(gCurrTrack.Tempo);
    webix.html.removeCss( $$("Tempo").getNode(), "bgCornSilk");
    
    $$("Key").setValue(gCurrTrack.Key);
    webix.html.removeCss( $$("Key").getNode(), "bgCornSilk");
    
    $$("TBPM_BPM").setValue(gCurrTrack.TBPM_BPM);
    webix.html.removeCss( $$("TBPM_BPM").getNode(), "bgCornSilk");
    
    $$("Date_Released").setValue(gCurrTrack.Date_Released);
    webix.html.removeCss( $$("Date_Released").getNode(), "bgCornSilk");
    
    $$("TDRC_Year").setValue(gCurrTrack.TDRC_Year);
    webix.html.removeCss( $$("TDRC_Year").getNode(), "bgCornSilk");
    
    $$("PRO_WorkNum").setValue(gCurrOrigTrack.PRO_WorkNum);
    webix.html.removeCss( $$("PRO_WorkNum").getNode(), "bgCornSilk");
    
    $$("ISWC_Num").setValue(gCurrTrack.ISWC_Num);
    webix.html.removeCss( $$("ISWC_Num").getNode(), "bgCornSilk");
    
    $$("ISRC_Num").setValue(gCurrTrack.ISRC_Num);
    webix.html.removeCss( $$("ISRC_Num").getNode(), "bgCornSilk");
    
    $$("Copyright").setValue(gCurrTrack.Copyright);
    webix.html.removeCss( $$("Copyright").getNode(), "bgCornSilk");
    
    $$("Volume").setValue(gCurrTrack.Volume);
    webix.html.removeCss( $$("Volume").getNode(), "bgCornSilk");
    
    $$("TRCK_TrackNum").setValue(gCurrTrack.TRCK_TrackNum);
    webix.html.removeCss( $$("TRCK_TrackNum").getNode(), "bgCornSilk");
    
    $$("Source").setValue(gCurrOrigTrack.Source);
    webix.html.removeCss( $$("Source").getNode(), "bgCornSilk");
    
    $$("Trk_Custom_01").setValue(gCurrTrack.Trk_Custom_01);
    webix.html.removeCss( $$("Trk_Custom_01").getNode(), "bgCornSilk");
    
    $$("Trk_Custom_02").setValue(gCurrTrack.Trk_Custom_02);
    webix.html.removeCss( $$("Trk_Custom_02").getNode(), "bgCornSilk");
    
    $$("Trk_Custom_03").setValue(gCurrTrack.Trk_Custom_03);
    webix.html.removeCss( $$("Trk_Custom_03").getNode(), "bgCornSilk");
    
    $$("Trk_Custom_04").setValue(gCurrTrack.Trk_Custom_04);
    webix.html.removeCss( $$("Trk_Custom_04").getNode(), "bgCornSilk");
    
    $$("Trk_Custom_05").setValue(gCurrTrack.Trk_Custom_05);
    webix.html.removeCss( $$("Trk_Custom_05").getNode(), "bgCornSilk");
    
    $$("Batch_Key").setValue('');
    
    $$("btnTransferUndo").disable(); 
}
// --------------------------------------------------------------------------- //
function catalogLoadOldValues()
{
    $$("Track_ID_Original").setValue(gCurrOrigTrack.Track2_ID);
    webix.html.addCss( $$("Track_ID_Original").getNode(), "bgCornSilk");

    $$("TIT2_TrackName").setValue(gCurrOrigTrack.TIT2_TrackName);
    webix.html.addCss( $$("TIT2_TrackName").getNode(), "bgCornSilk");
    
    $$("File_Name").setValue(gCurrOrigTrack.File_Name);
    webix.html.addCss( $$("File_Name").getNode(), "bgCornSilk");
    
    $$("TALB_CDTitle").setValue(gCurrOrigTrack.TALB_CDTitle);
    webix.html.addCss( $$("TALB_CDTitle").getNode(), "bgCornSilk");
    
    $$("TCOM_Composer").setValue(gCurrOrigTrack.TCOM_Composer);
    webix.html.addCss( $$("TCOM_Composer").getNode(), "bgCornSilk");
    
    $$("TPE1_Artist").setValue(gCurrOrigTrack.TPE1_Artist);
    webix.html.addCss( $$("TPE1_Artist").getNode(), "bgCornSilk");
    
    $$("TPE2_AlbumArtist").setValue(gCurrOrigTrack.TPE2_AlbumArtist);
    webix.html.addCss( $$("TPE2_AlbumArtist").getNode(), "bgCornSilk");
    
    $$("TPUB_Publisher").setValue(gCurrOrigTrack.TPUB_Publisher);
    webix.html.addCss( $$("TPUB_Publisher").getNode(), "bgCornSilk");
    
    $$("GRP1_Grouping").setValue(gCurrOrigTrack.GRP1_Grouping);
    webix.html.addCss( $$("GRP1_Grouping").getNode(), "bgCornSilk");
    
    $$("COMM_3_Desc").setValue(gCurrOrigTrack.COMM_3_Desc);
    webix.html.addCss( $$("COMM_3_Desc").getNode(), "bgCornSilk");
    
    $$("Tempo").setValue(gCurrOrigTrack.Tempo);
    webix.html.addCss( $$("Tempo").getNode(), "bgCornSilk");
    
    $$("Key").setValue(gCurrOrigTrack.Key);
    webix.html.addCss( $$("Key").getNode(), "bgCornSilk");
    
    $$("TBPM_BPM").setValue(gCurrOrigTrack.TBPM_BPM);
    webix.html.addCss( $$("TBPM_BPM").getNode(), "bgCornSilk");
    
    $$("Date_Released").setValue(gCurrOrigTrack.Date_Released);
    webix.html.addCss( $$("Date_Released").getNode(), "bgCornSilk");
    
    $$("TDRC_Year").setValue(gCurrOrigTrack.TDRC_Year);
    webix.html.addCss( $$("TDRC_Year").getNode(), "bgCornSilk");
    
    $$("PRO_WorkNum").setValue(gCurrOrigTrack.PRO_WorkNum);
    webix.html.addCss( $$("PRO_WorkNum").getNode(), "bgCornSilk");
    
    $$("ISWC_Num").setValue(gCurrOrigTrack.ISWC_Num);
    webix.html.addCss( $$("ISWC_Num").getNode(), "bgCornSilk");
    
    $$("ISRC_Num").setValue(gCurrOrigTrack.ISRC_Num);
    webix.html.addCss( $$("ISRC_Num").getNode(), "bgCornSilk");
    
    $$("Copyright").setValue(gCurrOrigTrack.Copyright);
    webix.html.addCss( $$("Copyright").getNode(), "bgCornSilk");
    
    $$("Volume").setValue(gCurrOrigTrack.Volume);
    webix.html.addCss( $$("Volume").getNode(), "bgCornSilk");
    
    $$("TRCK_TrackNum").setValue(gCurrOrigTrack.TRCK_TrackNum);
    webix.html.addCss( $$("TRCK_TrackNum").getNode(), "bgCornSilk");
    
    $$("Source").setValue(gCurrOrigTrack.Source);
    webix.html.addCss( $$("Source").getNode(), "bgCornSilk");
    
    $$("Trk_Custom_01").setValue(gCurrOrigTrack.Trk_Custom_01);
    webix.html.addCss( $$("Trk_Custom_01").getNode(), "bgCornSilk");
    
    $$("Trk_Custom_02").setValue(gCurrOrigTrack.Trk_Custom_02);
    webix.html.addCss( $$("Trk_Custom_02").getNode(), "bgCornSilk");
    
    $$("Trk_Custom_03").setValue(gCurrOrigTrack.Trk_Custom_03);
    webix.html.addCss( $$("Trk_Custom_03").getNode(), "bgCornSilk");
    
    $$("Trk_Custom_04").setValue(gCurrOrigTrack.Trk_Custom_04);
    webix.html.addCss( $$("Trk_Custom_04").getNode(), "bgCornSilk");
    
    $$("Trk_Custom_05").setValue(gCurrOrigTrack.Trk_Custom_05);
    webix.html.addCss( $$("Trk_Custom_05").getNode(), "bgCornSilk");
    
    $$("Batch_Key").setValue('load-old-data');
    
    $$("btnTransferUndo").enable();
    $$("btnTransferIn").disable();
}
// --------------------------------------------------------------------------- //
function getOldTrack(inID)
{
    for (ndx =0; ndx < gTransTracks.length; ndx++)
    {
        tt = gTransTracks[ndx]; 
        if (tt.Track_ID == inID) {return tt;}
    }
    return {};

}
// --------------------------------------------------------------------------- //
var context = new AudioContext();

// Play oscillators at certain frequency and for a certain time
var playNote = function (frequency, startTime, duration) {
    var osc1 = context.createOscillator(),
        osc2 = context.createOscillator(),
        volume = context.createGain();

    // Set oscillator wave type
    osc1.type = 'triangle';
    osc2.type = 'triangle';

    volume.gain.value = 0.1;    

    // Set up node routing
    osc1.connect(volume);
    osc2.connect(volume);
    volume.connect(context.destination);

    // Detune oscillators for chorus effect
    osc1.frequency.value = frequency + 1;
    osc2.frequency.value = frequency - 2;

    // Fade out
    volume.gain.setValueAtTime(0.1, startTime + duration - 0.05);
    volume.gain.linearRampToValueAtTime(0, startTime + duration);


    // Start oscillators
    osc1.start(startTime);
    osc2.start(startTime);

    // Stop oscillators
    osc1.stop(startTime + duration);
    osc2.stop(startTime + duration);
};
// --------------------------------------------------------------------------- //
var playSuccessSound = function () {
    // Play a 'B' now that lasts for 0.116 seconds
    playNote(493.883, context.currentTime, 0.116);

    // Play an 'E' just as the previous note finishes, that lasts for 0.275 seconds
    playNote(659.255, context.currentTime + 0.116, 0.275);
};
// --------------------------------------------------------------------------- //
var playFailedSound = function () {

    // Play a 'E' now that lasts for 0.116 seconds
    playNote(659.255, context.currentTime, 0.116);

    // Play an 'B' just as the previous note finishes, that lasts for 0.275 seconds
    playNote(493.883, context.currentTime + 0.116, 0.275);
};
// --------------------------------------------------------------------------- //
try {gp = gcPageShort;}  catch(err) {gp = 'other';}  
bc = '';
globalStop = false;

//if (isMac == true && isSafari == true)
//{
        //a=1;
        //// canot use broadcastchannel in safari
//}
//else
//{
    //if (gcPageShort != 'Payment-Admin')
    //{
        //const bc = new BroadcastChannel("trackstage.io-site");
        //globalStop = false;
        //bc.onmessage = (event) => {
          //if (event.data === "first tab?") {
            //bc.postMessage("negative");
          //}
          //if (event.data === "negative") {
            //globalStop = true;
            //alert(`Yak! An instance of the TrackStage website is already running in another tab.\n\nPlease close this tab and return to the other TrackStage tab.`);
          //}
        //};
        
        //bc.postMessage("first tab?");
    //}
//}
// --------------------------------------------------------------------------- //
async function submitBugLogs()
{

    notes = $$("UPbugNotes").getValue();
    url = '/data_profile/?mde=bugrep&seq=' + seq();
    pkge = {'Console_Logs': console.everything, 'Bug_Notes': notes, 'Environment': 'Operating System:  ' + getOS() + ' | Browser:  ' + getBrowser()};
    response = await axios.post(url, pkge)

    gRes = response;
    resData = response.data; 

    if (resData.status == 'error')
    {
        webix.message({type: "error", text: "<b>Error:</b>&nbsp;&nbsp;"+resData.Message, expire: 12000});
    }
    else
    {  
        webix.message({type: "success", text: "<b>Success:</b>&nbsp;&nbsp;"+resData.Message, expire: 12000});
        $$("UPbugNotes").setValue('');
    }     
}
// ------------------------------------------------------------ //
function pitchesSetVisibility()
{
    //console.log("pitchesSetVisibility():");
    
     //$$("contactSummaryFull_Name").define("template",gCurrContact.Contact.Full_Name);$$("contactSummaryFull_Name").refresh();
     
     $$("pitchTargetTarget").refresh();
     $$("refPitchTargetProd.TargetProd.Prod_Project_Name").setValue(refPitchTargetProd.TargetProd.Prod_Project_Name);
     //$$("pitchTargetDeadline").refresh();
     $$("pitchTargetGenres").refresh();
     //$$("pitchProjectName").refresh();
     $$("pitchContactNotes").refresh();
     
     $$("pitchTargetContactName").refresh();
     $$("pitchTargetRefNum").refresh();
     $$("pitchTargetType").refresh();
     $$("pitchTargetLength").refresh();
     $$("pitchTargetGenres").refresh();
     
    
}
// ------------------------------------------------------------ //
function targetsSetVisibility()
{
    //console.log("targetsSetVisibility():");
    thisTarget = gCurrTarget['Target'];

    setTimeout(`
            $$("targetInfoHeader").define("template",'<span style="color:#999999;">INFO&nbsp;&nbsp;|&nbsp;&nbsp;</span>' + gCurrTarget.Target.Target_Name);$$("targetInfoHeader").refresh();
            $$("targetSummaryFull_Name").define("template",gCurrTarget.Target.Target_Name);$$("targetSummaryFull_Name").refresh();
            $$("targetContactNameHeader").define("template",gCurrTarget.Target.Target_First + '&nbsp;' + gCurrTarget.Target.Target_Last);$$("targetContactNameHeader").refresh();
            $$("targetSummaryType").define("template",gCurrTarget.Target.Target_Type);$$("targetSummaryType").refresh();
            $$("targetSummaryIndustry").define("template",gCurrTarget.Target.Target_Industry);$$("targetSummaryIndustry").refresh();
            $$("targetSummaryRating").$setValue(gCurrTarget.Target.Target_Rating);
            //$$("yyy").define("template",gCurrTarget.Target.Target_Name);$$("yyy").refresh();
    `,300);
    
    webix.html.removeCss( $$("Target.Target_First").getNode(), "bgCornSilk"); 
    
    $$("Production.Prod_Sample_Links").hide();
    $$("linksLabel").hide();
    makeProdKWS();
    $$("Target.Target_Genres").define("options",arr_Prod_All_KW);    
    $$("Production.Prod_Genre").define("options",arr_Prod_All_KW);
    
    if (thisTarget.Target_Type == 'Music Supervisor')
    {
        
        $$("targetInfoHeader").setHTML('<span style="color:#999999;">INFO&nbsp;&nbsp;|&nbsp;&nbsp;</span>' + thisTarget.Target_Name );
        $$("targetResearchHeader").setHTML('<span style="color:#999999;">RESEARCH&nbsp;&nbsp;|&nbsp;&nbsp;</span>' + thisTarget.Target_Name);
        $$("targetProductionsHeader").setHTML('<span style="color:#999999;">' + gProductionsName + '&nbsp;&nbsp;|&nbsp;&nbsp;</span>' + thisTarget.Target_Name);
        
        $$("targetCompanyIndustryURL").show();
        $$("targetContactNameEmailPhone").show();
        $$("targetMailingAddressCell").show();
        $$("targetSocialMedia").show();
        $$("targetStandardTerms").hide();
        $$("targetContractURL").hide();
        $$("targetLibraryTerms").hide();
        $$("targetServiceFeesFeedback").hide();
        
        $$("targetContactInfoHeader").hide();
        $$("targetContractDetailsHeader").hide();
 
        $$("Target.Target_Genres").show();
        $$("targetComposersProjects").show();
        $$("targetPublicityAwardsConnect").show();
        $$("targetNotes").show();
       
        $$("targetContractRowSpacer").show();
        $$("targetTermsRowSpacer").show();

        $$("targetIconSupe").show();
        $$("targetIconPublisher").hide();
        $$("targetIconLibrary").hide();
        $$("targetIconCompany").hide();
        $$("targetIconService").hide();
        $$("targetIconAgent").hide();
       
        $$("productionSpacer").hide();
        $$("productionSpacer2").hide();
       
        $$("prodTitleStatus").show();
        $$("prodGenreLength").show();
        $$("prodSegStageDeadline").show();
        $$("prodProjectCompanyIMDb").show();
      
        $$("Production.Prod_Genre").show();
        $$("Production.Prod_Length").hide();
        $$("Production.Prod_Ind_Seg").show();
        $$("Production.Prod_Stage").show();
        $$("Production.Prod_Ref_Num").hide();
        $$("Production.Prod_Deadline").show();
        $$("Production.Prod_Project_Name").show();
        $$("Production.Prod_Company").show();
        $$("Production.Prod_IMDb").show();
        $$("Production.Prod_Notes").hide();                

        $$("opportunitiesCreateDate").setHTML('<span style="color:#351b5b;">Created:&nbsp;' + '</span>');
        
    }
    else if (thisTarget.Target_Type == 'Production Company')
    {
        $$("targetInfoHeader").setHTML('<span style="color:#999999;">INFO&nbsp;&nbsp;|&nbsp;&nbsp;</span>' + thisTarget.Target_Name );
        $$("targetResearchHeader").setHTML('<span style="color:#999999;">RESEARCH&nbsp;&nbsp;|&nbsp;&nbsp;</span>' + thisTarget.Target_Company);
        $$("targetProductionsHeader").setHTML('<span style="color:#999999;">' + gProductionsName + '&nbsp;&nbsp;|&nbsp;&nbsp;</span>' + thisTarget.Target_Company);

        $$("targetCompanyIndustryURL").show();
        $$("targetContactNameEmailPhone").show();
        $$("targetMailingAddressCell").show();
        $$("targetSocialMedia").hide();
        $$("targetStandardTerms").hide();
        $$("targetContractURL").hide();
        $$("targetLibraryTerms").hide();
        $$("targetServiceFeesFeedback").hide();
        
        $$("targetContactInfoHeader").show();
        $$("targetContractDetailsHeader").hide();

        $$("Target.Target_Genres").hide();
        $$("targetComposersProjects").hide();
        $$("targetPublicityAwardsConnect").show();
        $$("targetNotes").show();
       
        $$("targetContractRowSpacer").show();
        $$("targetTermsRowSpacer").show();

        $$("targetIconSupe").hide();
        $$("targetIconPublisher").hide();
        $$("targetIconLibrary").hide();
        $$("targetIconCompany").show();
        $$("targetIconService").hide();
        $$("targetIconAgent").hide();

        $$("productionSpacer").hide();
        $$("productionSpacer2").hide();
       
        $$("prodTitleStatus").show();
        $$("prodGenreLength").show();
        $$("prodSegStageDeadline").show();
        $$("prodProjectCompanyIMDb").show();
               
        $$("Production.Prod_Genre").show();
        $$("Production.Prod_Length").hide();
        $$("Production.Prod_Ind_Seg").show();
        $$("Production.Prod_Stage").show();
        $$("Production.Prod_Ref_Num").hide();
        $$("Production.Prod_Deadline").show();
        $$("Production.Prod_Project_Name").show();
        $$("Production.Prod_Company").hide();
        $$("Production.Prod_IMDb").show();
        $$("Production.Prod_Notes").hide();                

        $$("opportunitiesCreateDate").setHTML('<span style="color:#351b5b;">Created:&nbsp;' + '</span>');

    }
    else if (thisTarget.Target_Type == 'Library')
    {
        $$("targetInfoHeader").setHTML('<span style="color:#999999;">INFO&nbsp;&nbsp;|&nbsp;&nbsp;</span>' + thisTarget.Target_Name );
        $$("targetResearchHeader").setHTML('<span style="color:#999999;">RESEARCH&nbsp;&nbsp;|&nbsp;&nbsp;</span>' + thisTarget.Target_Company);
        $$("targetProductionsHeader").setHTML('<span style="color:#999999;">' + gProductionsName + '&nbsp;&nbsp;|&nbsp;&nbsp;</span>' + thisTarget.Target_Company);

        $$("targetCompanyIndustryURL").show();
        $$("targetContactNameEmailPhone").show();
        $$("targetMailingAddressCell").show();
        $$("targetSocialMedia").hide();
        $$("targetStandardTerms").show();
        $$("targetContractURL").show();
        $$("targetLibraryTerms").show();
        $$("targetServiceFeesFeedback").hide();

        $$("targetContactInfoHeader").show();
        $$("targetContractDetailsHeader").show();
        
        $$("Target.Target_Genres").show();
        $$("targetComposersProjects").show();
        $$("targetPublicityAwardsConnect").hide();
        $$("targetNotes").show();

        $$("targetContractRowSpacer").show();
        $$("targetTermsRowSpacer").show();

        $$("targetIconSupe").hide();
        $$("targetIconPublisher").hide();
        $$("targetIconLibrary").show();
        $$("targetIconCompany").hide();
        $$("targetIconService").hide();
        $$("targetIconAgent").hide();

        $$("productionSpacer").hide();
        $$("productionSpacer2").show();
      
        $$("prodTitleStatus").show();
        $$("prodGenreLength").show();
        $$("prodSegStageDeadline").show();
        $$("prodProjectCompanyIMDb").hide();
       
        $$("Production.Prod_Genre").show();
        $$("Production.Prod_Length").hide();
        $$("Production.Prod_Ind_Seg").show();
        $$("Production.Prod_Stage").hide();
        $$("Production.Prod_Ref_Num").hide();
        $$("Production.Prod_Deadline").show();
        $$("Production.Prod_Project_Name").hide();
        $$("Production.Prod_Company").hide();
        $$("Production.Prod_IMDb").hide();
        $$("Production.Prod_Notes").hide();                

        $$("opportunitiesCreateDate").setHTML('<span style="color:#351b5b;">Created:&nbsp;' + '</span>');
        
    } 
    else if (thisTarget.Target_Type == 'Sync/Licensing Agent')
    {
        $$("targetInfoHeader").setHTML('<span style="color:#999999;">INFO&nbsp;&nbsp;|&nbsp;&nbsp;</span>' + thisTarget.Target_Name );
        $$("targetResearchHeader").setHTML('<span style="color:#999999;">RESEARCH&nbsp;&nbsp;|&nbsp;&nbsp;</span>' + thisTarget.Target_Company);
        $$("targetProductionsHeader").setHTML('<span style="color:#999999;">' + gProductionsName + '&nbsp;&nbsp;|&nbsp;&nbsp;</span>' + thisTarget.Target_Company);

        $$("targetCompanyIndustryURL").show();
        $$("targetContactNameEmailPhone").show();
        $$("targetMailingAddressCell").show();
        $$("targetSocialMedia").hide();
        $$("targetStandardTerms").show();
        $$("targetContractURL").show();
        $$("targetLibraryTerms").hide();
        $$("targetServiceFeesFeedback").hide();

        $$("targetContactInfoHeader").show();
        $$("targetContractDetailsHeader").show();
        
        $$("Target.Target_Genres").show();
        $$("targetComposersProjects").show();
        $$("targetPublicityAwardsConnect").hide();
        $$("targetNotes").show();
 
        $$("targetContractRowSpacer").hide();
        $$("targetTermsRowSpacer").hide();
        
        $$("targetIconSupe").hide();
        $$("targetIconPublisher").hide();
        $$("targetIconLibrary").hide();
        $$("targetIconCompany").hide();
        $$("targetIconService").hide();
        $$("targetIconAgent").show();
 
        $$("productionSpacer").hide();
        $$("productionSpacer2").show();
       
        $$("prodTitleStatus").show();
        $$("prodGenreLength").show();
        $$("prodSegStageDeadline").show();
        $$("prodProjectCompanyIMDb").hide();
         
        $$("Production.Prod_Genre").show();
        $$("Production.Prod_Length").hide();
        $$("Production.Prod_Ind_Seg").show();
        $$("Production.Prod_Stage").hide();
        $$("Production.Prod_Ref_Num").hide();
        $$("Production.Prod_Deadline").show();
        $$("Production.Prod_Project_Name").hide();
        $$("Production.Prod_Company").hide();
        $$("Production.Prod_IMDb").hide();
        $$("Production.Prod_Notes").hide();                

        $$("opportunitiesCreateDate").setHTML('<span style="color:#351b5b;">Created:&nbsp;' + '</span>');
    } 
    else if (thisTarget.Target_Type == 'Publisher')
    {
        $$("targetInfoHeader").setHTML('<span style="color:#999999;">INFO&nbsp;&nbsp;|&nbsp;&nbsp;</span>' + thisTarget.Target_Name );
        $$("targetResearchHeader").setHTML('<span style="color:#999999;">RESEARCH&nbsp;&nbsp;|&nbsp;&nbsp;</span>' + thisTarget.Target_Company);
        $$("targetProductionsHeader").setHTML('<span style="color:#999999;">' + gProductionsName + '&nbsp;&nbsp;|&nbsp;&nbsp;</span>' + thisTarget.Target_Company);

        $$("targetCompanyIndustryURL").show();
        $$("targetContactNameEmailPhone").show();
        $$("targetMailingAddressCell").show();
        $$("targetSocialMedia").hide();
        $$("targetStandardTerms").show();
        $$("targetContractURL").show();
        $$("targetLibraryTerms").hide();
        $$("targetServiceFeesFeedback").hide();

        $$("targetContactInfoHeader").show();
        $$("targetContractDetailsHeader").show();
        
        $$("Target.Target_Genres").show();
        $$("targetComposersProjects").show();
        $$("targetPublicityAwardsConnect").hide();
        $$("targetNotes").show();

        $$("targetContractRowSpacer").hide();
        $$("targetTermsRowSpacer").hide();

        $$("targetIconSupe").hide();
        $$("targetIconPublisher").show();
        $$("targetIconLibrary").hide();
        $$("targetIconCompany").hide();
        $$("targetIconService").hide();
        $$("targetIconAgent").hide();
       
        $$("productionSpacer").hide();
        $$("productionSpacer2").hide();
       
        $$("prodTitleStatus").show();
        $$("prodGenreLength").show();
        $$("prodSegStageDeadline").hide();
        $$("prodProjectCompanyIMDb").hide();
        
        $$("Production.Prod_Genre").show();
        $$("Production.Prod_Length").hide();
        $$("Production.Prod_Ind_Seg").show();
        $$("Production.Prod_Stage").hide();
        $$("Production.Prod_Ref_Num").hide();
        $$("Production.Prod_Deadline").hide();
        $$("Production.Prod_Project_Name").hide();
        $$("Production.Prod_Company").hide();
        $$("Production.Prod_IMDb").hide();
        $$("Production.Prod_Notes").hide();                

        $$("opportunitiesCreateDate").setHTML('<span style="color:#351b5b;">Created:&nbsp;' + '</span>');

    } 
    else if (thisTarget.Target_Type == 'Pay-To-Play Service')
    {
    
	$$("Production.Prod_Sample_Links").show();
	$$("Production.Prod_Sample_Links").setHTML('');
	$$("linksLabel").show();
	
        $$("targetInfoHeader").setHTML('<span style="color:#999999;">INFO&nbsp;&nbsp;|&nbsp;&nbsp;</span>' + thisTarget.Target_Name );
        $$("targetResearchHeader").setHTML('<span style="color:#999999;">RESEARCH&nbsp;&nbsp;|&nbsp;&nbsp;</span>' + thisTarget.Target_Company);
        $$("targetProductionsHeader").setHTML('<span style="color:#999999;">' + gProductionsName + '&nbsp;&nbsp;|&nbsp;&nbsp;</span>' + thisTarget.Target_Company);

        $$("targetCompanyIndustryURL").show();
        $$("targetContactNameEmailPhone").hide();
        $$("targetMailingAddressCell").hide();
        $$("targetSocialMedia").hide();
        $$("targetStandardTerms").hide();
        $$("targetContractURL").show();
        $$("targetLibraryTerms").hide();
        $$("targetServiceFeesFeedback").show();
        
        $$("targetContactInfoHeader").hide();
        $$("targetContractDetailsHeader").show();
        
        $$("Target.Target_Genres").hide();
        $$("targetComposersProjects").hide();
        $$("targetPublicityAwardsConnect").hide();
        $$("targetNotes").show();

        $$("targetContractRowSpacer").show();
        $$("targetTermsRowSpacer").hide();
       
        $$("targetIconSupe").hide();
        $$("targetIconPublisher").hide();
        $$("targetIconLibrary").hide();
        $$("targetIconCompany").hide();
        $$("targetIconService").show();
        $$("targetIconAgent").hide();

        $$("productionSpacer").hide();
        $$("productionSpacer2").hide();
        
        $$("prodTitleStatus").show();
        $$("prodGenreLength").show();
        $$("prodSegStageDeadline").show();
        $$("prodProjectCompanyIMDb").hide();
       
        $$("Production.Prod_Genre").show();
        $$("Production.Prod_Length").show();
        $$("Production.Prod_Ind_Seg").show();
        $$("Production.Prod_Stage").hide();
        $$("Production.Prod_Ref_Num").show();
        $$("Production.Prod_Deadline").show();
        $$("Production.Prod_Project_Name").hide();
        $$("Production.Prod_Company").hide();
        $$("Production.Prod_IMDb").hide();
        $$("Production.Prod_Notes").show();                

        $$("opportunitiesCreateDate").setHTML('<span style="color:#351b5b;">Created:&nbsp;' + '</span>');

    }    
}
// ------------------------------------------------------------ //
function targetsIsDirty()
{
    //console.log("targetsIsDirty()");
    
    targetsDirty = false;
    if (targetsCurrID.row !== undefined)
    {
        if (targetsCurrID.row.length > 0 && gCurrTarget.Target.id !== undefined && gCurrTarget.Target.id.length > 0)
        {
            if ($$("targetsEditForm").isDirty())
            {
                targetsDirty = true;
                webix.html.removeCss( $$("btnTargetsSave").getNode(), "light_button");  
                $$("btnTargetsCancel").enable();
                if (targetsFstCheck == true) 
                {
                    targetsFstCheck = false;
                    //console.log('turned it off');
                    setTimeout('webix.html.triggerEvent($$("btnTargetsCancel").getInputNode(), "MouseEvents", "click");',100);
                    return false;
                }
            }
            else
            {
                webix.html.addCss( $$("btnTargetsSave").getNode(), "light_button");  
                $$("btnTargetsCancel").disable()
                targetsDirty = false;
            }
        }
    }
    return targetsDirty;
}
// ------------------------------------------------------------ //
function dteComp(d1,d2)
{
    // d1 = webix ctrl date value  - d2 = keepRecord date value
    try {if (d1 == "") {d1 = null}} catch(err) {a=1;}
    try {if (d2 == "") {d2 = null}} catch(err) {a=1;}
    
    if (d1 == null && d2 != null) {return true;}
    if (d2 == null && d1 != null) {return true;}
    if (d1 == null && d2 == null) {return false;}
    
    d1_iso = new Date(d1.getTime() - d1.getTimezoneOffset() * 60000).toISOString();
    d1_iso = d1_iso.substring(0,19).replace('T',' ');
    if (d1_iso == d2) {return false;} else {return true;}
}
// ------------------------------------------------------------ //
function isCustomPitchDirty()
{
    isDirty = false;
	//debugger;
    
    if (pitchesCurrID.row !== undefined)
    {
	if (dataWH.Pitches.keepRecord.hasOwnProperty('Pitch_ID') == false || gCurrPitch.hasOwnProperty('Pitch') == false) {return false;}
	
	if (gPTOrder_Dirty == true) {return true;}
    
        if (pitchesCurrID.row.length > 0 && gCurrPitch.Pitch.id !== undefined && gCurrPitch.Pitch.id.length > 0)
        {    
	    if ($$("Pitch.Pitch_Status").getValue() != dataWH.Pitches.keepRecord.Pitch_Status) {isDirty = true;}
	    if ($$("Pitch.Pitch_Project").getValue() != dataWH.Pitches.keepRecord.Pitch_Project) {isDirty = true;}
		if ($$("Pitch.Pitch_Playlist_Skin").getValue() != dataWH.Pitches.keepRecord.Pitch_Playlist_Skin) {isDirty = true;}
	    
	    if (dteComp($$("Pitch.Pitch_Deadline").getValue(), dataWH.Pitches.keepRecord.Pitch_Deadline) == true) {isDirty = true;}
	    if (dteComp($$("Pitch.Pitch_Submitted").getValue(), dataWH.Pitches.keepRecord.Pitch_Submitted) == true) {isDirty = true;}
	    if (dteComp($$("Pitch.Pitch_Next_FUp").getValue(), dataWH.Pitches.keepRecord.Pitch_Next_FUp) == true) {isDirty = true;}
	    if (dteComp($$("Pitch.Pitch_Last_FUp").getValue(), dataWH.Pitches.keepRecord.Pitch_Last_FUp) == true) {isDirty = true;}

	    if ($$("Pitch.Pitch_Description").getValue() != dataWH.Pitches.keepRecord.Pitch_Description ) {isDirty = true;}
	    
	    if ($$("refPitchTargetProd.TargetProd.Prod_Project_Name").getValue() != refPitchTargetProd.TargetProd.Prod_Project_Name) {isDirty = true;}
		
		//debugger; 
		if (dataWH.Pitches.keepRecord.Pitch_Allow_Download == false && $$("Pitch.Pitch_Allow_Download").getValue() == 1) {isDirty = true;}
		else if (dataWH.Pitches.keepRecord.Pitch_Allow_Download == true && $$("Pitch.Pitch_Allow_Download").getValue() == 0) {isDirty = true;}
		
	}
    }
    return isDirty;
}
// ------------------------------------------------------------ //
function pitchesIsDirty()
{
    setTimeout("pitchesIsDirtyLag();",600);
}
// ------------------------------------------------------------ //
function pitchesIsDirtyLag()
{
    pitchesDirty = false;
    console.log("pitchesIsDirtyLag()");
    if (pitchesCurrID.row !== undefined)
    {
	if (dataWH.Pitches.keepRecord.hasOwnProperty('Pitch_ID') == false || gCurrPitch.hasOwnProperty('Pitch') == false) {return false;}
    
        if (pitchesCurrID.row.length > 0 && gCurrPitch.Pitch.id !== undefined && gCurrPitch.Pitch.id.length > 0)
        {
	    if (isCustomPitchDirty() == true)
            {
                pitchesDirty = true;
                webix.html.removeCss( $$("btnPitchesSave").getNode(), "light_button");  
                $$("btnPitchesCancel").enable();
                if (1 == 2) //(pitchesFstCheck == true) 
                {
                    pitchesFstCheck = false;
                    setTimeout('webix.html.triggerEvent($$("btnPitchesCancel").getInputNode(), "MouseEvents", "click");',100);
                    return false;
                }
            }
            else
            {
                webix.html.addCss( $$("btnPitchesSave").getNode(), "light_button");  
                $$("btnPitchesCancel").disable()
                pitchesDirty = false;
            }
        }
    }
    return pitchesDirty;
}
// ------------------------------------------------------------ //
function pitchesIsDirty_old()
{
    pitchesDirty = false;
    if (pitchesCurrID.row !== undefined)
    {
        if (pitchesCurrID.row.length > 0  && gCurrPitch.hasOwnProperty('Pitch') == true && gCurrPitch.Pitch.id !== undefined && gCurrPitch.Pitch.id.length > 0)
        {
            if ($$("pitchesEditForm").isDirty())
            {
                pitchesDirty = true;
                webix.html.removeCss( $$("btnPitchesSave").getNode(), "light_button");  
                $$("btnPitchesCancel").enable();
                if (1 == 2) // (pitchesFstCheck == true) 
                {
                    pitchesFstCheck = false;
                    setTimeout('webix.html.triggerEvent($$("btnPitchesCancel").getInputNode(), "MouseEvents", "click");',100);
                    return false;
                }
            }
            else
            {
                webix.html.addCss( $$("btnPitchesSave").getNode(), "light_button");  
                $$("btnPitchesCancel").disable()
                pitchesDirty = false;
            }
        }
    }
    return pitchesDirty;
}
// ------------------------------------------------------------ //
function contactsIsDirtyxxx()
{
setTimeout('contactsIsDirtyLag();',500);
}
// ------------------------------------------------------------ //
function contactsIsDirty()
{
    contactsDirty = false;
    if (contactsCurrID.row !== undefined)
    {	
        if (contactsCurrID.row.length > 0 && gCurrContact.Contact.id !== undefined && gCurrContact.Contact.id.length > 0)
        {
            if ($$("contactsEditForm").isDirty())
            {
                contactsDirty = true;
                webix.html.removeCss( $$("btnContactsSave").getNode(), "light_button");  
                $$("btnContactsCancel").enable();
                if (contactsFstCheck == true) 
                {
                    contactsFstCheck = false;
                    setTimeout('webix.html.triggerEvent($$("btnContactsCancel").getInputNode(), "MouseEvents", "click");',100);
                    return false;
                }
            }
            else
            {
                webix.html.addCss( $$("btnContactsSave").getNode(), "light_button");  
                $$("btnContactsCancel").disable()
                contactsDirty = false;
            }
        }
    }
    return contactsDirty;
}
// --------------------------------------------------------------------------- //
function catalogIsDirty()
{
    dirty = false;
    try {if ($$("tour1").isVisible()) {return;}} catch(err) {a=1;}
    
    if (catalogCurrID.row !== undefined)
    {
        if (catalogCurrID.row.length > 0 && gCurrTrack.id !== undefined && gCurrTrack.id.length > 0)
        {         
            if ($$("catalogEditForm").isDirty())
            {
                dirty = true;
                webix.html.removeCss( $$("btnCatalogSave").getNode(), "light_button");  
                $$("btnCatalogCancel").enable();
                if (catalogFstCheck == true) 
                {
                    catalogFstCheck = false;
                    setTimeout('webix.html.triggerEvent($$("btnCatalogCancel").getInputNode(), "MouseEvents", "click");',100);
                    return false;
                }
            }
            else
            {
                webix.html.addCss( $$("btnCatalogSave").getNode(), "light_button");  
                $$("btnCatalogCancel").disable()
                dirty = false;
            }
        }
    }
    return dirty;
}
// --------------------------------------------------------------------------- //
function projectsIsDirty()
{ 
        prjDirty = false;noForm = false;
        try {theForm} catch(err) {noForm = true;}
        chnges = false;
        if (noForm == false)
        {
                if ($$("Data_Entry_Level") == undefined)
                {
                        noForm = true;
                }
                else
                {
                        if ($$("Data_Entry_Level").isVisible() == true)
                        {
                                noForm = false;
                                chnges = theForm.isDirty();
                        }
                        else
                        {
                                noForm = true;
                        }			
                }
        }
        if (chnges || noForm == false) {prjDirty = true;}
        return prjDirty;
}

winAdmin = '';chkNewAcct = '';
// --------------------------------------------------------------------------- //
function prodPmt(spec='n')
{
    lcURL = '/pmtadmin/?go=y&spec='+spec+'&seq='+seq();
    winAdmin = window.open(lcURL);
    
}    
// ------------------------------------------------------------ //
function showBilling()
{    

    var billingContent = 
    [
        {   view: "template", 
            scroll:true,
            template: 'hello',
            css: "help_dialog",
            borderless:1,
        },
    ];    

    inHP = 0.80;
    inWP = 0.45;
    genHelpWindow("Account Billing",inHP,inWP,billingContent);
    setTimeout('$$("helpWindowClose").show();',800);

}

pmtFreq = ''; pmtService = '';

// ------------------------------------------------------------ //
function procPayment()
{
    if (pmtService == 'Stripe')
    {
            if (pmtFreq == 'Monthly') 
                    {priceID = cat_refs.Price_Keys.Stripe_Pro_Monthly;} 
            else
                    {priceID = cat_refs.Price_Keys.Stripe_Pro_Yearly;} 
                    
            createCheckoutSession(priceID).then(function(data) 
            {
              //Call Stripe.js method to redirect to the new Checkout page
              stripe.redirectToCheckout({sessionId: data.sessionId}).then(handleResultStripe);
            });

    }
    else
    {
            // PayPal processing here
    }
}
// ------------------------------------------------------------ //
function handleResultStripe()
{
    a=1;
}
// ------------------------------------------------------------ //
function handleResultPayPal()
{
    a=1;
}
// ------------------------------------------------------------ //
function windowFWDCall(inJSON)
{
    //gTSSocket.send('json|{"Call": "test", "Mode": "Try", "JustFWD": "y"}');
	inJSON.JustFWD = 'y';
	if (typeof(inJSON) == "object")	{lcJSON = JSON.stringify(inJSON);} else {lcJSON = inJSON;}
	if (lcJSON.substring(0,5) != 'json|') {lcJSON = 'json|' + lcJSON;}
	gTSSocket.send(lcJSON);
}
// ------------------------------------------------------------ //
function tryCall()
{
    gTSSocket.send('json|{"Call": "test", "Mode": "Try"}');
}
// ------------------------------------------------------------ //
function tsSocketBack(data)
{
	tjd = data.replace('json|','');
    oJSON = JSON.parse(tjd);
    //console.log(oJSON);
    

}
// ------------------------------------------------------------ //
function tsSocketConnect()
{
    //return;
    
	ur = 'ws://localhost:5564?uid=' + gcFP;
    gTSSocket = new WebSocket(ur); 
    gTSSocket.onmessage = function(event){tsSocketBack(event.data);gsSocketAvail = true;} 
    gTSSocket.onopen = function(){gsSocketAvail = true;} 
    gTSSocket.onclose = function(){gsSocketAvail = false;}
    gTSSocket.onerror = function(){gsSocketAvail = true;}
}
// ------------------------------------------------------------ //
function pitchesFilter(text)
{
  filtOn = $$("pitchesSearchFld").getValue().toLowerCase(); 
  whichType = $$("pitchesMainFilter").getValue();
          
    tdp = eval('dataWH.Pitches.dp'); 
    dtable = $$("pitchesTable");
    fltText = dataWH.Pitches.Settings.filterText = text;
    
    dtable.filter(function(obj){
        return true;
    }); 
    
    if (text == '') 
	{webix.html.removeCss($$("pitchesSearchFld").getNode(), "pasted_data");}
    else 
	{webix.html.addCss($$("pitchesSearchFld").getNode(), "pasted_data");}     
    
    if (text.length == 0  && whichType == 'all') {return;} 
    
	
    dtable.filter(function(obj)
    { 
        record = obj;
        textHide = false;typeHide = false;
        if (text.length > 0 || whichType != 'all')
        {
	
	    if (whichType == 'all') {typeHide = false}
	    else if (whichType == 'unpitched') {if (obj.Pitch_Status != 'Unpitched') {typeHide = true;}}
	    else if (whichType == 'submitted') {if (obj.Pitch_Status != 'Submitted') {typeHide = true;}}
	    else if (whichType == 'followup') {if (obj.Pitch_Status != 'Follow-Up') {typeHide = true;}}
	    else if (whichType == 'followedup') {if (obj.Pitch_Status != 'Followed-Up') {typeHide = true;}}
	    else if (whichType == 'licensed') {if (obj.Pitch_Status != 'Licensed') {typeHide = true;}}
	    else if (whichType == 'closed') {if (obj.Pitch_Status != 'Closed') {typeHide = true;}}
	
            textHide = true;
            var columns = dtable.config.columns;   
            fldList = 'Pitch_Project,Pitch_Status,Pitch_Notes,Pitch_Description,Pitch_Category,Target_Name';
            for (var i=0; i<columns.length; i++)
            {
                fld = columns[i].id;
                if (fldList.indexOf(fld) == -1) {continue;}
                try
                {
                    if (record[columns[i].id].toString().toLowerCase().indexOf(text.toLowerCase()) != -1) {textHide = false;break;}
                }
                catch(err) 
                {   
                    // a = 1;
                }                
            }
            
	    resHide = false;
	    if (textHide == true || typeHide == true) {resHide = true;}
	    //console.log(record,'texthide=',textHide,'typehide=',typeHide,'reshide=',resHide);
	    return !resHide;
        }                   
        
    });
}// ------------------------------------------------------------ //
function licensesFilter(text)
{
  filtOn = $$("licensesSearchFld").getValue().toLowerCase(); 
  whichType = $$("licensesMainFilter").getValue();
          
    tdp = eval('dataWH.Pitch_Tracks.dp'); 
    dtable = $$("licensesTable");

    if (text == '') 
	{webix.html.removeCss($$("licensesSearchFld").getNode(), "pasted_data");}
    else 
	{webix.html.addCss($$("licensesSearchFld").getNode(), "pasted_data");}        
	
    dtable.filter(function(obj){
        return true;
    }); 
    
    if (text.length == 0  && whichType == 'all') {return;}

    dtable.filter(function(obj)
    { 
        record = obj;
        textHide = false;typeHide = false;
        if (text.length > 0 || whichType != 'all')
        {
	
	    if (whichType == 'all') {typeHide = false}
	    else if (whichType == 'filmtv') {if (obj.Track_License.PT_Ind_Seg != 'Film' && obj.Track_License.PT_Ind_Seg != 'TV' && obj.Track_License.PT_Ind_Seg != 'Film/TV') {typeHide = true;}}
	    else if (whichType == 'advertising') {if (obj.Track_License.PT_Ind_Seg != 'Commercials') {typeHide = true;}}
	    else if (whichType == 'streaming') {if (obj.Track_License.PT_Ind_Seg != 'Streaming') {typeHide = true;}}
	    else if (whichType == 'microlicensing') {if (obj.Track_License.PT_Ind_Seg != 'MicroLicensing') {typeHide = true;}}
	    else if (whichType == 'corporate') {if (obj.Track_License.PT_Ind_Seg != 'Corporate') {typeHide = true;}}
	    else if (whichType == 'games') {if (obj.Track_License.PT_Ind_Seg != 'Games') {typeHide = true;}}
	
            textHide = true;
            var columns = dtable.config.columns;   
           
	    rval = record['Track_License']['PT_Ind_Seg'].toString().toLowerCase();
	    if (rval.length > 0 && rval.indexOf(text.toLowerCase()) > -1 != false) {textHide = false;}
	    
	    rval = record['Track_License']['PT_Network'].toString().toLowerCase();
	    if (rval.length > 0 && rval.indexOf(text.toLowerCase()) > -1 != false) {textHide = false;}		
	    
	    rval = record['Track_License']['PT_EpisodeName'].toString().toLowerCase();
	    if (rval.length > 0 && rval.indexOf(text.toLowerCase()) > -1 != false) {textHide = false;}
	    
	    rval = record['Track_License']['PT_EpisodeNum'].toString().toLowerCase();
	    if (rval.length > 0 && rval.indexOf(text.toLowerCase()) > -1 != false) {textHide = false;}		
	    
	    rval = record['Track_License']['Track']['TIT2_TrackName'].toString().toLowerCase();
	    if (rval.length > 0 && rval.indexOf(text.toLowerCase()) > -1 != false) {textHide = false;}
	    
	    rval = record['Track_License']['Target']['Target_Name'].toString().toLowerCase();
	    if (rval.length > 0 && rval.indexOf(text.toLowerCase()) > -1 != false) {textHide = false;}	
	    
	    rval = record['Track_License']['Production']['Prod_Title'].toString().toLowerCase();
	    if (rval.length > 0 && rval.indexOf(text.toLowerCase()) > -1 != false) {textHide = false;}	
	    
	    rval = record['Track_License']['Production']['Prod_Project_Name'].toString().toLowerCase();
	    if (rval.length > 0 && rval.indexOf(text.toLowerCase()) > -1 != false) {textHide = false;}		
            
            
	    resHide = false;
	    if (textHide == true || typeHide == true) {resHide = true;}
	    //console.log(record,'texthide=',textHide,'typehide=',typeHide,'reshide=',resHide);
	    return !resHide;
        }                   
        
    });
}
// ------------------------------------------------------------ //
function checkContactTypes(inWhich, inTypes)
{
    // inWhich = vague type ... like 'company'
    fnd = false;
    if (inWhich == '') {inWhich = 'all';}
    
    types_person = 'Personal';
    types_collab = 'Collaborator|Contractor';
    types_supe = 'Music Supervisor';
    types_library = 'Library|Sync/Licensing Agent|Publisher';
    types_company = 'Production Company';
    types_all = 'Personal|Collaborator|Music Supervisor|Sync/Licensing Agent|Library|Other|Production Company|Contractor|Publisher|Label|Pay-To-Play Service|'    
    checkTypes = types_all;

    if      (inWhich == 'personal')     {checkTypes = types_person;}
    else if (inWhich == 'collaborator') {checkTypes = types_collab;}
    else if (inWhich == 'supe')         {checkTypes = types_supe;}
    else if (inWhich == 'library')      {checkTypes = types_library;}
    else if (inWhich == 'company')      {checkTypes = types_company;}

    if (obj.inTypes == '') {return false;}
    
    lst = inTypes.split(',');
    fnd = false;
    for (ndx=0; ndx < lst.length; ndx++)
    {
	typ = lst[ndx]; 
	if (checkTypes.indexOf(typ) > -1) {fnd = true;break;}
    }
    
return !fnd;
}
// ------------------------------------------------------------ //
function contactsFilter(text)
{

  if ($$("contactsSearchFld") == undefined) {return;}
  //console.log("contactsFilter():");
    
  filtOn = $$("contactsSearchFld").getValue().toLowerCase();
  whichType = $$("contactMainFilter").getValue();
  if (whichType == '') {whichType = 'all';}
  
  if (text == 'swContactACTIVE') {text = '';}
          
    tdp = eval('dataWH.Contacts.dp'); 
    dtable = $$("contactsTable");
    fltText = dataWH.Contacts.Settings.filterText = text;
    swVal = $$("swContactACTIVE").getValue();
    
    dtable.filter(function(obj){
        return true;
    }); 
    
    if (text == '') 
	{webix.html.removeCss($$("contactsSearchFld").getNode(), "pasted_data");}
    else 
	{webix.html.addCss($$("contactsSearchFld").getNode(), "pasted_data");}      
    
    if (text.length == 0 && swVal == 0  && whichType == 'all') {return;}   
    
    dtable.filter(function(obj)
    { 
        record = obj;
        textHide = false;switchHide = false;typeHide = false;
	//if (1 == 1)
	if (text.length >= 0 || whichType != 'all')
        {
	
	    if (whichType == 'all') {typeHide = false}
	    else {typeHide = checkContactTypes(whichType, obj.Types);
	    }
	
            textHide = true;
            var columns = dtable.config.columns;   
            fldList = 'Full_Name,Last_Name,First_Name,Middle_Name,Company,Email,Phone,Cell,Types,Address1,Address2,City,StateProv,Country,PRO_Name,IPI_Num,Notes,Ind_Seg,Genres';
            for (var i=0; i<columns.length; i++)
            {
                fld = columns[i].id;
                if (fldList.indexOf(fld) == -1) {continue;}
                try
                {
                    if (record[columns[i].id].toString().toLowerCase().indexOf(text.toLowerCase()) != -1) {textHide = false;break;}		    
                }
                catch(err) 
                {   
                    // a = 1;
                } 		
            }
	    
	    if (swVal == 1 && obj.Status == 'Inactive') {switchHide = true;}
            
            //console.log(record,textHide,switchHide);
	    if (textHide == true || switchHide == true || typeHide == true) {return false;} else {return true;}
            //return !textHide;
        }                   
        
    });
}
// ------------------------------------------------------------ //
function wzPitchLookupIcon(obj)
{
    if (obj.Primary_Track == true)
    {
        return icon_primary_enabled;
    }
    else if (obj.Is_Alternate == true)
    {
        return icon_alternate_enabled;
    }
    else if (obj.Is_Stem == true)
    {
        return icon_stem_enabled;
    }
    else
    {
        return icon_contact_library;
    }    
}
// ------------------------------------------------------------ //
function usedPRODataIcon(obj,inFld='usedPROData')
{
    if (inFld == 'usedPROData')
    {
	if (obj.Used_PRO_Data == 0)
	{
	    return icon_no_pro_data;
	}  
	else if (obj.Used_PRO_Data == 2)
	{
	    return icon_bad_pro_data;
	} 	
	else
	{
	    return icon_yes_pro_data;
	} 
    }
    else if (inFld == 'fromPROData_Right') 
    {
	if (obj.Right_Holder.PRO_WorkNum.length == 0)
	{
	    return icon_no_pro_data;
	}  
	else if (obj.Right_Holder.Used_PRO_Data == 2)
	{
	    return icon_bad_pro_data;
	} 	
	else
	{
	    return icon_yes_pro_data;
	} 
    }
    else if (inFld == 'fromPROData_Target') 
    {
	if (obj.Target.PRO_WorkNum.length == 0)
	{
	    return icon_no_pro_data;
	}  
	else if (obj.Target.Used_PRO_Data == 2)
	{
	    return icon_bad_pro_data;
	} 	
	else
	{
	    return icon_yes_pro_data;
	} 
    }    
    else {return '';}
}
// ------------------------------------------------------------ //
function shareLookupIcon(obj)
{
    if (obj.Perm_Share_Link.length == 0)
    {
        return icon_no_share;
    }
    else if (obj.Perm_Share_Outdated == 'Y')
    {
        return icon_old_share;
    }     
    else
    {
        return icon_has_share;
    }    
    
}
// ------------------------------------------------------------ //
function targetLookupIcon(obj)
{
    if (obj.Target_Type == 'Music Supervisor')
    {
        return icon_contact_supe;
    }
    else if (obj.Target_Type == 'Production Company')
    {
        return icon_contact_prod_company;
    }
    else if (obj.Target_Type == 'Pay-To-Play Service')
    {
        return icon_contact_service;
    }
    else if (obj.Target_Type == 'Publisher')
    {
        return icon_contact_publisher;
    }
    else if (obj.Target_Type == 'Sync/Licensing Agent')
    {
        return icon_contact_syncAgent;
    }
    else if (obj.Target_Type == 'Library')
    {
        return icon_contact_library;
    }  
    else
    {
	return '';
    }
}
// ------------------------------------------------------------ //
function productionLookupStatusIcon(obj)
{
    if (obj.Production.Prod_Status == 'Pitched')
    {
        return icon_status_pitched;
    }
    else if (obj.Production.Prod_Status == 'Pending')
    {
        return icon_status_pending;
    }
    else if (obj.Production.Prod_Status == 'Closed')
    {
        return icon_status_closed;
    }
    else
    {
        return icon_status_other;
    }    
}
// ------------------------------------------------------------ //
function industryLookupIcon(obj)
{
    if (obj.PT_Ind_Seg == 'Film')
    {
        return icon_industry_film;
    }
    else if (obj.PT_Ind_Seg == 'TV')
    {
        return icon_industry_tv;
    }
    else if (obj.PT_Ind_Seg == 'Film/TV')
    {
        return icon_industry_film;
    }
    else if (obj.PT_Ind_Seg == 'Commercials')
    {
        return icon_industry_commercials;
    }
    else if (obj.PT_Ind_Seg == 'Streaming')
    {
        return icon_industry_streaming;
    }
    else if (obj.PT_Ind_Seg == 'Games')
    {
        return icon_industry_games;
    }
    else if (obj.PT_Ind_Seg == 'MicroLicensing')
    {
        return icon_industry_microLicensing;
    }
    else if (obj.PT_Ind_Seg == 'Corporate')
    {
        return icon_industry_corporate;
    }
    else
    {
        return icon_industry_other;
    }    
}
// ------------------------------------------------------------ //
function catalogImportCatFilter(text)
{
  if (text == '') 
	{webix.html.removeCss($$("importCatSearchFld").getNode(), "pasted_data");}
  else 
	{webix.html.addCss($$("importCatSearchFld").getNode(), "pasted_data");}    
  
    dtable = $$("grid2");
    dtable.filter(function(obj){
        return true;
    }); 
    
    if (text == '') {return true;}
    dtable.filter(function(obj)
    { 
        record = obj;textHide = false;    
        if (text.length > 0)
        {
            textHide = true;
            var columns = dtable.config.columns;             
            fldList = 'Full_FileName,TIT2_TrackName';

            for (var i=0; i<columns.length; i++)
            {
                fld = columns[i].id;
                if (fldList.indexOf(fld) == -1) {continue;}
                try
                {
                    if (record[columns[i].id].toString().toLowerCase().indexOf(text.toLowerCase()) != -1) {textHide = false;break;}
                }
                catch(err) {a = 1;}                
            }
                        
            resHide = false;
            if (textHide == true) {resHide = true;}
            return !resHide;
        }                           
    });
}
// ------------------------------------------------------------ //
function catalogImportCSVFilter(text)
{
  if (text == '') 
	{webix.html.removeCss($$("importCSVSearchFld").getNode(), "pasted_data");}
  else 
	{webix.html.addCss($$("importCSVSearchFld").getNode(), "pasted_data");}    
  
    dtable = $$("grid1");
    dtable.filter(function(obj){
        return true;
    }); 
    
    if (text == '') {return true;}

    dtable.filter(function(obj)
    { 
        record = obj;textHide = false;    
        if (text.length > 0)
        {
            textHide = true;
            var columns = dtable.config.columns;             
            fldList = 'Track_Name';

            for (var i=0; i<columns.length; i++)
            {
                fld = columns[i].id;
                if (fldList.indexOf(fld) == -1) {continue;}
                try
                {
                    if (record[columns[i].id].toString().toLowerCase().indexOf(text.toLowerCase()) != -1) {textHide = false;break;}
                }
                catch(err) {a = 1;}                
            }
                        
            resHide = false;
            if (textHide == true) {resHide = true;}
            return !resHide;
        }                           
    });
}
// ------------------------------------------------------------ //
function targetsFilter(text)
{
  filtOn = $$("targetsSearchFld").getValue().toLowerCase();
  text = filtOn;
  whichStatus = '';

  if ($$("swActiveTarg").getValue() != 0 || $$("swPendingTarg").getValue() != 0 || $$("swRevisitTarg").getValue() != 0 ) {$$("swALLTarg").setValue(0);}
  
  tAll = $$("swALLTarg").getValue();
  if ($$("swActiveTarg").getValue() == 1 && $$("swPendingTarg").getValue() == 1 && $$("swRevisitTarg").getValue() == 1)
  {
    $$("swActiveTarg").setValue(0);
    $$("swPendingTarg").setValue(0);
    $$("swRevisitTarg").setValue(0);
    $$("swALLTarg").setValue(1);
    whichStatus = 'Active|Inactive|Pending|Revisit|Avoid';
  }
  else
  {
    if ($$("swActiveTarg").getValue() == 1) {whichStatus += 'Active|'}
    if ($$("swPendingTarg").getValue() == 1) {whichStatus += 'Pending|'}
    if ($$("swRevisitTarg").getValue() == 1) {whichStatus += 'Revisit|'}
  }
  
    if (text == '') 
	{webix.html.removeCss($$("targetsSearchFld").getNode(), "pasted_data");}
    else 
	{webix.html.addCss($$("targetsSearchFld").getNode(), "pasted_data");}    
  
  if (whichStatus.length == 0) {whichStatus = 'Active|Inactive|Pending|Revisit|Avoid';}
  
  whichType = $$("targetMainFilter").getValue();
  
    tdp = eval('dataWH.Targets.dp'); 
    dtable = $$("targetsTable");
    fltText = dataWH.Contacts.Settings.filterText = text;
    
    dtable.filter(function(obj){
        return true;
    }); 
    
    if (text.length == 0 && whichType == 'all' && whichStatus == 'Active|Inactive|Pending|Revisit|Avoid') {return;}

    dtable.filter(function(obj)
    { 
        record = obj;
        textHide = false;typeHide = false;statusHide = true;
                
        if (text.length > 0 || whichType != 'all' || whichStatus.length > 0)
        {
        
            if(whichStatus.indexOf(obj.Target_Status) > -1) {statusHide = false;}
        
            if (whichType == 'all') {typeHide = false}
            else if (whichType == 'supe') {if (obj.Target_Type != 'Music Supervisor') {typeHide = true;}}
            else if (whichType == 'library') {if (obj.Target_Type != 'Library') {typeHide = true;}}
            else if (whichType == 'company') {if (obj.Target_Type != 'Production Company') {typeHide = true;}}
            else if (whichType == 'agent') {if (obj.Target_Type != 'Sync/Licensing Agent') {typeHide = true;}}
            else if (whichType == 'publisher') {if (obj.Target_Type != 'Publisher') {typeHide = true;}}
            else if (whichType == 'service') {if (obj.Target_Type != 'Pay-To-Play Service') {typeHide = true;}}
            
            textHide = true;
            var columns = dtable.config.columns; 
            
            fldList = 'Target_Type,Target_Status,Target_Name,Target_First,Target_Last,Target_Company,Target_Contact_Title,Target_Email,Target_Cell,Target_Phone,';
            fldList += 'Target_Address1,Target_Address ,Target_City,Target_Industry,Target_Genres,Target_Composers,Target_Current_Projects,Target_Past_Projects,Target_Publicity,Target_Awards';
            fldList += 'Target_Mutual_Connections,Target_Notes,Target_Agreement,Target_StateProv,Target_Country';

            for (var i=0; i<columns.length; i++)
            {
                fld = columns[i].id;
                if (fldList.indexOf(fld) == -1) {continue;}
                try
                {
                    if (record[columns[i].id].toString().toLowerCase().indexOf(text.toLowerCase()) != -1) {textHide = false;break;}
                }
                catch(err) 
                {   
                    // a = 1;
                }                
            }
                        
            resHide = false;
            if (textHide == true || typeHide == true || statusHide == true) {resHide = true;}
            //console.log(record,'texthide=',textHide,'typehide=',typeHide,'reshide=',resHide);
            return !resHide;
        }                   
        
    });
}
// ------------------------------------------------------------ //
function contactsNew() 
{
    if (gAddContactType == 'P') {lcType = 'Person Name:';} else {lcType = 'Company Name:';}
    webix.prompt(
     {
      title: "Add a NEW Contact",
      text: lcType,
      ok: "Add Now",
      cancel: "Cancel",
      input: {
        required: true,
        placeholder: "Jane Doe",
      },
      width:380,
    }).then(function(result)
    {
        contactNewSubmit(result);
        
    }).fail(function(){
      webix.alert({
        type: "alert-error",
        text: "Cancelled"
      });
    });    

}
// ------------------------------------------------------------ //
async function contactNewSubmit(inName)
{
    url = '/data_contacts/?mde=newcontact&seq=' + seq();
    pkge = {'New_Contact': inName, 'id': gXID, 'Contact_Type': gAddContactType};
    response = await axios.post(url, pkge)

    gRes = response;
    resData = response.data; 

    if (resData.status == 'error')
    {
        webix.message({type: "error", text: "<b>Error:</b>&nbsp;&nbsp;"+resData.Message, expire: 10000});
    }
    else
    {
        dataWH.Contacts.dataStore.add(resData.newObj);
        trec = resData.newObj.Cont_ID;         
        contactsCurrID = trec;
        gCurrContact['Contact'] = dataWH.Contacts.dataStore.getItem(contactsCurrID);
        $$("contactsTable").select(gCurrContact.Contact.id)
        $$("contactsEditForm").parse(gCurrContact);        
        
        setTimeout("gotoContactsTab('contactsInfo');",700);
        setTimeout("webix.UIManager.setFocus($$('Contact.Types'));",1200);

        webix.message({type: "success", text: "<b>Success:</b>&nbsp;&nbsp;"+resData.Message, expire: 3000});
    }     
}
// ------------------------------------------------------------ //
function contactsSendEMClear()
{
    $$("contactsEMailTo").setValue(gCurrContact.Contact.Email);
    $$("contactsEMailCC").setValue('');
    $$("contactsEMailCC_ID").setValue('');
    $$("contactsEMailSubject").setValue('');
    //$$("contactsEMailAttach").setValue('');
    $$("contactsSendEmailEditor").setValue('');
    $$("contactsEditForm").setDirty(false);
    contactCurrPMMsg_ID = '';
    gcPrev_Msg_ID = '';
    gKeep_Subject = '';
    //gKeep_Body = '';
    webix.message({type: "debug", text: "Email settings cleared", expire: 2000});
}
// ------------------------------------------------------------ //
function contactsSendEMNow()
{
    ok = true;
    lcTo = $$("contactsEMailTo").getValue();
    lcSubj = $$("contactsEMailSubject").getValue();
    
    if (lcTo == '' || lcSubj == '')
    {
        webix.message({type: "error", text: "Sending an Email requries a <b>To:</b> recipient as well as a message <b>subject line</b>", expire: 10000});
        ok = false;
        return;
    }
    
    lcText = `  
      Send this email to:<br/><br/>
      <span style="font-weight:bold;">##name##</span><br/>
      <span style="color:purple;">##email##</span><br/><br/>
    `;
    
    lcText = lcText.replace('##name##',gCurrContact.Contact.Full_Name);
    lcText = lcText.replace('##email##',gCurrContact.Contact.Email);
  
    webix.confirm(
     {
      title: "<span style='line-height:2.5;'>Send Now</span>" + icon_email_send,
      text: lcText,
      ok: "Send",
      cancel: "Cancel",
      width:380,
    }).then(function(result)
    {
        contactsSendEMNowGo();
        
    }).fail(function(){
      webix.alert({
        type: "alert-error",
        text: "Cancelled"
      });
    });     
    
}
// ------------------------------------------------------------ //
async function contactsSendEMNowGo()
{
    webix.message({type: "info", text: "Sending Email", expire: 2000});
    lcBody = $$("contactsSendEmailEditor").getValue();
    lcTo = $$("contactsEMailTo").getValue();
    lcCC = $$("contactsEMailCC").getValue();
    lcCC_ID = $$("contactsEMailCC_ID").getValue();
    lcSubj = $$("contactsEMailSubject").getValue();
    
    lcTextOnly = $$("contactsSendEmailEditor")._editor.getContent()
   .replace(/<[^>]*>/ig, ' ')
   .replace(/<\/[^>]*>/ig, ' ')
   .replace(/&nbsp;|&#160;/gi, '<br/>')
   .replace(/\s+/ig, ' ')
   .trim();    
    
    gcPrevEmailBody = lcBody;
    
    url = '/data_contacts/?mde=sendemail&seq=' + seq();
    pkge = {'To': lcTo, 'CC': lcCC,  'CC_ID': lcCC_ID, 'Subject': lcSubj, 'Body': lcBody,  'TextOnly': lcTextOnly, 'id': gCurrContact.Contact.id, 'Prev_MsgID': gcPrev_Msg_ID};
    response = await axios.post(url, pkge);
    

    gRes = response;
    resData = response.data; 

    if (resData.status == 'error')
    {
        webix.message({type: "error", text: "<b>Error:</b>&nbsp;&nbsp;"+resData.Message, expire: 10000});
    }
    else
    {
        webix.message({type: "success", text: "<b>Success:</b>&nbsp;&nbsp;"+resData.Message, expire: 5000});
        contactsCurrPMMsg_ID = resData.PMMsg_ID;
        contactsSendEMClear();
    }    
    
}
// ------------------------------------------------------------ //
function catalogAssignType(inType)
{
    catalogTags = []; 
    catalogTags = catalogTagged();
    if (inType == 'Primary') 
	{icn = icon_primary_enabled;}
    else if (inType == 'Alternate')
	{icn = icon_alternate_enabled;}
    else if (inType == 'Stem')
	{icn = icon_stem_enabled;}
    else {icn = '';}
    
    jsonDataX = localStorage.getItem('userMiscFlags');
    if (jsonDataX == null)
    {
		jsonData = {'confirmMarkPrimary': false,'confirmMarkAlternate': false,'confirmMarkStem': false};
		localStorage.setItem('userMiscFlags',JSON.stringify(jsonData));
    }
	
	if (jsonDataX != null) {jsonDataX = JSON.parse(jsonDataX);}
	if (typeof(jsonDataX) != "object") {jsonData = JSON.parse(jsonDataX);}
	else {jsonData = jsonDataX;}

    
    if (inType == 'Primary') {flg = jsonData.confirmMarkPrimary;}
    else if (inType == 'Alternate') {flg = jsonData.confirmMarkAlternate;}
    else {flg = jsonData.confirmMarkStem;}
    
    
    lcCheck = "<span style='color:#999999;font-size:13px;'>(In future, do not ask to confirm this&nbsp;&nbsp;<input style='color:#999999;font-size:14px;' id='chkRemoveFirst' onChange='scbv();' type='checkbox'/>)</span>"
    lcText = "Mark these tracks as <span style='color:purple;font-weight:bold;line-height:3.0;'>" + inType + "?</span>&nbsp;" + icn + "<br/>&nbsp;" + lcCheck + "<br/>";
    
    if (flg == true)
    {
	catalogAssignTypeGo(inType);
	return;
    }
    webix.confirm(
     {
      title: "Mark Tracks",
      text: lcText,
      ok: "Assign",
      cancel: "Cancel",
      width:380,
    }).then(function(result)
    {
	if (gSplitsCheck == 'yes')
	{
	    if (inType == 'Primary') {jsonData.confirmMarkPrimary = true;}
	    else if (inType == 'Alternate') {jsonData.confirmMarkAlternate = true;}
	    else {jsonData.confirmMarkStem = true;}
	    localStorage.setItem('userMiscFlags',JSON.stringify(jsonData));
	}
        catalogAssignTypeGo(inType);
        
    }).fail(function(){
      //webix.alert({
        //type: "alert-error",
        //text: "Cancelled"
      //});
    });     
    
}
// ------------------------------------------------------------ //
async function catalogAssignTypeGo(inType)
{
    webix.message({type: "info", text: "Assigning Tracks", expire: 2000});
    metaProcess('assign',assignType=inType)  
    
}
// ------------------------------------------------------------ //
function cDate(inVal)
{
    if (inVal == null) {return ''}
    try
        {out = inVal.substring(0,10);}
    catch(err) {a=1;}
    return out;
}

// ------------------------------------------------------------- //
function catalogSetView(inVal='',inDesc='',isEnter=false,forFunc='')
{
    //console.log('catalogSetView():');
    if (isEnter == true)    // possibly adding a new entry
    {
        localViewSettings(mde='load',area='catalog',viewtype_id=inVal,view_desc=inDesc,forFunc);    
    }
    else
    {
        localViewSettings(mde='load',area='catalog',viewtype_id=inVal,view_desc=inDesc,forFunc);
    }
}
// ------------------------------------------------------------- //
function localViewSettings(mde='',area='', viewtype_id='', view_desc='', forFunc='')
{
    //{
            //current: 'catalog_standard',
            //list:
            //[ 
                    //{id: 'catalog_standard', 'value': 'Standard', webix_state: {website-state-object...} },
                    //{id: 'catalog_187gf8', 'value': 'My Fancy One', webix_state: {website-state-object...} },
            //]
            
    //}
    if (mde == 'load')
    {
        thisViewId = '';thisViewDesc = '';
        // +++++++++++++++++++++++++++++++++++++++++++++++++ //
        // save current one if not blank
        //if (gUser_Profile.User.catalogViewCurrentId && gUser_Profile.User.catalogViewCurrentDesc.length > 0 && viewtype_id != '**current**')
        if (forFunc == 'change' && viewtype_id != '**current**')
        {
            cSets = webix.storage.local.get("catalogViews");  
            if (cSets != null) 
            {
                gSets = JSON.parse(cSets);
                try 
                {
                    list = gSets.list;
                    for (ndx=0; ndx < list.length; ndx++)
                    {
                        tt = list[ndx]; 
                        if (tt.value == view_desc) 
                        {
                            newState = $$("catalogTable").getState();
                            tt.webix_state = newState;
                            cSets = JSON.stringify(gSets);
                            webix.storage.local.put("catalogViews", cSets);                            
                            break;
                        }
                    }                    
                    
                } catch(err) {list = [];thisViewId = '';}   
            }
        }

        // +++++++++++++++++++++++++++++++++++++++++++++++++ //
        if (area == 'catalog')
        {
            cSets = webix.storage.local.get("catalogViews");
            if (cSets == null) 
            {
                gSets = {'current_id': '', 'current_desc': '', list: []};
                cSets = JSON.stringify(gSets);
                webix.storage.local.put("catalogViews", cSets);
            }
            
            if (cSets != null) 
            {
                gSets = JSON.parse(cSets);
                if (viewtype_id == '**current**') {viewtype_id = gSets.current_id; view_desc = gSets.current_desc;}
                try 
                {
                    list = gSets.list;
                    for (ndx=0; ndx < list.length; ndx++)
                    {
                        tt = list[ndx]; 
                        if (tt.value == view_desc) {thisViewId = tt.id;thisViewDesc = tt.value;thisViewState = tt.webix_state;break;}
                    }                    
                    
                } catch(err) {list = [];thisViewId = '';}
                
                gUser_Profile.User.catalogViewTypes = list;
                gUser_Profile.User.catalogViewCurrentId = thisViewId;
                gUser_Profile.User.catalogViewCurrentDesc = thisViewDesc;                
                
                if (thisViewId == '' && viewtype_id.length > 0)
                {
                    // is a new view..
                    wstate = $$("catalogTable").getState();
                    newObj = {'id': 'catalog_' + seq() + seq(), 'value': view_desc, 'webix_state': wstate}
                    list.push(newObj);
                    gSets = {'current_id': newObj.id, 'current_desc': newObj.value, 'list': list};
                    cSets = JSON.stringify(gSets);
                    webix.storage.local.put("catalogViews", cSets);
                    gUser_Profile.User.catalogViewTypes = list;
                    gUser_Profile.User.catalogViewCurrentId = newObj.id;
                    gUser_Profile.User.catalogViewCurrentDesc = newObj.value;
                    $$("catalogTable").refresh();
                }
                
                if (thisViewId.length > 0) 
                {
                    if ($$("catalogTable") != undefined)
                    {
                        $$("catalogTable").setState(thisViewState);
                        $$("catalogTable").refresh();
                    }
                    gSets.current_id = thisViewId;
                    gSets.current_desc = thisViewDesc;
                    cSets = JSON.stringify(gSets);
                    webix.storage.local.put("catalogViews", cSets);

                }          
            }
        }
    }
        // +++++++++++++++++++++++++++++++++++++++++++++++++ //
    else
    {
        // +++++++++++++++++++++++++++++++++++++++++++++++++ //
        if (area == 'catalog')
        {    
            //vw = webix.UIManager.getState("catalogViews", true)
            //webix.storage.local.put("catalogViews",'' );
        }
    }
}
gProjectClock = '';
// ------------------------------------------------------------- //
function displayProjectClock()
{
    inID = gProjectClock;
    n = $$(inID).config.runningTime;
    $$(inID).config.runningTime = n;
    $$(inID).config.labelRight = formatDaysHrsMinsSecs(n) + '';
    $$(inID).refresh();
    $$(inID).config.runningTime = n + 1;
}
// ------------------------------------------------------------- //
function clockThis(inID,inItem)
{
    var cvar  = "setInterval(displayProjectClock,1000);"
    res = eval(cvar);
    return res;

}
// ------------------------------------------------------------- //
function billInfo()
{
    out = '';
    if (gUser_Profile.Artist.License_Mode == 'Subscriber' || gUser_Profile.Artist.License_Mode == 'Trial')
    {
        out = gUser_Profile.Artist.License_Mode + '&nbsp;until:<br/>' + cDate(gUser_Profile.Artist.License_Expires);
    }
    else
    {
        out = gUser_Profile.Artist.License_Mode + ':&nbsp;&nbsp;&nbsp;' + cDate(gUser_Profile.Artist.License_Expires);
    }
    
    if (gUser_Profile.Artist.Pending_Cancel == true) {out = out.replaceAll('Subscriber&nbsp;until:','<span style="color:darkRed;">Subscription&nbsp;ends:</span>');}
	
	if (gUser_Profile.Artist.Account_Level && glCollab_Only == true)
	{
		out = 'Unlimited free access to invited projects'
	}	
    
    
    return out;
}
// ------------------------------------------------------------- //
function mpmt()
{
    if (gUser_Profile.Artist.Lifetime_Plan_Summary.indexOf('(Lifetime Member)') == -1)
    {
	if (gcAcctLevel == 'Special')
	{
	    prodPmt(spec='y');
	}
	else
	{
	    prodPmt(spec='m');	
	}	
    }
    else
    {
        webix.message({type: "debug", text: "<b>All good!</b>&nbsp;Lifetime membership . :-)", expire: 7000});
    }
}
// ------------------------------------------------------------- //
function invshow()
{
    if (gUser_Profile.Artist.Deal_Receipt_URL.length > 0)
    {
	window.open(gUser_Profile.Artist.Deal_Receipt_URL,'_blank');
    }
    
}
// ------------------------------------------------------------- //
function ppmt()
{
    if (gUser_Profile.Artist.Lifetime_Plan_Summary.indexOf('(Lifetime Member)') == -1)
    {
	if (gcAcctLevel == 'Special')
	{
	    prodPmt(spec='y');
	}
	else
	{
	    prodPmt();	
	}	
    }
    else
    {
        webix.message({type: "debug", text: "<b>All good!</b>&nbsp;Lifetime membership . :-)", expire: 7000});
    }
}
// ------------------------------------------------------------- //
function mbrLvl()
{
    if (gUser_Profile.Artist.Promo_Code.length > 0 && gUser_Profile.Artist.Lifetime_Prod_IDN.length > 0)
    {
        tout =  'TrackStage Pro<br/>Premier Club'
        return (tout);                     
    }
    else
    {   
	
	lcMde = gUser_Profile.Artist.License_Mode;
	tout = 'TrackStage ' + gUser_Profile.Artist.Account_Level;
	if (lcMde == 'Trial') {tout = 'Trial'}
	tout = tout.replaceAll('Standard','Sync')
	tout = tout.replaceAll('Special','Pro Special')
	return tout;
    }
}
// ------------------------------------------------------------- //
function memberLevel(redo=0)
{    
    if (gUser_Profile.Artist.Promo_Code.length > 0 && gUser_Profile.Artist.Lifetime_Prod_IDN.length > 0)
    {
        tout = gUser_Profile.Artist.Lifetime_Plan_Summary.replaceAll(' - ','<br/>')
        tout = tout.replaceAll('TrackStage Pro', 'TrackStage Pro<br/>Premier Club')
        return (icon_lifemember + '' + tout);                     
    }
    else
    {   
	
	lcMde = gUser_Profile.Artist.License_Mode;
	tout = 'TrackStage ' + gUser_Profile.Artist.Account_Level + ' Member';
	tout = tout.replaceAll('False', 'Trial');
	if (lcMde == 'Trial') {tout = icon_trialmember + '' + tout;} else {tout = icon_regmember + '' + tout;}
	tout = tout.replaceAll('Standard Member','Sync Member');
	tout = tout.replaceAll('Basic Member','Lite Member');
	tout = tout.replaceAll('Special Member','Pro Special Member');
	
	if (gUser_Profile.Artist.Account_Level && glCollab_Only == true)
	{
		tout = 'TrackStage Creative Collaborator'
	}
	return tout;
    }
}
// ------------------------------------------------------------- //
function linkOpen(link)
{
    trgt = 'none';
    if      (link == 'spotify')    {trgt = ((gUser_Profile.Artist.Spotify_Access_Token.length > 0) ? gUser_Profile.Artist.Spotify_Access_Token : 'none');}
    else if (link == 'apple')      {trgt = ((gUser_Profile.Artist.AppleMusic_Account.length > 0) ? gUser_Profile.Artist.AppleMusic_Account : 'none');}
    else if (link == 'facebook')   {trgt = ((gUser_Profile.Artist.FB_Account.length > 0) ? gUser_Profile.Artist.FB_Account : 'none');}
    else if (link == 'itunes')     {trgt = ((gUser_Profile.Artist.AppleMusic_Account.length > 0) ? gUser_Profile.Artist.AppleMusic_Account : 'none');}
    else if (link == 'youtube')    {trgt = ((gUser_Profile.Artist.YouTube_Channel.length > 0) ? gUser_Profile.Artist.YouTube_Channel : 'none');}
    else if (link == 'tiktok')     {trgt = ((gUser_Profile.Artist.TikTok_Account.length > 0) ? gUser_Profile.Artist.TikTok_Account : 'none');}
    else if (link == 'soundcloud') {trgt = ((gUser_Profile.Artist.SoundCloud_URL.length > 0) ? gUser_Profile.Artist.SoundCloud_URL : 'none');}
    else if (link == 'amazon')     {trgt = ((gUser_Profile.Artist.Amazon_Account.length > 0) ? gUser_Profile.Artist.Amazon_Account : 'none');}
    else if (link == 'facebook')     {trgt = ((gUser_Profile.Artist.FB_Account.length > 0) ? gUser_Profile.Artist.FB_Account : 'none');}
    else if (link == 'instagram')  {trgt = ((gUser_Profile.Artist.Instagram_Account.length > 0) ? gUser_Profile.Artist.Instagram_Account : 'none');}
    
    if (trgt == 'none') 
        {webix.message({type: "info", text: "<b>Oops:</b>&nbsp;&nbsp;You need to set your " + link.toProperCase() + ' account field in your <b>User Profile</b> first.', expire: 7000});}
    else
        {
            winFeatures = "top=10,left=40,width=" + (ww*0.8) + ",height=" + (hh*0.86);
            winDisco = window.open(trgt, "winLinker", winFeatures); 
        }
}
// ------------------------------------------------------------- //
function setContactImageUploadItems()
{
    $$("contactImageCols").show();
    zz=genImgContactLink(gCurrContact.Contact.Contact_Imge);$$('contactProfileImage').setHTML(zz);$$('contactProfileImage').show();
    $$("contactImageUploader").addDropZone( $$("contactuploadlist").$view, "Drop new image here");
    aaa = $('div[view_id="contactImageUploader"]').first();
    aaa[0].firstElementChild.firstChild.innerHTML = '<span class="fa-solid fa-pencil" style="color:#351b5b"></span>';
    bbb = $("button",aaa);
    bbb.css('width','30px');
    bbb.css('height','30px');
    bbb.css('background','#F6F5FA');
    bbb.css('border','0px');
    
    setTimeout('$$("contactProfileImage").define("template",genImgContactLink(gCurrContact.Contact.Contact_Image));$$("contactProfileImage").refresh();',150);
    
} 
// ------------------------------------------------------------- //
function cpDash_Icon3(trow)
{
    icn = icon_preview_enabled;
    url = 'cpGotoBrief("' + trow.id + '");'; 
    icn = icn.replace("<span class","<span onclick='" + url +  "' class");
    return icn;
}
// ------------------------------------------------------------- //
function cpDash_Icon2(trow)
{
    icn = icon_preview_enabled;
    url = 'cpDash_Icon2_Go("' + trow.id + '");';
    icn = icn.replace("<span class","<span onclick='" + url +  "' class");
    return icn;
}
// ------------------------------------------------------------- //
function cpDash_Icon2_Go(id)
{
    trow = $$("cpNote_Notices").getItem(id);
    cpNoteGotoItem2(trow);
    return icon_preview_enabled;
}
cpProj_tCard = {};
// ------------------------------------------------------------- //
function cpDash_Icon(trow)
{
    icn = icon_preview_enabled;
    url = 'cpDash_Icon_Go("' + trow.id + '");';
    icn = icn.replace("<span class","<span onclick='" + url +  "' class");
    
    return icn;
}
jnkid = '';
// ------------------------------------------------------------- //
function cpDash_Icon_Go(id)
{
    //console.log('clicked',id);
    trow = $$("cpProj_Deadlines").getItem(id);
    if (trow.cpNote_NoticeType == 'Pitch')
    {
	gCurrTab = 'Pitches';
	gotoModule('Pitches');
	id = id.substring(0,id.length-2);
	jnkid = id;
	cpPitch_tItem = $$("pitchesTable").getItem(id);
	setTimeout('$$("pitchesTable").select(jnkid);',1600);
	setTimeout("gotoPitchesTab('pitchesInfo');",1900); 
	setTimeout('$$("pitchesEditForm").clear();',2100);
	setTimeout('$$("pitchesEditForm").parse(gCurrPitch);',2400);
    }
    else
    {
	cpProjGotoItem(trow);
    }

    return icon_preview_enabled;
}
cpProj_tCard = {};
// ------------------------------------------------------------- //
function projectsSummaryReport()
{
    
    webix.message({type: "info", text: "<b>Summary Report</b>&nbsp;&nbsp;Processing...", expire: 2200});
    url = '/TrackStage-Reports/?mde=summaryreport&pid=' + gCurrProjectItem.Proj_ID + '&seq='+seq();
    winPDF = window.open(url);

}
// ------------------------------------------------------------- //
//async function projectsSummaryReport()
//{
    //webix.message({type: "info", text: "<b>Summary Report</b>&nbsp;&nbsp;Processing...", expire: 1200});
    //url = '/kbdata/?mde=summaryreport&seq='+seq();
    //data = {"Proj_ID": gCurrProjectItem.Proj_ID, "Extra": ""}
    //await axios.post(url, data).then(response =>     
    //{
        //console.log("reloadTS got back", response);
        //webix.message({type: "success", text: "Loading report....", expire: 2000});
        //winPDF = window.open(response.data.url); 
    //},
    //(error) => 
    //{ 
        //console.log("Error:", error);
        //webix.message({type: "error", text: "Error with report.", expire: 5000});
    //});      
//}
// ------------------------------------------------------------- //
function projectsCollabLeave()
{
    if (gUser_Profile.Artist.Arti_ID == gCurrProjectItem.Arti_ID)
    {
        webix.message({type: "error", text: "<b>Oops!</b>  You can't leave your <u>own</u> project. " + smile_tongue + " <br/>This is for <b>collaborators</b> who want to leave the project.", expire: 11000});
        return;
    }
    
        webix.confirm(
         {
          title: "Leave Project?",
          text: "Do you want to <b>stop collaborating</b> on this Project?",
          ok: "Yes, leave",
          cancel: "No, stay",
          width:380,
        }).then(function(result)
        {
            projectsCollabLeaveGo();
            
        })      
}
// ------------------------------------------------------------- //
function projectsCollabLeaveGo()
{

    webix.message({type: "debug", text: "<b>Sending Request</b><br/>Stop collaborating on this project", expire: 2200});
    url = '/data_projects/?mde=collableave&seq=' + seq();
    pkge = {'Arti_ID': gUser_Profile.Artist.Arti_ID, 'Proj_ID': gCurrProjectItem.Proj_ID};
    
    axios.post(url,pkge).then(response => 
    {
        //console.log("got back", response);
        webix.message({type: "success", text: "You are no longer a collaborator on this project:  reloading...", expire: 2000});
        setTimeout("location.reload();",2000);
    },
    (error) => 
    { 
    
	if (error.response.status == 502)
	{
	    webix_message({type: "error", text: "<b>Error:</b>&nbsp;TrackStage is currently offline.  Please try back in a few minutes.", expire: 10000},1);
	    return;	
	}    
        //console.log("Error:", error);
        webix.message({type: "error", text: "An error occurred processing your request..", expire: 3000});
    }); 
}
// ------------------------------------------------------------- //
function cpProjGotoItem(trow)
{
    //console.log("cpProjGotoItem():");
    tskid = trow.cpProj_Task_ID;
    prjid = trow.cpProj_Proj_ID;
    //console.log("cpProjGotoItem", prjid, tskid);

    if (trow.cpNote_NoticeType == 'Pitch')
    {
	gCurrTab = 'Pitches';
	gotoModule('Pitches');
	id = trow.Comm_ID;
	if (id.indexOf('_') > -1) {id = id.substring(0,id.length-2);}
	jnkid = id;
	//console.log("jnkid = ", jnkid);
	cpPitch_tItem = $$("pitchesTable").getItem(id);
	setTimeout('$$("pitchesTable").select(jnkid);',1600);
	setTimeout("gotoPitchesTab('pitchesInfo');",1900); 
	setTimeout('$$("pitchesEditForm").clear();',2100);
	setTimeout('$$("pitchesEditForm").parse(gCurrPitch);',2400);
    }
    if (trow.cpNote_NoticeType == 'Birthday')
    {
	gCurrTab = 'Contacts';
	gotoModule('Contacts');
	id = trow.Comm_ID;
	if (id.indexOf('_') > -1) {id = id.substring(0,id.length-2);}
	jnkid = id;
	//console.log("jnkid = ", jnkid);
	cpPitch_tItem = $$("contactsTable").getItem(id);
	setTimeout('$$("contactsTable").select(jnkid);',1600);
	setTimeout("gotoContactsTab('contactsInfo');",1900); 
	setTimeout('$$("contactsEditForm").clear();',2100);
	setTimeout('$$("contactsEditForm").parse(gCurrContact);',2400);
    }    
    else
    {
	gCurrTab = 'Creative';
	gotoModule('Creative');
	cardID = null;
	if (cardID == null)
	{
	    if (gcPAData != null && gcPAData != '' && gcPAData.hasOwnProperty("Project_ID"))
	    {
		$$("projectsKB").select(gcPAData.Project_ID);
		cardID = $$("projectsKB").getSelectedId();
	    }
	}	
	cpProj_tCard = $$("projectsKB").getItem(prjid);
	gCurrProjectItem = cpProj_tCard;
	setTimeout('x1x = gCurrProjectItem.id;tCard = $$("projectsKB").getItem(x1x);$$("projectsKB").showEditor(tCard);',1900);
	
	
	setTimeout(`
	$$("$kanbaneditor1").show();
	if (tskid.length > 0 && tskid != '0') {setTimeout('$$("projectsACTS").select(tskid);',200);}
	if (trow.cpProj_Deadline_Type == 'Project Deadline') {setTimeout('$$("Deadline_Date").focus();webix.html.addCss($$("Deadline_Date").getNode(), "pasted_data");',300);}
	else if (trow.cpProj_Deadline_Type == 'Task Deadline') {a=1;}
	else {setTimeout('$$("Area_Deadline_Date").focus();webix.html.addCss($$("Area_Deadline_Date").getNode(), "pasted_data");',400);}  
	`,2400);
    }
    
}
gctrow = {};
// ------------------------------------------------------------- //
function formatBriefGenCat(obj)
{
    out = obj.Brief_Genre + ' | ' + obj.Brief_Category.replaceAll('|',',').replaceAll('_',' ');
    if (out.endsWith(',') == true)
    {
	out = out.substring(0, out.length-1).trim();
    }
    return out;
    
}
// ------------------------------------------------------------- //
function cpGotoBrief(trw)
{
    trow = $$("cpBriefs").getItem(trw);
    bkey = trow.Brief_Key;
    btyp = trow.Brief_Type;
    console.log("cpGotoBrief():",trow);
    
    if (btyp == 'TAXI')
    {
        url = 'https://www.taxi.com/industry#listing-' + bkey;
        winFeatures = "top=30,left=40,width=" + (ww-(50)) + ",height=" + (hh-20);
        winAdmRep = window.open(url, "winTAXI", winFeatures);    	
    }
    else if (btyp == 'BROADJAM')
    {
	bkey = bkey.replaceAll('BJ','');
        url = 'https://broadjam.com/delivery/opportunity.php?contest_id=' + bkey;
        winFeatures = "top=30,left=40,width=" + (ww-(50)) + ",height=" + (hh-20);
        winAdmRep = window.open(url, "winBroadJam", winFeatures);      
    }
    else if (btyp == 'SONGTRADR')
    {
        url = 'https://www.songtradr.com/user/wanted/v2/opportunities';
        winFeatures = "top=30,left=40,width=" + (ww-(50)) + ",height=" + (hh-20);
        winAdmRep = window.open(url, "winSongTradr", winFeatures);      
    }    
    
}
// ------------------------------------------------------------- //
gPTID = '';
function cpNoteGotoItem2(trow)
{
    //console.log("cpNoteGotoItem2():");
    if (trow.cpNote_NoticeType == 'Email')
    {
        contid = trow.cpNote_Cont_ID;
        gctrow = trow;
	gCurrTab = 'Contacts';
        gotoModule('Contacts');
        cpNote_tItem = $$("contactsTable").getItem(contid);
        gCurrContact.Contact = cpNote_tItem;
        setTimeout('$$("contactsTable").select(gCurrContact.Contact.id);',900);
        setTimeout("gotoContactsTab('contactsContact');",1600);
        
        setTimeout(`           
            setTimeout('contactsGetCommsLog(gctrow);',400); 
        `,2200);
    }
    else if (trow.cpNote_NoticeType == 'Collaborator')
    {
        tskid = '';
        prjid = trow.cpNote_Proj_ID;
        //console.log("cpProjGotoItem", prjid, tskid);
	gCurrTab = 'Creative';
        gotoModule('Creative');
        cpProj_tCard = $$("projectsKB").getItem(prjid);
        gCurrProjectItem = cpProj_tCard;
        setTimeout('x1x = gCurrProjectItem.id;tCard = $$("projectsKB").getItem(x1x);$$("projectsKB").showEditor(tCard);',1900);        
        
        setTimeout(`
        $$("$kanbaneditor1").show();
        `,2400);    
    }
    else if (trow.cpNote_NoticeType == 'Comment')
    {
        tskid = '';
        prjid = trow.cpNote_Proj_ID;
        //console.log("cpProjGotoItem", prjid, tskid);
	gCurrTab = 'Creative';
        gotoModule('Creative');
        cpProj_tCard = $$("projectsKB").getItem(prjid);
        gCurrProjectItem = cpProj_tCard;
        setTimeout('x1x = gCurrProjectItem.id;tCard = $$("projectsKB").getItem(x1x);$$("projectsKB").select(gCurrProjectItem.id)',1900);        
        
        setTimeout(`
            var id = gCurrProjectItem.id;
            var node = $$("projectsKB").getOwnerList(id).getItemNode(id).querySelector(".kbi-comment");
            var popup = $$("projectsKB").getComments();
            var comments = popup.getBody();
            popup.show(node);
            comments.parse($$("projectsKB").getItem(id).comments);
        `,2400);    
    }    
    else if (trow.cpNote_NoticeType == 'Tracking')
    {
        tskid = '';
        prjid = trow.cpNote_Proj_ID;
        //console.log("cpProjGotoItem", prjid, tskid);
	gCurrTab = 'Pitches';
        gotoModule('Pitches');
        gCurrPitch.Pitch = $$("pitchesTable").getItem(prjid);
        setTimeout('$$("pitchesTable").select(gCurrPitch.Pitch.id);',1500);
        setTimeout("setPitchDetails(pitchesCurrID, '', '');",2400);
        if (trow.cpNote_Cont_ID == 'Pitch')
        {
            setTimeout("gotoPitchesTab('pitchesInfo');",1900); 
        }
        else
        {
            //console.log("this PT is ", trow.cpNote_Msg_ID);             
            setTimeout("gotoPitchesTab('pitchesTracks');",1900); 
        } 
    }
}
// ------------------------------------------------------------- //
function openAdmRep(inRep)
{
    if (inRep == false) {return;}
    
    if (inRep.substring(0,6) == 'admcmd')
    {
        url = gcBaseURL + "adminreport/?name=admcmd&&mde=js&seq=" + seq();  
        extra = $('#admdataarea').val();
        cData = {'data': inRep};
        if (extra.length == 0) {cData.extra = '';} else {cData.extra = extra;}
        axios.post(url,cData).then(response => 
        {
            //console.log("reloadTS got back", response);
            webix.message({type: "success", text: "Command was executed.", expire: 2000});
        },
        (error) => 
        { 
            //console.log("Error:", error);
            webix.message({type: "error", text: "Error with command", expire: 3000});
        });         
    }
    else
    {
        url = gcBaseURL + "adminreport/?name=" + inRep + "&seq=" + seq();
        winFeatures = "top=30,left=40,width=" + (ww-(50)) + ",height=" + (hh-20);
        winAdmRep = window.open(url, "winAdmRep", winFeatures);      
    }
  

}
// ------------------------------------------------------------- //
async function projectsInviteCollabGo()
{
    lcID = $$("projectsCollab_ID").getValue();
    lcName = $$("projectsCollabName").getValue(); 
    if (lcName.length == 0)
        {webix.message({type: "error", text: "<b>Error</b><br/>Please select a Collaborator first", expire: 3000});}
    else
    {
        webix.message({type: "debug", text: "<b>Sending Invite</b><br/>Inviting Collaborator to this project", expire: 3000});
        url = '/data_projects/?mde=sendcollabinvite&seq=' + seq();
        pkge = {'CollabName': lcName, 'Cont_ID': lcID, 'Proj_ID': gCurrProjectItem.Proj_ID};
        response = await axios.post(url, pkge)
        gRes = response;
        resData = response.data; 
    
        if (resData.status == 'error')
        {
            webix.message({type: "error", text: "<b>Error:</b>&nbsp;&nbsp;"+resData.Message, expire: 10000});
        }
        else
        {  
            webix.message({type: "debug", text: "<b>Success:</b>&nbsp;&nbsp;"+resData.Message, expire: 6000});
            //$$("Collabs_Invited_Long").setValue(response.data.Collabs_Invited_Long);
            kbItem = $$("projectsKB").data.getItem(gCurrProjectItem.Proj_ID);
           
            gCurrProjectItem.Collabs_Invited_Long = response.data.Collabs_Invited_Long;
            gProjCollabsInvited_List = [];
            gProjCollabsInvited_Vals = [];
            cLst = gCurrProjectItem.Collabs_Invited_Long.split('\n');
            for (ndx =0; ndx < cLst.length; ndx++)
            {
                tCollab = cLst[ndx];
                if (tCollab.length == 0) {continue;}
                cLst2 = tCollab.split('|');
                tID = cLst2[1].replaceAll('  ',' ').replaceAll(' ','').replaceAll('(','').replaceAll(')','');
                cLst3 = cLst2[0].split('<');
                tEmail = cLst3[0].trim();
                tName = cLst3[1].replaceAll('<','').replaceAll('>','').trim();
                gProjCollabsInvited_Vals.push(tID);
                tItem = {id: tID, title: tName, eml: tEmail};
                gProjCollabsInvited_List.push(tItem);                      
            }             
            
            kbItem.Collabs_Invited = response.data.Collabs_Invited; 
            
            setTimeout(`
                    $$("Collabs_Invited_View").getPopup().getList().parse(gProjCollabsInvited_List);
                    $$("Collabs_Invited_View").setValue(gProjCollabsInvited_Vals);
                    $$("Collabs_Invited_View").refresh();
                    `,400);            
                    
        }         
    }
}
// ------------------------------------------------------------- //
function projectsInviteCollab()
{
    lcID = $$("projectsCollab_ID").getValue();
    lcName = $$("projectsCollabName").getValue(); 
    if (lcName.length == 0)
        {webix.message({type: "error", text: "<b>Error</b><br/>Please select a Collaborator first", expire: 3000});}
    else
    {
    
        webix.confirm(
         {
          title: "Send Invite",
          text: "Send this collaborator an Invite Email Now?",
          ok: "Send",
          cancel: "Cancel",
          width:380,
        }).then(function(result)
        {
            projectsInviteCollabGo();
            
        })            
    }
}
gProjOtherCollabs_Vals = [1,7,9,12];
gProjOtherCollabs_List = 
    [
      {id: 1, title: "Robina Ritchie-Barker", eml:"robina@uboribinals.com"},
      {id: 2, title: "second entry", eml:"alice@wewew.wwwrowre.com"},
      {id: 7, title: "seventh", eml:"fred@gmail.com"},
      {id: 8, title: "eight", eml:"test@one.ca"},
      {id: 9, title: "hello ninth", eml:"aaa@eee.com"},
    ];

// ------------------------------------------------------------- //
function projectsSelectCollab()
{
    Make_ContLookup("COLLAB",'',membersOnly=false);
    
    setTimeout(`
    topzval = parseInt($('div[view_id="$kanbaneditor1"]').css('z-index')) + 1;
    $('div[view_id="win_contact_lookup"]').css('z-index',topzval+'');
    `,400);
    
}
// ------------------------------------------------------------- //
function doadmrep()
{
    lcText = "Message/Data:<br/><textarea style='height:130px;width:460px;border-radius:5px;border:solid 1px #dddddd;' id='admdataarea'></textarea><br/>Report/Command:";
    if (gUser_Profile.User.Admin_User == true)
    {
        webix.prompt(
        {            
            title: "Admin Reports",
            width: 500,
            text: lcText,
            ok: "Go",
            type: "prompt-warning",
            cancel: "Cancel",
            callback: function(result) {
                openAdmRep(result);
            }            
        
        });
        
        
    }
}
// -------------------------------------------------------------- //
function contactsGetCommsLog(showRow={})
{
    //console.log("contactsGetCommsLog():");
    url = '/data_contacts/?mde=comms&cid=' + gCurrContact.Contact.id + '&seq=' + seq();
    contactsHistory = [];
    axios.get(url).then(response => 
    {
        //console.log("contactsGetCommsLog got back", response);
        //webix.message({type: "success", text: "<b>Success</b><br/> " + response.data.Message, expire: 1000});
        contactsHistory = response.data.Contact_History;
        $$("contact_Timeline").clearAll();$$("contact_Timeline").parse(contactsHistory);
        
        if (showRow.hasOwnProperty('cpNote_Cont_ID'))
        {
            id = trow.Comm_ID;
            gcCurrEmail = getContHistoryItem(id);
            if (gcCurrEmail.hasOwnProperty('id') == true)
            {
                Make_EmailPreview(gcCurrEmail.url);
            }
            else
            {
               // webix.message({type: "debug", text: "No email preview available for this item", expire: 4000});
            }
        }        
    },
    (error) => 
    { 
        //console.log("Error:", error);
	if (error.response.status == 502)
	{
	    webix_message({type: "error", text: "<b>Error:</b>&nbsp;TrackStage is currently offline.  Please try back in a few minutes.", expire: 10000},1);
	    return;	
	}	
	
        webix.message({type: "error", text: "<b>Error</b><br/> " + response.data.Message, expire: 3000});
        $$("contact_Timeline").clearAll();$$("contact_Timeline").parse(contactsHistory);
    }); 
    $$("contact_Timeline").refresh();    
    

}
// -------------------------------------------------------------- //
function getContHistoryItem(id)
{
    for (ndx =0; ndx < contactsHistory.length; ndx++)
    {
        th = contactsHistory[ndx]; 
        if (th.id == id)
        {
            return th;
        }
    }
    return {}

}
// -------------------------------------------------------------- //
async function doReply()
{
    gotoContactsTab("contactsEmail");
    gcPrev_Msg_ID = gcCurrEmail.PMMsg_ID;
    webix.html.triggerEvent($$("btnContactsSendClear").getInputNode(), "MouseEvents", "click");
    
    purl = gcCurrEmail.url;
    //purl = 'https://web.trackstage.io/YzqMWn0p7J';
    
    lcPreBody = '';
    await axios.get(purl).then(response => 
    {
            //console.log("contactsGetCommsLog got back", response);
            lcPreBody = response.data;            
            
            setTimeout
            (`
                $$("contactsEMailSubject").setValue($$("contHistoryEMailSubject").getValue());
                $$("contactsEMailTo").setValue($$("contHistoryEMailTo").getValue());
                $$("contactsSendEmailEditor").setValue(lcPreBody);
            `,200);            
    
    },
    (error) => 
    { 
            //console.log("Error:", error);
            lcPreBody = '';
    
    }); 
}
// -------------------------------------------------------------- //
function contactsNewEmail()
{
    setTimeout("gotoContactsTab('contactsEmail');",50);
    setTimeout('webix.html.triggerEvent($$("btnContactsSendClear").getInputNode(), "MouseEvents", "click");',250); 
}
gcc_cont = {};
// -------------------------------------------------------------- //
function contactsSetCC()
{
    lcCCEmail = '';
    lcCC = $$("contactsEMailCC").getValue();
    lcCC = lcCC.replace("< ","<").replace(" >",">");
    if (lcCC.indexOf(',') > 0)
    {
        lsc = lcCC.split(',');
        if (lsc.length > 0) {lcCC2 = lsc[0]} else {lcCC2 = lcCC;}
    }
    else {lcCC2 = lcCC;}
    
    x1 = lcCC2.indexOf('<'); x2 = lcCC2.indexOf('>');

    if (x1 > 0 && x2 > 0)
    {
        lcCC3 = lcCC2.substring(x1+1,x2)
    }  
    else {lcCC3 = lcCC2;}
    
    gcc_cont = {};
    loCont = getContactFromEmail(lcCC3);
    loCont = gcc_cont;
    if (loCont.hasOwnProperty("Email")) {lcCCEmail = loCont.Email;lcCC_ID = loCont.Cont_ID;} else {lcCCEmail = lcCC3;lcCC_ID = '';}
    
    Make_ContLookup("CC",lcCC_ID);
}
// -------------------------------------------------------------- //
function getContactFromEmail(email) 
{
    dataWH.Contacts.dataStore.data.each(function(cont, index)
    { 
        //console.log(cont)
        if (cont.Email == email)
        {
            gcc_cont = cont;
            return cont;
        }                        
    });

    return {}
}
// -------------------------------------------------------------- //
function fullEmail(oContact)
{
    out = oContact.Email;
    if (out.indexOf("<") > -1) {return out;}
    
    if (oContact.Class == 'Person')
    {
        out = oContact.First_Name + ' ' + oContact.Last_Name + ' <' + oContact.Email + '>';
        return out;
    }
    else
    {
        out = oContact.Company + ' <' + oContact.Email + '>';
        return out;    
    }

}
// -------------------------------------------------------------- //
function openWindowURL(inURL,wp,hp)
{
    ls = 10;        
    winFeatures = "toolbar=0,menubar=0,titlebar=0,top=10,left=" + ls + ",width=" + (ww*wp) + ",height=" + (hh*hp) + '';
    winSample = window.open(inURL, "winPage", winFeatures);
}
// -------------------------------------------------------------- //
function SampleList(inm3u)
{
    trurl = 'https://media.trackstage.io/sampletrack.html?id=' + seq() + seq() +seq() + '&ur=' + encodeURIComponent(inm3u);
    ls = ww - (320) - 30;        
    winFeatures = "toolbar=0,menubar=0,titlebar=0,top=250,left=" + ls + ",width=" + 320 + ",height=" + 60 + '';
    winSample = window.open(trurl, "winSample", winFeatures);
}
// -------------------------------------------------------------- //
async function SamplePlayer()
{
	// 1. collect the checked tracks and ensure they have share links
	//debugger;
    tks = catalogTagged();   
	theseTracks = [];
    if (tks.length == 0)
    {
        webix.message({type: "error", text: "<b>Error:</b>&nbsp;&nbsp;No tracks selected.", expire: 10000});
        return '';
    }
    else
    {
        tct = 0;
        for (var i=0;i<tks.length;i++) {
            ttrk = dataWH.Catalog.dataStore.getItem(tks[i].Track_ID);
            if (ttrk.Perm_Share_Link.length > 0 && ttrk.Perm_Share_Active == true)
            {
                theseTracks.push(ttrk.Track_ID);
				tct += 1;
            }
            else
            {
                ttrk.chkCatalog = 'off';
                $$("catalogTable").refresh(i);
                lcOops = "<b>Info:</b>&nbsp;&nbsp;You must first cache <b>" + ttrk.File_Name + ttrk.File_Ext + "</b>&nbsp; to the cloud using <b>Process Tracks</b> before it can be played. It has been removed from the list."
                webix.message({type: "error", text: lcOops, expire: 15000});                
            }            
        }                 
    }	
	
	if (tct > 0)
	{
		// 2. axios post data including the selected tracks to server (put in session there)
		pkge = {'Tracks': theseTracks, 'Count': tct};
		trurl = gcBaseURL + 'player_preview/?mde=prep&seq='+seq();
		response = await axios.post(trurl, pkge)
		gRes = response;
		resData = response.data; 
		if (resData.status == 'ok')
		{
			// 3. open a new browser window that generates the player preview page
			trurl = gcBaseURL + 'player_preview/?mde=play&seq='+seq();
			winSample = window.open(trurl, "winSample");
		}
		else
		{
			webix.message({type: "error", text: 'An error occuring processing your request', expire: 7000}); 
		}
	}
}
// -------------------------------------------------------------- //
function SampleTrack()
{

    if (gTauri == false)
    {	
	bw = getBrowser();	
	if (bw.indexOf('Safari') > -1)
	{
	    vh = 130;
	}
	else
	{
	    vh = 110;
	}
	//vw = ww*.54;
	//vw = 750;
	vw = 900;

	vl = (screen.width/2)-(vw/2);
	vt = (screen.height/2)-(vh/2);
	trurl = gcBaseURL + 'static/sampletrack.html?id=' + seq() + seq() +seq() + '&title=' + encodeURIComponent(gCurrTrack.TIT2_TrackName) + '&ur=' + encodeURIComponent(gcBaseURL + gCurrTrack.Perm_Share_Link + '/') + '&seq=' + seq();        
	winFeatures = "toolbar=no,menubar=no,titlebar=no,top=" + vt + ",left=" + vl + ",width=" + vw + ",height=" + vh + '';
	winSample = window.open(trurl, "winSample", winFeatures);
	jsonData = {'Artist': gUser_Profile.Artist, 'Track': gCurrTrack};
	localStorage.setItem('sampletrackdata',JSON.stringify(jsonData)) 
    }
    else
    {

	trurl = gcBaseURL + 'static/playertrack.html?id=' + seq() + seq() +seq() + '&ar=' + gcArti_ID +  '&title=' + encodeURIComponent(gCurrTrack.TIT2_TrackName) + '&ur=' + encodeURIComponent(gcBaseURL + gCurrTrack.Perm_Share_Link + '/') + '&seq=' + seq();        
	jsonData = {'Artist': gUser_Profile.Artist, 'Track': gCurrTrack};
	localStorage.setItem('sampletrackdata',JSON.stringify(jsonData)) 
	pkge = {"audioTrack": trurl, "TrackJSON": jsonData, "stack": "SampleTrack"};
	amsg = genAblyMsg("catalog-play-track", inTarget="CMD", inStage="broadcast", inID="",inPrev_ID="", inPkge=pkge, autoSend=true)	
	
    }      
}
// -------------------------------------------------------------- //
function catalogTrackInfoHead()
{

    if (gcAcctLevel == 'Basic')
    {
	$$('TIT2_TrackName_Title').setHTML("Track Info");
	return;
    }
    
    if (gCurrTrack.Perm_Share_Active == true && gCurrTrack.Perm_Share_Link.length > 0)
    {
	if (gCurrTrack.Perm_Share_Outdated == 'Y')
	{
	    $$('TIT2_TrackName_Title').setHTML("Track Info" + '<span title="Cached track is OUT OF DATE.  You need to re-cache this track." onclick="SampleTrack();" style="cursor:pointer;">' + cloud_outdated + '</span>');    
	}
	else
	{
	    $$('TIT2_TrackName_Title').setHTML("Track Info" + '<span title="Track is cached to the cloud." onclick="SampleTrack();" style="cursor:pointer;">' + cloud_success + '</span>');	
	}
    }
    else
    {
	 $$('TIT2_TrackName_Title').setHTML("Track Info" + cloud_warning);
    }
    
    setTimeout("$$('TIT2_TrackName_Title').refresh();",350);

}

// -------------------------------------------------------------- //
function templatePitchTrackList()
{
    out = "<br/><table style='border-collapse:collapse; padding:0px;'><tr height='33px' style='padding:0px;'><td style='padding: 0px;background-image: linear-gradient(to right, #682c94,#e628f2);border-top-right-radius:8px; border-top-left-radius:8px;'></td></tr><tr style='padding:0px;'><td style='padding:0px;'><table class='emlTblTracks' style='border-collapse:collapse; width:100%; padding:0px; border-right:3px solid #e628f2;border-left:3px solid #682c94;'>";
    
    tks = catalogTagged();    
    if (tks.length == 0)
    {
        webix.message({type: "error", text: "<b>Error:</b>&nbsp;&nbsp;No tracks selected.", expire: 10000});
        return '';
    }
    else
    {
        for (ndx =0; ndx < tks.length; ndx++)
        {
            tt = tks[ndx]; 
            tt.Tag_Done = 0;
        }  
        
        tct = 0;
        for (var i=0;i<tks.length;i++) {
            ttrk = dataWH.Catalog.dataStore.getItem(tks[i].Track_ID);
            if (ttrk.Perm_Share_Link.length > 0 && ttrk.Perm_Share_Active == true)
            {
                out = out + addTrackLine(ttrk);
            }
            else
            {
                ttrk.chkCatalog = 'off';
                $$("catalogTable").refresh(i);
                lcOops = "<b>Info:</b>&nbsp;&nbsp;You must first cache <b>" + ttrk.File_Name + ttrk.File_Ext + "</b>&nbsp; to the cloud using <b>Process Tracks</b> before it can be pitched. It has been removed from the list."
                webix.message({type: "error", text: lcOops, expire: 15000});                
            }
            tct += 1;
        }                 
    }
    
    out = out + '</table></td></tr><tr><td colspan="3" style="padding:0px;"><img src="##baseurl##static/assets/images/PoweredByTrackStage.jpg" width="650px;" style="padding:0px;border-bottom-left-radius:8px;border-bottom-right-radius:8px;"></td></tr></table>';
    out = out.replaceAll('##baseurl##',gcBaseURL);
    return out;
}
// -------------------------------------------------------------- //
function templateTrackList()
{
    out = "<br/><table style='border-collapse:collapse; padding:0px;'><tr style='padding:0px;'><td style='padding: 0px;background-image: linear-gradient(to right, #682c94,#e628f2);border-top-right-radius:8px; border-top-left-radius:8px;><img src='##baseurl##static/assets/images/PoweredByTrackStageHeader.jpg' width='650px;' style='padding:0px; border:0px; border-top-left-radius:8px;border-top-right-radius:8px;margin-bottom:0px;'></td></tr><tr style='padding:0px;'><td style='padding:0px;'><table class='emlTblTracks' style='border-collapse:collapse; width:100%; padding:0px; border-right:3px solid #e628f2;border-left:3px solid #682c94;'>";
    tks = catalogTagged();    
    if (tks.length == 0)
    {
        webix.message({type: "error", text: "<b>Error:</b>&nbsp;&nbsp;No tracks selected.", expire: 10000});
        return '';
    }
    else
    {
        for (ndx =0; ndx < tks.length; ndx++)
        {
            tt = tks[ndx]; 
            tt.Tag_Done = 0;
        }  
        
        tct = 0;
        for (var i=0;i<tks.length;i++) {
            ttrk = dataWH.Catalog.dataStore.getItem(tks[i].Track_ID);
            if (ttrk.Perm_Share_Link.length > 0 && ttrk.Perm_Share_Active == true)
            {
                out = out + addTrackLine(ttrk);
            }
            else
            {
                ttrk.chkCatalog = 'off';
                $$("catalogTable").refresh(i);
                lcOops = "<b>Info:</b>&nbsp;&nbsp;You must first cache <b>" + ttrk.File_Name + ttrk.File_Ext + "</b>&nbsp; to the cloud using <b>Process Tracks </b> before it can be sent. It has been removed from the list."
                webix.message({type: "error", text: lcOops, expire: 15000});                
            }
            tct += 1;
        }                 
    }
    
    out = out + '</table></td></tr><tr height="114px;"><td colspan="3" style="padding: 0px;background-image: linear-gradient(to right, #682c94,#e628f2);border-bottom-right-radius:8px; border-bottom-left-radius:8px;"><div style="height:40px;"><img src="##baseurl##static/assets/images/PoweredByTrackStage.jpg" width="650px;" style="padding:0px;border-bottom-left-radius:8px;border-bottom-right-radius:8px;"></div></td></tr></table>';
    out = out.replaceAll('##baseurl##',gcBaseURL);
    return out;
}
// -------------------------------------------------------------- //
function addTrackLine(inTrk)
{

    tImg = genTrackImgLink(inTrk);
    tImg = tImg.replaceAll(":230px;",":82px;");
    tImg = tImg.replaceAll("/static/assets/images/no_image.png",gcBaseURL + "static/assets/images/TrackStage_Grey.jpg");
    
    //<td class='emlCellTrackPlay' width="40px;" style="border-bottom:1px solid #cccccc; padding-left:10px;"><a data-pm-no-track="yes" href="##playlink##"><img src="https://www.trackstage.io/static/assets/images/PurplePlay.jpg" width="30px"></a></td>
    
    tmpl = `
    <tr style='padding:0px;'>
        <td class='emlCellTrackPlay' width="40px;" style="border-bottom:1px solid #cccccc; padding-left:10px;"><a data-pm-no-track="yes" style="font-weight:600;font-size:13px;text-decoration:none;color:purple;" href="##playlink##">Play</a></td>
        <td class='emlCellTrackImage' width="80px;" style="border-bottom:1px solid #cccccc;">##trackimage##</td>
        <td class='emlCellTrackName' style="font-weight:600; font-size:16px!important;padding:20px;border-bottom:1px solid #cccccc;">##trackname##<br/>
        <span class='emlCellTrackGenre' style="font-weight:200; font-family:Poppins,Robato, sans-serif;color: #666666!important; font-size:14px!important;">##artistname##<br/>
        <span class='emlCellTrackGenre' style="font-weight:200; font-family:Poppins,Robato, sans-serif;color: #A6A6A6!important; font-size:12px!important;font-style:italic">##genre##</span></td>
    </tr>
    `;    
    
    tmplX = tmpl.replaceAll('##trackimage##',tImg);
    tmplX = tmplX.replaceAll('##trackname##',inTrk.TIT2_TrackName);
    tmplX = tmplX.replaceAll('##artistname##',inTrk.TPE1_Artist);
    tmplX = tmplX.replaceAll('##genre##',inTrk.TCON_Genre);
    tmplX = tmplX.replaceAll('##baseurl##',gcBaseURL);
    tmplX = tmplX.replaceAll('##playlink##',gcBaseURL + '!~eml~!' + inTrk.Perm_Share_Link + '/');
    
    return tmplX;
}
// -------------------------------------------------------------- //
function targetsNew()
{
    wzSelected = [];
    Make_ContLookup("targetsNew",{row: gXID});
}
// -------------------------------------------------------------- //
function targetsNew2()
{
    wzSelected = [];
    Make_New_Target("targetsNew",{row: gXID});
}
// ------------------------------------------------------------ //
function targetNewSubmit(inObj,forTrackLicense=false)
{
    if (forTrackLicense == false)
    {
	title = 'Add NEW Target';
	addMessage = 'Add a Target record for:&nbsp;&nbsp;<br/><br/><b>' + inObj.Target.Target_Name + '</b>?<br/>';
	gtObj = inObj;
	gtObj.forTrackLicense = false;
	ConfirmIt(title=title, description=addMessage, txtYes='Ok', txtNo='Cancel', fncForYes='targetNewSubmitGo', 
	keyID=undefined, cancel_Msg=undefined, boxType='new');    
    }
    else
    {
	trk = {}
	$$("catalogTable").data.each(function(obj)
	{ 
	    if (obj.chkCatalog == 'on') {trk = obj;}
	});    	
	title = 'Add Track License'; 
	addMessage = 'License the Track <br/><br/><span style="color:purple;font-weight:Bold;">' + trk.TIT2_TrackName + '</span><br/><br/>&nbsp;&nbsp;to:&nbsp;&nbsp;<br/><br/><b>' + inObj.Target.Target_Name + '</b>?<br/>';
	gtObj = inObj;
	gtObj.forTrackLicense = true;
	gtObj.Track = trk;
	ConfirmIt(title=title, description=addMessage, txtYes='Ok', txtNo='Cancel', fncForYes='targetNewSubmitGo', 
	keyID=undefined, cancel_Msg=undefined, boxType='new');      
    }
    
}
gtObj = '';gtrec = '';
// ------------------------------------------------------------ //
async function targetNewSubmitGo()
{

    pitchesFstCheck = true;
    url = '/data_targets/?mde=newtarget&seq=' + seq();
    autoPitch = (wzSelected.length > 0) ? true : false;
    oTrack = {};
    
    if (gtObj.hasOwnProperty('forTrackLicense') == false) {gtObj.forTrackLicense = false;}
    if (gtObj.hasOwnProperty('Track') == true) {oTrack = gtObj.Track;}
    
    pkge = {'New_Target': gtObj, 'id': gXID, 'wzSelected': wzSelected, 'autoPitch': autoPitch, 'forTrackLicense': gtObj.forTrackLicense, 'Track': oTrack, 'Manual_License': gManualLicense};
    response = await axios.post(url, pkge)
    gRes = response;
    resData = response.data; 
    
    addedTarget = true; addedProd = true;addedPitch = false;addedPitchTrack = false;
    if (autoPitch == true || gtObj.forTrackLicense == true)
    {
        addedTarget = resData.addedTarget;
        addedProd = resData.addedProd;
	addedPitch = resData.addedPitch;
	addedPitchTrack = resData.addedPitchTrack;
    }
    
    if (resData.newCont != null)
    {dataWH.Contacts.dataStore.add(resData.newCont);}
    
    gUser_Profile.Artist.Pitch_Email_Blurb = resData.Pitch_Email_Blurb;
    
    if (resData.status == 'error')
    {
        webix.message({type: "error", text: "<b>Error:</b>&nbsp;&nbsp;"+resData.Message, expire: 10000});
    }
    else
    {
	if (gtObj.forTrackLicense == false)
	{
	    if (addedTarget == true)
		{dataWH.Targets.dataStore.add(resData.newObj);}
	    trec = resData.newObj.Target_ID;         
	    targetsCurrID = trec;
	    gCurrTarget['Target'] = dataWH.Targets.dataStore.getItem(targetsCurrID);
	    if (addedProd == true)
		{dataWH.Productions.dataStore.add(resData.newProdObj);}
	    setProductions();	
	    $$("targetsTable").select(gCurrTarget.Target.id);     
	    gNewTarget = {};
	    setProductions();
	    $$("targetsEditForm").parse(gCurrTarget);
	    setTimeout("targetsSetVisibility();",300);  
	    setTimeout("gotoTargetsTab('targetsInfo');",600);
	    setTimeout('$$("Target.Target_Type").focus();',1450);
    
	    setTimeout("webix.UIManager.setFocus($$('Target.Target_Company'));",1200);
	    webix.message({type: "success", text: "<b>Success:</b>&nbsp;&nbsp;"+resData.Message, expire: 3000});
	    
	    if (autoPitch == true)
	    {
		// now the target/prod are in place ... bring up  the pitch form
		gCurrTargetProd.TargetProd = targetsProductions[0].Production; 
		targetsCreatePitch(resData,'')
		setTimeout('wzQikTags();',1300);
	    }
	}
	else
	{
	    if (addedTarget == true)
		{dataWH.Targets.dataStore.add(resData.newObj);}

	    if (addedProd == true)
		{dataWH.Productions.dataStore.add(resData.newProdObj);}
		
	    if (addedPitch == true)
		{dataWH.Pitches.dataStore.add(resData.newPitchObj);}		
		
	    if (addedPitchTrack == true)
		{dataWH.Pitch_Tracks.dataStore.add(resData.newPitchTrackObj);}			
		
	    webix.message({type: "success", text: "<b>Success:</b>&nbsp;&nbsp;"+resData.Message, expire: 3000});
	    gotoModule('Licenses');
	    setLicensedTracks();
	    setTimeout(`
		gtrec = resData.newPitchTrackObj.PT_ID;         
		licensesCurrID = gtrec; 
		gCurrLicense['License'] = dataWH.Pitch_Tracks.dataStore.getItem(licensesCurrID);
		refPitch = dataWH.Pitches.dataStore.getItem(gCurrLicense['License'].Pitch_ID);
		refPitchTargetProd = findPitchRef(refPitch.Prod_ID,'prod');
		refPitchTarget = findPitchRef(refPitchTargetProd.TargetProd.Target_ID,'target');		
		$$("licensesTable").select(licensesCurrID);		
	    `,800);
	    
	    setTimeout('$$("licensesTable").select(gCurrLicense.License.id);',1200);
	    setTimeout("gotoLicensesTab('licensesInfo');",1500);
	    
	    setTimeout('$$("licensesEditForm").clearValidation();$$("licensesEditForm").clear();',1600);
	    setTimeout('$$("licensesEditForm").parse(gCurrLicense);',1700);
	    setTimeout(`
		$$("License.Pitch.Target_Name").setValue(gCurrLicense.License.Target.Target_Name);
		$$("License.Pitch.Prod_Title").setValue(gCurrLicense.License.Production.Prod_Title);
	    `,1900);
	    setTimeout('setLicenseDetails();',1800);
		
		
	    $$("catalogTable").data.each(function(obj)
	    { 
		if (obj.chkCatalog == 'on') 
		{
		    obj.chkCatalog = 'off';
		    $$("catalogTable").refresh(obj.id);
		}
	    }); 		
	}
    }     
}
// ------------------------------------------------------------ //
function wzQikTags()
{
    dtable = $$("pitchWZTrackSelectTable"); 

    dtable.eachRow(function(row){ 
        const record = dtable.getItem(row);
        record.wzIs_Checked = 'off';            
        this.updateItem(row, record);
    });    

    dtable.data.each(function(obj)
    { 
        const record = dtable.getItem(obj.id);
        fnd = false;
        for (ndx =0; ndx < wzSelected.length; ndx++)
        {
            tt = wzSelected[ndx]; 
            if (tt.id == record.id)
            {
                fnd = true
                //console.log('found');
                break;
            }
        }
        
        if (fnd == true)
        {
            record.wzIs_Checked = 'on';
            this.updateItem(obj.id, record);
        }  
    }); 
    
    setTimeout(`
        $$("wzPitch_One").hide();
        $$("wzPitch_Two").hide();
        $$("wzPitch_Three").config.header = webix.template('Prepare your Pitch');
        $$("wzPitch_Three").refresh();
        $$("wzPitch_Three").expand();
        $$("createNewPitch").parse(gNewPitch);
        `,500);
        
        
        wzShowSelected('wzPitchTrackNames');
	if (gCurrTarget.Target.Target_Email.length > 0)
	{
	    setTimeout(`
		$$("pitchWZCategorySelect").getList().getItem('Email').disabled = false;
		$$("pitchWZCategorySelect").getList().refresh();
	    `,1400);
	} 
	else
	{
	    webix.message({type: "debug", text: "<b>Email Option Disabled:</b><br/>This Target has no email address: sending via Email requires an Email Address..", expire: 10000});                                
	}	
        
}
// ------------------------------------------------------------ //
function licensesChecked()
{
    var checked = [];
    
    $$("licensesTable").data.each(function(obj)
    {
        if (obj.chkLicense && obj.chkLicense == 'on') 
        {
            obj.Tag_Done = 0;
            checked.push(webix.copy(obj));
        }
    });    

    return checked;
}
// ------------------------------------------------------------ //
function targetsChecked()
{
    var checked = [];
    
    $$("targetsTable").data.each(function(obj)
    {
        if (obj.chkTarget && obj.chkTarget == 'on') 
        {
            obj.Tag_Done = 0;
            checked.push(webix.copy(obj));
        }
    });    

    return checked;
}
// ------------------------------------------------------------ //
function targetsDelete()
{
    marks = targetsChecked();
    //console.log('marks = ', marks);
    if (marks.length == 0)
    {
        webix.message({type: "debug", text: "Please select the Targets you wish to delete, first.", expire: 5000});
    } 
    else
    { 
        gMarks = marks;
        title = 'Delete Target(s)';
        delMessage = `
        
        Are you sure you want to REMOVE the selected <b>##cnt##</b>&nbsp;Targets?
        `;
        
        if (marks.length == 1) 
        {
            oCo = dataWH.Targets.dataStore.getItem(marks[0].id);
	    bwarn = `
	    <br/>Removing a Target will <b>permanently delete</b> ALL historical info, including all opportunities, pitches created for that Target.<br/> 
	    `;
            title = 'Remove Target';
            delMessage = 'Are you sure you want to DELETE this Target? <b><br/><br/>' + oCo.Target_Name + '</b><br/>' + bwarn;
        }
        delMessage = delMessage.replace('##cnt##',marks.length+'');
        
        ConfirmIt(title=title, description=delMessage, txtYes='Ok', txtNo='Cancel', fncForYes='targetsDeleteGo', 
        keyID=undefined, cancel_Msg=undefined, boxType='new');    
    }
}
// ------------------------------------------------------------ //
async function targetsDeleteGo()
{
    webix.message({type: "success", text: "<b>OK:</b>&nbsp;Processing request", expire: 500});
    gForm_Data = {'Targets': gMarks}
    url = '/data_targets/?mde=del_targets&seq='+seq();
    response = await axios.post(url, gForm_Data)
    gRes = response;
    resData = response.data;
    if (resData.status == 'error')
    {
      webix.message({type: "error", text: resData.message, expire: 10000});
    }
    else
    {
        if (resData.status == 'success')
        {
            objList = resData.delsList;            
            webix.message({type: "success", text: resData.message, expire: 3000});
            for (ndx =0; ndx < objList.length; ndx++)
            {
                tObj = objList[ndx];
                dataWH.Targets.dataStore.remove(tObj.id);               
            }
        }        
        else
            {webix.message({type: "error", text: resData.message, expire: 10000});}
                    
        setTimeout("targetsRefresh();",2500);
    } 
}

// ------------------------------------------------------------ //
async function saveProductionItem()
{
    
    isValidated = $$("productionForm").validate();
    if (isValidated == false) 
    {   
        webix.message({type: "error", text: "<b>Error:</b>&nbsp;Please correct any errors and retry", expire: 6000});
        return;
    }
    else
    {   
        productions_list = $$("productionsList");
        var production_form = $$("productionForm");
        var production_data = production_form.getValues();
        gForm_DataT = production_data.Production;
	gForm_DataT.Sample_Links = '';
	if (findBrief != null && findBrief.hasOwnProperty('Brief_Key') == true)
	{
	    gForm_DataT.Sample_Links = findBrief.Brief_Sample_Links;
	}
	
        if (gForm_DataT.Prod_ID) {tcid = gForm_DataT.Prod_ID;} else {tcid = gXID;}
        gForm_DataT.Target_ID = targetsCurrID.row; 
        gForm_DataT.Prod_ID = tcid;
        
        if (targetsProdCurrID == '' && tcid != gXID)
        {
            webix.message({type: "error", text: "<b>Error:</b>&nbsp;No Production record is currently selected", expire: 7000});
            return;    
        }        
        
        $$("productionForm").clear();
	
	$$("Production.Prod_Sample_Links").setHTML('');
	
	dd = gForm_DataT.Prod_Deadline;
	dd2 = moment(dd).utcOffset(0, true).format();
	dd2 = dd2.substring(0,dd2.length-1);
	dd2 = dd2.replace("T"," ");
	gForm_DataT.Prod_Deadline = dd2;
	
        webix.message({type: "success", text: "<b>OK:</b>&nbsp;Ready to save to server", expire: 500});
        url = '/data_productions/?mde=prod_save&cid='+tcid+'&category='+targetsCurrTab+'&seq='+seq();
        response = await axios.post(url, gForm_DataT)
        gRes = response;

        resData = response.data;
        if (resData.status == 'error')
        {
          webix.message({type: "error", text: resData.Message, expire: 4000});
        }
        else
        {
            if (resData.status == 'success')
            {
                newObj = {"Production": resData.newObj};
                
                webix.message({type: "success", text: resData.Message, expire: 3000});
                if (gForm_DataT.id)
                {
                    productions_list.updateItem(production_data.id, newObj);
                    dataWH.Productions.dataStore.updateItem(resData.newObj.id, resData.newObj);                      
                } 
                else 
                {
                    productions_list.add(newObj); 
                    dataWH.Productions.dataStore.add(resData.newObj);
                } 
            }
            else	    
            {
                webix.message({type: "error", text: resData.Message, expire: 3200});
            } 
        }
    }
    
    setProductions() // re-establish the array...
}
// ------------------------------------------------------------ //
function clearProductionItem()
{
    //console.log("clearProductionItem():");
    $$("productionForm").clear();
    $$("Production.Prod_Sample_Links").setHTML('');
    pD = false;
    $$("Production.Prod_Title").define("disabled",pD);
    $$("Production.Prod_Status").define("disabled",pD);
    $$("Production.Prod_Desc").define("disabled",pD);
    $$("Production.Prod_Genre").define("disabled",pD);
    $$("Production.Prod_Length").define("disabled",pD);
    $$("Production.Prod_Ind_Seg").define("disabled",pD);
    $$("Production.Prod_Stage").define("disabled",pD);
    $$("Production.Prod_Ref_Num").define("disabled",pD);
    $$("Production.Prod_Deadline").define("disabled",pD);
    $$("Production.Prod_Project_Name").define("disabled",pD);
    $$("Production.Prod_Company").define("disabled",pD);
    $$("Production.Prod_IMDb").define("disabled",pD);
    $$("Production.Prod_Notes").define("disabled",pD);    
}
// ------------------------------------------------------------ //
function deleteProductionItem()
{
    if (tCurrTargetProd.Production.Prod_Quick_Pitch == true) 
    {
	webix.message({type: "error", text: "The Quick Pitch is a default record and cannot be deleted", expire: 8000});
	return;
    }

    ConfirmIt(title='Delete Production', 
        description='Click Ok to DELETE this Opportunity record?', 
        txtYes='Ok', txtNo='Cancel', fncForYes='goDeleteProductionItem', 
        fncForNo='cancelMsg', keyID=undefined, cancel_Msg='Request cancelled.');  
}
// ------------------------------------------------------------ //
async function goDeleteProductionItem(keyID)
{

    var target_list = $$("productionsList");
    var target_id = target_list.getSelectedId();
    gForm_DataT = $$("productionForm").getValues();

        if (target_id) 
        {
            tcid = gForm_DataT.Production.Prod_ID;

            webix.message({type: "success", text: "<b>OK:</b>&nbsp;Delete request sent to server", expire: 500});            
            url = '/data_productions/?mde=prod_del&pid='+tcid+'&seq='+seq();
            response = await axios.post(url, gForm_DataT)
            gRes = response;
            resData = response.data;
            if (resData.status == 'error')
            {
                webix.message({type: "error", text: resData.message, expire: 10000});
            }
            else
            {
                if (resData.status == 'success')
                {                  
                    webix.message({type: "success", text: resData.message, expire: 3000});
                    target_list.remove(target_id)
                    dataWH.Productions.dataStore.remove(tcid);		    

                    $$("productionForm").clear();
                    $$("productionsList").unselectAll();
                    setTimeout('$$("productionsList").clearSelection();',1500);
                    $$("productionForm").clearValidation();
		    $$("Production.Prod_Sample_Links").setHTML('');

                    setProductions() // re-establish the array...
                }
                else
                    {webix.message({type: "error", text: resData.message, expire: 10000});}
            }                                              
        }
}

gTracksPitchable = [];gTargetProds = [];
// ------------------------------------------------------------ //
function wzPitchRefresh()
{
    //$$("pitchWZTargetTitle").refresh();
    
    
    $$("pitchWZTargetDescription").define("template",gCurrTargetProd.TargetProd.Prod_Desc);
    $$("pitchWZTargetDescription").refresh();    
        
    
    $$("pitchWZTargetGenres").refresh();
    $$("pitchWZTargetDeadline").refresh();
    $$("pitchWZTargetLength").refresh();
    $$("pitchWZTargetType").refresh();
    $$("pitchWZContactNotes").refresh();
    $$("pitchWZProjectName").refresh();
    $$("pitchWZTargetContactName").refresh();
    $$("pitchWZTargetRefNum").refresh();
    $$("pitchWZContactNotes").refresh();
    $$("pitchWZTargetLength").refresh();
    
    $$("pitchWZTargetDescription").setHTML("" + gCurrTargetProd.TargetProd.Prod_Desc);
    
}
// ------------------------------------------------------------ //
async function targetsPitchPull(inMode)
{
    if (inMode == 'targets' && targetsCurrID == '')
    {
        webix.message({type: "error", text: "<b>Error:</b>&nbsp;You must select a Target record first", expire: 7000});
        return;
    }
    if (inMode == 'catalog') 
        {url = '/data_targets/?mde=getpitchform&tid=' + gtObj.Target.Target_ID + '&seq=' + seq();pkge = {'AutoPitch': true, 'NewTarget': gtObj, 'Cont_ID': gtObj.Target.Cont_ID};}
    else
        {url = '/data_targets/?mde=getpitchform&tid=' + gCurrTarget.Target.Target_ID + '&seq=' + seq();pkge = {'AutoPitch': false, 'NewTarget': {}};}
        
    
    await axios.post(url,pkge).then(response => 
    {
        //console.log("targetsPitchPull got back", response);
        webix.message({type: "success", text: "<b>Success</b><br/> " + response.data.Message, expire: 1000});
        
        targetsCreatePitch(response.data,inMode=inMode);       
    },
    (error) => 
    { 
	if (error.response.status == 502)
	{
	    webix_message({type: "error", text: "<b>Error:</b>&nbsp;TrackStage is currently offline.  Please try back in a few minutes.", expire: 10000},1);
	    return;	
	}    
    
        //console.log("Error:", error);
        webix.message({type: "error", text: "<b>Error</b><br/> " + response.data.Message, expire: 3000});
    }); 
}
// ------------------------------------------------------------ //
gCurrTargetProd = [];
wzPitchProdCurrID = ''; isQuick = false;
    
function targetsCreatePitch(resp,inMode)
{
    wzPitchProdCurrID = '';
    $$('catalogSearchFld').setValue('');
    catalogFilter('');
    
    if (gCurrTarget.Target.Target_Status != 'Active' && gCurrTarget.Target.Target_Status != 'Pending')
    {
        webix.message({type: "error", text: "<b>Error:</b>&nbsp;You can only pitch to Targets whose status is <b>Active</b> or <b>Pending</b>.", expire: 7000});
        return;
    }  

    gTargetProds = targetProdsAvail();
    gTracksPitchable = catalogGetPitchable();
    gCurrTargetProd['TargetProd'] = gTargetProds[0];  
    if (gCurrTargetProd['TargetProd'].Prod_Quick_Pitch == false)
    {
        for (ndx =0; ndx < gTargetProds.length; ndx++)
        {
            pItem = gTargetProds[ndx];	if (pItem.Prod_Quick_Pitch == true)
	    {
		gCurrTargetProd['TargetProd'] = pItem;
		break;
	    }
	}
    }
    
    gNewPitch = {};gNP = {};
    gNP.Target_ID = gCurrTarget.Target.Target_ID;
    gNP.Prod_ID = gCurrTargetProd.TargetProd.Prod_ID;
    gNP.Target_Name = gCurrTarget.Target.Target_Name;
    gNP.Pitch_Project = gCurrTargetProd.TargetProd.Prod_Title;
    gNP.Pitch_Deadline = gCurrTargetProd.TargetProd.Prod_Deadline;
    gNewPitch.NewPitch = gNP;
    
    varTargetPitch = {view: "template", template: "Error pulling form contents"};
    vpt = resp.Create_Pitch_Form;
    
    try {varTargetPitch = eval(vpt);} catch(err) {a=1;}
    

    title = (inMode == 'targets') ? 'Create Targeted Pitch' : 'Create Quick Pitch';
    isQuick = (inMode == 'targets') ? false : true;
    
    if (inMode != 'targets') {setTimeout('webix.UIManager.setFocus($$("pitchWZCategorySelect"));',2400);}
        
    genPitchWindow(title,hh*0.9,ww*0.8,varTargetPitch,makeSquare=false,isModal=false,noPct=true,scrollBar=false);
    
    setTimeout(`
        $$("pitchWZOpportunities").select(tCurrTargetProd.Production.id);
        wzPitchProdCurrID = tCurrTargetProd.Production.id;                              
        gCurrTargetProd['TargetProd'] = dataWH.Productions.dataStore.getItem(wzPitchProdCurrID);                                 
        $$("wzPitchForm").parse(gCurrTargetProd);
        setTimeout("wzPitchRefresh();",200);
        wzPitchSuggestTracks();           
    `,1100)
    
    setTimeout(`
        wzPitchSuggestTracks();
        thh = $('div[view_id="pitchWZMatchButtons"]').height();
        $('div[view_id="pitchWZMatchButtons"]').height(thh-6);
        $('div[view_id="pitchWZMatchButtons"]').css('border-bottom-width','1px');        
    `,400);
}
// ------------------------------------------------------------ //
function suggestToTop(popupWindowID,suggestListID)
{
    //console.log('suggestToTop():');
    zt = parseInt($('div[view_id="' + popupWindowID + '"]').css('z-index')) + 1;
    //console.log('suggestToTop(): next zt = ', zt);
    $('div[view_id="' + suggestListID + '"]').css('z-index',zt+'')

}
// ------------------------------------------------------------ //
function wzRun_LengthRange(prod_len)
{
    out = '';
    if (prod_len == '<15') {return "< 00:15";}
    if (prod_len == '16-30') {return "00:16-00:30";}
    if (prod_len == '31-60') {return "00:31-01:00";}
    if (prod_len == '61-90') {return "01:01-01:30";}
    if (prod_len == '91-120') {return "01:31-02:00";}
    if (prod_len == '121-240') {return "02:01-04:00";}    
    if (prod_len == '> 240') {return "> 04:00";} 
    return out;
}
// ------------------------------------------------------------ //
function wzCompareSeconds(track_len, prod_len)
{

    //{ id: "", value: "" },
    //{ id: "<15", value: "< 00:15" },
    //{ id: "16-30", value: "00:16-00:30" },
    //{ id: "31-60", value: "00:31-01:00" },
    //{ id: "61-90", value: "01:01-01:30" },
    //{ id: "91-120", value: "01:31-02:00" },
    //{ id: "121-180", value: "02:01-03:00" },    
    //{ id: ">181", value: "> 03:01" },
    
    res = false;
    if (prod_len == '<15' && track_len < 15) {return true;}
    if (prod_len == '16-30' && (track_len > 15 && track_len <= 30)) {return true;}
    if (prod_len == '31-60' && (track_len > 30 && track_len <= 60)) {return true;}
    if (prod_len == '61-90' && (track_len > 60 && track_len <= 90)) {return true;}
    if (prod_len == '91-120' && (track_len > 90 && track_len <= 120)) {return true;}
    if (prod_len == '121-180' && (track_len > 120 && track_len <= 180)) {return true;}    
    if (prod_len == '>180' && track_len > 180) {return true;}
    
    return res;
}
// ------------------------------------------------------------ //
function wzCrossMatchList(trackfld,prodfld,delims=[','], trackDelim=',')
{
    res = false;
    tf = trackfld.toLowerCase().trim();
    pf = prodfld.toLowerCase().trim();
    tf = tf.replaceAll(',  ',',').replaceAll(', ',',')
    pf = pf.replaceAll(',  ',',').replaceAll(', ',',')
    
    for (ddx =0; ddx < delims.length; ddx++)
    {   
        delim = delims[ddx];
        lstT = tf.split(trackDelim);
        lstP = pf.split(delim);    
        //if (delim != ',' && trackfld.length > 0 && prodfld.length > 0){debugger;}
        for (ndx =0; ndx < lstP.length; ndx++)
        {
            pItem = lstP[ndx] + delim;
            for (ndx2 =0; ndx2 < lstT.length; ndx2++)
            {
                tItem = lstT[ndx2];
                chk = (tItem + delim);
                if (pItem.indexOf(chk) > -1) {return true;}
            } 
            ndx2 = 0;
        }
    }
    if (res == true) {debugger;}
    return res;
}
// ------------------------------------------------------------ //
function wzPitchMatch(record)
{
    res = 0;
    // get flags
    wzG = $$("wzPitchGenres").getValue();
    wzK = $$("wzPitchKeywords").getValue();
    wzS = $$("wzPitchSoundsLike").getValue();
    wzC = $$("wzPitchCueType").getValue();
    wzL = $$("wzPitchLength").getValue();
    tAny_All = $$("wzAny_Or_All").getValue();
    //tAny_All = 'any';
    
    wzG_Match = false;wzK_Match = false;wzS_Match = false;wzC_Match = false;wzL_Match = false;
    //debugger;
    wzS_Val = gCurrTargetProd.TargetProd.Prod_Sounds_Like.toLowerCase().trim() + record.Sounds_Like.toLowerCase().trim();
    wzC_Val = gCurrTargetProd.TargetProd.Prod_Cue_Type.toLowerCase().trim();
    wzG_Val = gCurrTargetProd.TargetProd.Prod_Genre;
	
    //wzK_Val = gCurrTargetProd.TargetProd.Prod_Genre;
	wzK_Val = gCurrTargetProd.TargetProd.Prod_Desc;
	
    wzL_Val = gCurrTargetProd.TargetProd.Prod_Length;
    
    wzS_Src = record.Sounds_Like;
    wzC_Src = record.Cue_Type;
    wzG_Src = record.TCON_Genre;
    wzK_Src = record.TMOO_Keywords;
    wzL_Src = record.Run_Length + '';
    
    // matching on:
    //Production Field 		->	Track Field
    //Prod_Cue_Type	        ->	Cue_Type
    //Prod_Genre		->	TCON_Genre
    //Prod_Genre		->	TMOO_Leywords
    //Prod_Length		->	Run_Length
    //Prod_Sounds_Like          ->	Sounds_Like   
   
    if (wzS == 1 && record.Sounds_Like.trim().length > 0 && gCurrTargetProd.TargetProd.Prod_Sounds_Like.trim().length > 0)
    {
        if (
                record.Sounds_Like.toLowerCase().trim().indexOf(gCurrTargetProd.TargetProd.Prod_Sounds_Like.toLowerCase().trim()) >-1 ||
                gCurrTargetProd.TargetProd.Prod_Sounds_Like.toLowerCase().trim().indexOf(record.Sounds_Like.toLowerCase().trim()) >-1 ||
                record.Sounds_Like.toLowerCase().trim() == gCurrTargetProd.TargetProd.Prod_Sounds_Like.toLowerCase().trim()
            ) 
            {wzS_Match = true;}
    }
    if (wzS_Match == false && record.Sounds_Like.trim().length > 0 && gCurrTargetProd.TargetProd.Prod_Desc.trim().length > 0)
    {
        wzS_Match = wzCrossMatchList(trackfld=record.Sounds_Like, prodfld=gCurrTargetProd.TargetProd.Prod_Desc, [' ',','], trackDelim=',');  // first try a comma on track delim
        if (wzS_Match == false  && record.Sounds_Like.trim().length > 0 && gCurrTargetProd.TargetProd.Prod_Desc.trim().length > 0)
        {
            wzS_Match = wzCrossMatchList(trackfld=record.Sounds_Like, prodfld=gCurrTargetProd.TargetProd.Prod_Desc, [' ',','], trackDelim=' ');   // then try a space on tgrack delim     
        }
        else {a=1;}
    }
    else {wzS_Match = false;}
    
    if (wzC == 1 && record.Cue_Type.trim().length > 0 && gCurrTargetProd.TargetProd.Prod_Cue_Type.trim().length > 0)
    {
        if (
                record.Cue_Type.toLowerCase().trim().indexOf(gCurrTargetProd.TargetProd.Prod_Cue_Type.toLowerCase().trim()) > -1 ||
                gCurrTargetProd.TargetProd.Prod_Cue_Type.toLowerCase().trim().indexOf(record.Cue_Type.toLowerCase().trim()) > -1 ||
                gCurrTargetProd.TargetProd.Prod_Cue_Type.toLowerCase().trim() == record.Cue_Type.toLowerCase().trim() 
            ) 
        
            {wzC_Match = true;}
    } 
    else {wzC_Match = false;}

    if (wzG == 1)
    {
        wzG_Match = wzCrossMatchList(trackfld=record.TCON_Genre, prodfld=gCurrTargetProd.TargetProd.Prod_Genre, [',']);
    }   
    else {wzG_Match = false}

    if (wzK == 1)
    {
        wzK_Match = wzCrossMatchList(trackfld=record.TMOO_Keywords, prodfld=gCurrTargetProd.TargetProd.Prod_Desc, [' ',',']); 
    }  
    else {wzK_Match = false;}
    
    if (wzL == 1)
    {
        wzL_Match = wzCompareSeconds(track_len=record.Run_Length, prod_len=gCurrTargetProd.TargetProd.Prod_Length);
    } 
    else {wzL_Match}
    
    if (tAny_All == 'any')
    {
        if (
                (wzS_Match == true && wzS_Val.length > 0 && wzS_Src.length > 0) || (wzC_Match == true && wzC_Val.length > 0 && wzC_Src.length > 0) || 
                (wzG_Match == true && wzG_Val.length > 0 && wzG_Src.length > 0) || (wzK_Match == true && wzK_Val.length > 0 && wzK_Src.length > 0) || 
                (wzL_Match == true && wzL_Val.length > 0 && wzL_Src.length > 0)
            )
            {res = true;}
    }
    else
    {
        if (
            (wzS_Match == true && wzS_Val.length > 0 && wzS_Src.length > 0) && 
            (wzC_Match == true && wzC_Val.length > 0 && wzC_Src.length > 0) && 
            (wzG_Match == true && wzG_Val.length > 0 && wzG_Src.length > 0) && 
            (wzK_Match == true && wzK_Val.length > 0 && wzK_Src.length > 0) && 
            (wzL_Match == true && wzL_Val.length > 0 && wzL_Src.length > 0)
        ) 
        {res = true;}
    }
    return res;
}
// ------------------------------------------------------------ //
function wzPitchSuggestTracks()
{
    dtable = $$("pitchWZTrackSelectTable");
    
    dtable.eachRow(function(row){ 
        const record = dtable.getItem(row);
        record.wzIs_Checked = 0;
            
        this.updateItem(row, record);
    });   
    
    dtable.eachRow(function(row)
    { 
        const record = dtable.getItem(row);
        trackMatches = wzPitchMatch(record);
        record.wzIs_Suggested = trackMatches;            
        this.updateItem(row, record);
    });
    
    //console.log('wzFlags = ', wzS_Match, wzC_Match, wzG_Match, wzK_Match, wzL_Match);

}
// ------------------------------------------------------------ //
function catalogGetPitchable()
{
    var pitchableTracks = [];
       
    $$("catalogTable").data.each(function(obj)
    { 
        if (obj.Is_Stem == false && obj.Perm_Share_Active == 1) 
        {
            obj.wzIs_Suggested = 0;
            obj.wzIs_Checked = 0;
            pitchableTracks.push(webix.copy(obj));
        }
    });  

    return pitchableTracks;
}
// ------------------------------------------------------------ //
function targetProdsAvail(nested=false)
{
    var prods = [];
    for (ndx =0; ndx < targetsProductions.length; ndx++)
    {
        pp = targetsProductions[ndx].Production;
        if (nested == false) {tp = targetsProductions[ndx].Production; }   else {tp = targetsProductions[ndx]; }
        //if (pp.Prod_Status == 'Active') 
        if (1 == 1)
        {    
            prods.push(webix.copy(tp));   
        }
    }    

    return prods;
}
// ------------------------------------------------------------ //
async function VSSendGo() 
{

    url = '/kbdata/?mde=sendVS' + '&seq='+seq();
    gForm_Data = {'Surv_ID': gCurrSurvey.Survey_Data.Surv_ID}
    response = await axios.post(url, gForm_Data)
    gRes = response;
    resData = response.data;
    if (resData.status == 'error')
    {
      webix.message({type: "error", text: resData.Message, expire: 10000});
    }
    else
    {
	if (resData.status == 'success')
	{
	    webix.message({type: "success", text: resData.Message, expire: 4000});
	    $$("Survey_Data.Survey_Status").setValue('Active');
		
	}
	else
	    {webix.message({type: "error", text: resData.Message, expire: 10000});}
    }  
} 
// ------------------------------------------------------------ //
function VSSend() 
{
    if ($$("SurveyWindowForm").validate() == true)
    {    
	// process checks:
	if (gVSUsers.length == 0) 
	    {webix.message({type: "error", text: "<b>Error:</b>&nbsp;You <u>must</u> have at least one user participating in your Vetting Survey.", expire: 7000});return;}
	else
	    {
		$$("Survey_Data.Survey_Status").setValue('Ready');
		$$("Survey_Data.Survey_Status").refresh();	    
	    }
	if (gVSUsers.length == 0 && gForm_Data.Surver_Data.Survey_Status == 'Ready') 
	    {
		webix.message({type: "error", text: "<b>Error:</b>&nbsp;You must have at least one user in order to SEND the Survey.", expire: 7000});
		$$("Survey_Data.Survey_Status").setValue('Pending');
		$$("Survey_Data.Survey_Status").refresh();
		return;
	    }    
    
	toThese = "Do you want all users with a status of Pending to receive this survey now? <br/>";
	vcnt = 0;vus = '<blockquote>'
	
	for (ndx =0; ndx < gVSUsers.length; ndx++)
	{
	    vu = gVSUsers[ndx]; 
	    if (vu.VSUser_Status == 'Pending')
	    {
		vcnt += 1;
		vus = vus + vu.VSUser_Name + '<br/>'		
	    }	    	
	}
	
	if (vcnt == 0)
	{
	    webix.message({type: "debug", text: "<b>Oops!</b>&nbsp;There are no <u>Pending</u> users to send surveys to", expire: 8000});
	    return;
	}	
	
	lcText = toThese + "<br/><span style='padding-top:20px;line-height:1.8;'>Press <b>Yes</b> to SEND NOW.</span><br/><br/>"
	webix.confirm(
	 {
	  title: "<span style='line-height:2.8;'>Send out Vetting Survey?<br/></span>",
	  text: lcText,
	  ok: "Yes",
	  cancel: "No",
	  width:380,
	}).then(function(result)
	{
	    webix.message({type: "debug", text: "Sending your Vetting Survey to your users...", expire: 2000});
	    VSSendGo();
	    
	}).fail(function(){
	    webix.message({type: "error", text: "No action taken..", expire: 5000});       
	});	
	
	
    } 
    else
    {
        webix_message({type: "error", text: "<b>Error:</b>&nbsp;Please correct any errors and retry", expire: 3000},1,'Survey Save','wfferwwef');
    }
} 
gVSUsers = [];
// ------------------------------------------------------------ //
function doNewVettingUser()
{
    // newVetting was filled
    //console.log('newVetting =', newVetting);
    already = false;
    LL = gVSUsers.length;
    utot = 0
    for (ndx =0; ndx < gVSUsers.length; ndx++)
    {
	utot += 1;
    }
    
    newSlot = 99;lastSlot = 0;
    for (ndx =0; ndx < gVSUsers.length; ndx++)
    {
	vu = gVSUsers[ndx];             
	if (parseInt(vu.VSUser_Num) < newSlot && (lastSlot + 1) < parseInt(vu.VSUser_Num) && lastSlot != 0)
	{
	    newSlot = lastSlot + 1;               
	    lastSlot = parseInt(vu.VSUser_Num);
	}
	else
	{
	    lastSlot = parseInt(vu.VSUser_Num);	   
	}
    }    
    
    for (ndx =0; ndx < gVSUsers.length; ndx++)
    {
	VU = gVSUsers[ndx];  
	if (VU.VSUser_Email == newVetting.Email) {already = true;break;}
    } 
    if (already == false && LL < 10)
    {
	utot += 1;
	if (newSlot != 99) {utot = newSlot;}
	ctot =pad(utot,2)
	newuser = {'VSUser_Num': ctot, 'VSUser_Email': newVetting.Email, 'VSUser_Name': newVetting.Full_Name, 'VSUser_Status': 'Pending'};
	gVSUsers.push(newuser);
	setTimeout(`
	    $$("vsUsersTable").clearAll();
	    $$("vsUsersTable").parse(gVSUsers);
	    $$("vsUsersTable").refresh();	
	    showSaveReviewerMsg();
	    `,1200);
	    
	    
    }
}
// ------------------------------------------------------------ //
function showSaveReviewerMsg()
{

    lcWarning = 
    `
    <table>
	<tr>
	    <td>
	    <img src="/static/assets/images/wigit_100.png" width="60px;"> 
	    </td>
	    <td style="padding-left:10px; padding-right:10px; font-size:13px;line-height:1.6;">
	    <br/>After adding a Reviewer click SAVE to confirm them as a recipient.
	    </td>
	</tr>
    </table>
    `;
    
    ph = 120; pw = 310;
    setTimeout("genSmallPopup('btnVSNew',lcWarning,ph,pw);",700);  
}
// ------------------------------------------------------------ //
function VSFind()
{
    $$("btnVSSend").disable();
    $$("btnVSClear").disable();
    Make_ContLookup("VETTING",'',membersOnly=false);
}
// ------------------------------------------------------------ //
async function VSDel() 
{
    selectedVSU = $$("vsUsersTable").getSelectedItem();
    if ( selectedVSU == undefined)
    {
	webix.message({type: "error", text: "<b>Oops:</b>&nbsp;Please select a record to delete first.", expire: 5000});
	return;
    }
    else
    {
	webix.confirm(
	 {
	  title: "<span style='line-height:2.8;'>Delete Reviewer?<br/></span>",
	  text:"<span style='padding-top:20px;line-height:1.8;'>Press <b>Yes</b> to remove <br/><b>" + selectedVSU.VSUser_Email + "</b> <br/>as a Reviewer</span><br/><br/>",
	  ok: "Yes",
	  cancel: "No",
	  width:380,
	}).then(function(result)
	{
	    webix.message({type: "debug", text: "Deleting Survey User", expire: 2000});
	    del_user_id = selectedVSU.VSUser_Num + ':' + selectedVSU.VSUser_Email;
	    VSSave(inArea='survey',inDelUser=del_user_id) 
	    
	}).fail(function(){
	    webix.message({type: "error", text: "No action taken..", expire: 5000});       
	});       	    
	}
} 
// ------------------------------------------------------------ //
function VSClear()
{
    webix.confirm(
     {
      title: "<span style='line-height:2.8;'>Clear All Survey Data<br/></span>",
      text:"<span style='padding-top:20px;line-height:1.8;'>Press <b>Yes</b> to clear all Survey Data, Questions, and Answers, and start over.</span><br/><br/>",
      ok: "Yes",
      cancel: "No",
      width:380,
    }).then(function(result)
    {

         setTimeout('VSClearGo();',500);
        
    }).fail(function(){
        webix.message({type: "error", text: "Cancelled", expire: 5000});       
    });  
}
// ------------------------------------------------------------ //
function VSClearGo() 
{
    webix.message({type: "debug", text: "Clearing Survey data .. please wait", expire: 2000});
    vettingSurveyPull(true);
    webix.message({type: "debug", text: "Survey clear completed", expire: 4000});
} 
// ------------------------------------------------------------ //
async function VSSave(inArea='survey',inDelUser='') 
{
    wasFor = inArea;
    if (inArea == 'btnVSNew' || inArea == 'btnVSSave') {inArea = 'survey';}
    if ($$("SurveyWindowForm").validate() == true)
    {	
	if (inArea == 'survey') 
	{
	    gForm_Data = $$("SurveyWindowForm").getValues();	
		
	    if (gVSUsers.length == 0 && gForm_Data.Survey_Data.Survey_Status == 'Ready') 
		{
		    webix.message({type: "error", text: "<b>Error:</b>&nbsp;You must have at least one user in order to set the Survey to <b>Ready</b>.", expire: 7000});
		    $$("Survey_Data.Survey_Status").setValue('Pending');
		    $$("Survey_Data.Survey_Status").refresh();
		    return;
		}		
	    	    
	    gForm_Data.Survey_Users = gVSUsers; 
	    gForm_Data.Delete_User_ID = inDelUser;
	    webix.message({type: "success", text: "<b>OK:</b>&nbsp;Saving Vetting Survey data..", expire: 900});
	}

	url = '/kbdata/?mde=saveVS&area=' + inArea + '&seq='+seq();
	response = await axios.post(url, gForm_Data)
	gRes = response;
	resData = response.data;
	if (resData.status == 'error')
	{
	  webix.message({type: "error", text: resData.Message, expire: 10000});
	}
	else
	{
	    if (resData.status == 'success')
	    {
		if (wasFor == 'btnVSNew')
		{
		    $$("btnVSSave").enable();
		    $$("btnVSSend").enable();
		    $$("btnVSClear").enable();		
		}
		
		if (gRes.data.Survey_Data.Survey_Status == 'Ready') {$$("Survey_Data.Survey_Status").setValue('Ready');}
	    
		webix.message({type: "success", text: resData.Message, expire: 4000});
		gCurrSurvey = {'Survey_Data': resData.Survey_Data};
		setTimeout('$$("SurveyWindowForm").parse(gCurrSurvey);',400);		
		$$("vsUsersTable").clearAll();
		gVSUsers = resData.Survey_User_Array;
		$$("vsUsersTable").parse(gVSUsers);
		setTimeout(`
		    if (gVSUsers.length >= 10) {$$("btnVSFind").disable();}
		`,1000);		
	    }
	    else
		{webix.message({type: "error", text: resData.Message, expire: 10000});}
	}  

    }
    else
    {
	if ($$("Survey_Data.Survey_Track_Link").getValue().length == 0)
	{
	    lcWarning = 
	    `
	    <table>
		<tr>
		    <td>
		    <img src="/static/assets/images/wigit_100.png" width="60px;"> 
		    </td>
		    <td style="padding-left:10px; padding-right:10px; font-size:13px;line-height:1.6;">
		    <br/>Before you begin work on your survey, you must add the audio file you want reviewed to this Project&apos;s <strong>Files</strong> Tab, then select it from this drop-down.
		    </td>
		</tr>
	    </table>
	    `;
	    
	    ph = 160; pw = 370;
	    setTimeout("genSmallPopup('Survey_Data.Survey_Track_Link',lcWarning,ph,pw);",700);    
	}
    }
} 

fdcToggle = false;

// ------------------------------------------------------------ //
function genSmallPopup_2_ID(inViewID,inHTML,inH,inW)
{

	node = $$(inViewID).getInputNode();
	if ($$("tmpPopup") !== undefined) {$$('tmpPopup').hide();$$('tmpPopup').destructor();}
	
	webix.ui({
	  view: "popup",
	  id: "tmpPopup",
	  height: inH,
	  width: inW,
	  body:
	  {
		template: inHTML
	  }
	});
	
	$$("tmpPopup").show(node, { pos: "bottom", x:-10, y:10});
}
// ------------------------------------------------------------ //
function anyTagsPendingWarning()
{

    warnPending = localStorage.getItem('userWarnPending');
    if (warnPending == null) 
	{
		localStorage.setItem('userWarnPending','y');
		warnPending = localStorage.getItem('userWarnPending');
	}
	if (warnPending == 'y')
	{
		lcWarning = 
		`
		<table>
		<tr>
			<td>
			<img src="/static/assets/images/wigit_100.png" width="60px;"> 
			</td>
			<td style="padding-left:10px; padding-right:10px; font-size:13px;line-height:1.6;">
			<br/>When a Track in the Catalog list is highlighted <strong>yellow</strong> there are metadata updates that need to be <b>Tagged to Files</b>
			<br/><a href="#" onclick='localStorage.setItem("userWarnPending","n");' style="color:purple;font-weight:bold;">Dismiss</a></br>
			</td>
		</tr>
		</table>
		`;
		
		ph = 160; pw = 370;
		setTimeout("genSmallPopup_2_ID('catalogSearchFld',lcWarning,ph,pw);",700);  
	}
}
// ------------------------------------------------------------ //
function toggleFDChecks()
{
    if (fdcToggle == false)
    {
        fdcToggle = true;
        $("#fdc_toggler").addClass('fdcToggle_On').removeClass('fdcToggle_Off');
                fdMap.set("chkMeta_COMM_3_Desc", 1);
                fdMap.set("chkMeta_TrackNum", 1);
                fdMap.set("chkMeta_Volume", 1);
                fdMap.set("chkMeta_Source", 1);
                fdMap.set("chkMeta_TCON_Genre", 1);
                fdMap.set("chkMeta_APIC_AlbumArt", 1);
                fdMap.set("chkMeta_Tempo", 1);
                fdMap.set("chkMeta_TBPM_BPM", 1);
                fdMap.set("chkMeta_Reg_Date", 1);
                fdMap.set("chkMeta_Date_Released", 1);
                fdMap.set("chkMeta_PRO_WorkNum", 1);
                fdMap.set("chkMeta_ISWC_Num", 1);
                fdMap.set("chkMeta_ISRC_Num", 1);   
                fdMap.set("chkMeta_Key", 1);
                fdMap.set("chkMeta_TALB_CDTitle", 1);
                fdMap.set("chkMeta_GRP1_Grouping", 1); 
                fdMap.set("chkMeta_TPUB_Publisher", 1);
                fdMap.set("chkMeta_TCOM_Composer", 1);
                fdMap.set("chkMeta_TPE1_Artist", 1);
                fdMap.set("chkMeta_TPE2_AlbumArtist", 1);
                fdMap.set("chkMeta_Lyrics", 1);
                fdMap.set("chkMeta_Sounds_Like", 1);
                fdMap.set("chkMeta_TMOO_Keywords", 1);
                fdMap.set("chkMeta_Copyright", 1);  
                fdMap.set("chkMeta_Copyright_Info", 1);
                fdMap.set("chkMeta_CopyParts", 0);
                fdMap.set("chkMeta_CopyBlanks", 0);
                fdMap.set("chkMeta_Cue_Type", 1);
                fdMap.set("chkMeta_Prod_Type", 1);
                fdMap.set("chkMeta_Ideal_For", 1);        
    }
    else
    {
        fdcToggle = false;
        $("#fdc_toggler").addClass('fdcToggle_Off').removeClass('fdcToggle_On');
                fdMap.set("chkMeta_COMM_3_Desc", 0);
                fdMap.set("chkMeta_TrackNum", 0);
                fdMap.set("chkMeta_Volume", 0);
                fdMap.set("chkMeta_Source", 0);
                fdMap.set("chkMeta_TCON_Genre", 0);
                fdMap.set("chkMeta_APIC_AlbumArt", 0);
                fdMap.set("chkMeta_Tempo", 0);
                fdMap.set("chkMeta_TBPM_BPM", 0);
                fdMap.set("chkMeta_Reg_Date", 0);
                fdMap.set("chkMeta_Date_Released", 0);
                fdMap.set("chkMeta_PRO_WorkNum", 0);
                fdMap.set("chkMeta_ISWC_Num", 0);
                fdMap.set("chkMeta_ISRC_Num", 0);   
                fdMap.set("chkMeta_Key", 0);
                fdMap.set("chkMeta_TALB_CDTitle", 0);
                fdMap.set("chkMeta_GRP1_Grouping", 0); 
                fdMap.set("chkMeta_TPUB_Publisher", 0);
                fdMap.set("chkMeta_TCOM_Composer", 0);
                fdMap.set("chkMeta_TPE1_Artist", 0);
                fdMap.set("chkMeta_TPE2_AlbumArtist", 0);
                fdMap.set("chkMeta_Lyrics", 0);
                fdMap.set("chkMeta_Sounds_Like", 0);
                fdMap.set("chkMeta_TMOO_Keywords", 0);
                fdMap.set("chkMeta_Copyright", 0);  
                fdMap.set("chkMeta_Copyright_Info", 0);
                fdMap.set("chkMeta_CopyParts", 0);
                fdMap.set("chkMeta_CopyBlanks", 0);
                fdMap.set("chkMeta_Cue_Type", 0);
                fdMap.set("chkMeta_Prod_Type", 0);
                fdMap.set("chkMeta_Ideal_For", 0);        
    }
    
    $$("chkMeta_COMM_3_Desc").setValue(fdMap.get("chkMeta_COMM_3_Desc"));
    $$("chkMeta_TrackNum").setValue(fdMap.get("chkMeta_TrackNum"));
    $$("chkMeta_Volume").setValue(fdMap.get("chkMeta_Volume"));
    $$("chkMeta_Source").setValue(fdMap.get("chkMeta_Source"));
    $$("chkMeta_TCON_Genre").setValue(fdMap.get("chkMeta_TCON_Genre"));
    $$("chkMeta_APIC_AlbumArt").setValue(fdMap.get("chkMeta_APIC_AlbumArt"));
    $$("chkMeta_Tempo").setValue(fdMap.get("chkMeta_Tempo"));
    $$("chkMeta_TBPM_BPM").setValue(fdMap.get("chkMeta_TBPM_BPM"));
    $$("chkMeta_Reg_Date").setValue(fdMap.get("chkMeta_Reg_Date"));
    $$("chkMeta_Date_Released").setValue(fdMap.get("chkMeta_Date_Released"));
    $$("chkMeta_PRO_WorkNum").setValue(fdMap.get("chkMeta_PRO_WorkNum"));
    $$("chkMeta_ISWC_Num").setValue(fdMap.get("chkMeta_ISWC_Num"));
    $$("chkMeta_ISRC_Num").setValue(fdMap.get("chkMeta_ISRC_Num"));
    $$("chkMeta_Key").setValue(fdMap.get("chkMeta_Key"));
    $$("chkMeta_TALB_CDTitle").setValue(fdMap.get("chkMeta_TALB_CDTitle"));
    $$("chkMeta_GRP1_Grouping").setValue(fdMap.get("chkMeta_GRP1_Grouping"));
    $$("chkMeta_TPUB_Publisher").setValue(fdMap.get("chkMeta_TPUB_Publisher"));
    $$("chkMeta_TCOM_Composer").setValue(fdMap.get("chkMeta_TCOM_Composer"));
    $$("chkMeta_TPE1_Artist").setValue(fdMap.get("chkMeta_TPE1_Artist"));
    $$("chkMeta_TPE2_AlbumArtist").setValue(fdMap.get("chkMeta_TPE2_AlbumArtist"));
    $$("chkMeta_Lyrics").setValue(fdMap.get("chkMeta_Lyrics"));
    $$("chkMeta_Sounds_Like").setValue(fdMap.get("chkMeta_Sounds_Like"));
    $$("chkMeta_TMOO_Keywords").setValue(fdMap.get("chkMeta_TMOO_Keywords"));
    $$("chkMeta_Copyright").setValue(fdMap.get("chkMeta_Copyright"));
    $$("chkMeta_Copyright_Info").setValue(fdMap.get("chkMeta_Copyright_Info"));
    $$("chkMeta_CopyParts").setValue(fdMap.get("chkMeta_CopyParts"));
    $$("chkMeta_CopyBlanks").setValue(fdMap.get("chkMeta_CopyBlanks"));
    $$("chkMeta_Cue_Type").setValue(fdMap.get("chkMeta_Cue_Type"));
    $$("chkMeta_Prod_Type").setValue(fdMap.get("chkMeta_Prod_Type"));
    $$("chkMeta_Ideal_For").setValue(fdMap.get("chkMeta_Ideal_For"));    

}
// ------------------------------------------------------------ //
fdMap = new Map();
function fdChecks(mde='init')
{
        if (mde == 'init')
        {
                fdMap.set("chkMeta_COMM_3_Desc", 1);
                fdMap.set("chkMeta_TrackNum", 1);
                fdMap.set("chkMeta_Volume", 1);
                fdMap.set("chkMeta_Source", 1);
                fdMap.set("chkMeta_TCON_Genre", 1);
                fdMap.set("chkMeta_APIC_AlbumArt", 1);
                fdMap.set("chkMeta_Tempo", 1);
                fdMap.set("chkMeta_TBPM_BPM", 1);
                fdMap.set("chkMeta_Reg_Date", 1);
                fdMap.set("chkMeta_Date_Released", 1);
                fdMap.set("chkMeta_PRO_WorkNum", 1);
                fdMap.set("chkMeta_ISWC_Num", 1);
                fdMap.set("chkMeta_ISRC_Num", 1);   
                fdMap.set("chkMeta_Key", 1);
                fdMap.set("chkMeta_TALB_CDTitle", 1);
                fdMap.set("chkMeta_GRP1_Grouping", 1); 
                fdMap.set("chkMeta_TPUB_Publisher", 1);
                fdMap.set("chkMeta_TCOM_Composer", 1);
                fdMap.set("chkMeta_TPE1_Artist", 1);
                fdMap.set("chkMeta_TPE2_AlbumArtist", 1);
                fdMap.set("chkMeta_Lyrics", 1);
                fdMap.set("chkMeta_Sounds_Like", 1);
                fdMap.set("chkMeta_TMOO_Keywords", 1);
                fdMap.set("chkMeta_Copyright", 1);  
                fdMap.set("chkMeta_Copyright_Info", 1);
                fdMap.set("chkMeta_CopyParts", 0);
                fdMap.set("chkMeta_CopyBlanks", 0);
                fdMap.set("chkMeta_Cue_Type", 1);
                fdMap.set("chkMeta_Prod_Type", 1);
                fdMap.set("chkMeta_Ideal_For", 1);
                return;
        }
        
        if (mde == 'store')
        {
                fdMap.set("chkMeta_COMM_3_Desc", $$("chkMeta_COMM_3_Desc").getValue());
                fdMap.set("chkMeta_TrackNum", $$("chkMeta_TrackNum").getValue());
                fdMap.set("chkMeta_Volume", $$("chkMeta_Volume").getValue());
                fdMap.set("chkMeta_Source", $$("chkMeta_Source").getValue());
                fdMap.set("chkMeta_TCON_Genre", $$("chkMeta_TCON_Genre").getValue());
                fdMap.set("chkMeta_APIC_AlbumArt", $$("chkMeta_APIC_AlbumArt").getValue());
                fdMap.set("chkMeta_Tempo", $$("chkMeta_Tempo").getValue());
                fdMap.set("chkMeta_TBPM_BPM", $$("chkMeta_TBPM_BPM").getValue());
                fdMap.set("chkMeta_Reg_Date", $$("chkMeta_Reg_Date").getValue());
                fdMap.set("chkMeta_Date_Released", $$("chkMeta_Date_Released").getValue());
                fdMap.set("chkMeta_PRO_WorkNum", $$("chkMeta_PRO_WorkNum").getValue());
                fdMap.set("chkMeta_ISWC_Num", $$("chkMeta_ISWC_Num").getValue());
                fdMap.set("chkMeta_ISRC_Num", $$("chkMeta_ISRC_Num").getValue());   
                fdMap.set("chkMeta_Key", $$("chkMeta_Key").getValue());
                fdMap.set("chkMeta_TALB_CDTitle", $$("chkMeta_TALB_CDTitle").getValue());
                fdMap.set("chkMeta_GRP1_Grouping", $$("chkMeta_GRP1_Grouping").getValue()); 
                fdMap.set("chkMeta_TPUB_Publisher", $$("chkMeta_TPUB_Publisher").getValue());
                fdMap.set("chkMeta_TCOM_Composer", $$("chkMeta_TCOM_Composer").getValue());
                fdMap.set("chkMeta_TPE1_Artist", $$("chkMeta_TPE1_Artist").getValue());
                fdMap.set("chkMeta_TPE2_AlbumArtist", $$("chkMeta_TPE2_AlbumArtist").getValue());
                fdMap.set("chkMeta_Lyrics", $$("chkMeta_Lyrics").getValue());
                fdMap.set("chkMeta_Sounds_Like", $$("chkMeta_Sounds_Like").getValue());
                fdMap.set("chkMeta_TMOO_Keywords", $$("chkMeta_TMOO_Keywords").getValue());
                fdMap.set("chkMeta_Copyright", $$("chkMeta_Copyright").getValue());  
                fdMap.set("chkMeta_Copyright_Info", $$("chkMeta_Copyright_Info").getValue());
                fdMap.set("chkMeta_CopyParts", $$("chkMeta_CopyParts").getValue());
                fdMap.set("chkMeta_CopyBlanks", $$("chkMeta_CopyBlanks").getValue());
                fdMap.set("chkMeta_Cue_Type", $$("chkMeta_Cue_Type").getValue());
                fdMap.set("chkMeta_Prod_Type", $$("chkMeta_Prod_Type").getValue());
                fdMap.set("chkMeta_Ideal_For", $$("chkMeta_Ideal_For").getValue());
                return;
        }
        
        if (mde == 'load')
        {  
            $$("chkMeta_COMM_3_Desc").setValue(fdMap.get("chkMeta_COMM_3_Desc"));
            $$("chkMeta_TrackNum").setValue(fdMap.get("chkMeta_TrackNum"));
            $$("chkMeta_Volume").setValue(fdMap.get("chkMeta_Volume"));
            $$("chkMeta_Source").setValue(fdMap.get("chkMeta_Source"));
            $$("chkMeta_TCON_Genre").setValue(fdMap.get("chkMeta_TCON_Genre"));
            $$("chkMeta_APIC_AlbumArt").setValue(fdMap.get("chkMeta_APIC_AlbumArt"));
            $$("chkMeta_Tempo").setValue(fdMap.get("chkMeta_Tempo"));
            $$("chkMeta_TBPM_BPM").setValue(fdMap.get("chkMeta_TBPM_BPM"));
            $$("chkMeta_Reg_Date").setValue(fdMap.get("chkMeta_Reg_Date"));
            $$("chkMeta_Date_Released").setValue(fdMap.get("chkMeta_Date_Released"));
            $$("chkMeta_PRO_WorkNum").setValue(fdMap.get("chkMeta_PRO_WorkNum"));
            $$("chkMeta_ISWC_Num").setValue(fdMap.get("chkMeta_ISWC_Num"));
            $$("chkMeta_ISRC_Num").setValue(fdMap.get("chkMeta_ISRC_Num"));
            $$("chkMeta_Key").setValue(fdMap.get("chkMeta_Key"));
            $$("chkMeta_TALB_CDTitle").setValue(fdMap.get("chkMeta_TALB_CDTitle"));
            $$("chkMeta_GRP1_Grouping").setValue(fdMap.get("chkMeta_GRP1_Grouping"));
            $$("chkMeta_TPUB_Publisher").setValue(fdMap.get("chkMeta_TPUB_Publisher"));
            $$("chkMeta_TCOM_Composer").setValue(fdMap.get("chkMeta_TCOM_Composer"));
            $$("chkMeta_TPE1_Artist").setValue(fdMap.get("chkMeta_TPE1_Artist"));
            $$("chkMeta_TPE2_AlbumArtist").setValue(fdMap.get("chkMeta_TPE2_AlbumArtist"));
            $$("chkMeta_Lyrics").setValue(fdMap.get("chkMeta_Lyrics"));
            $$("chkMeta_Sounds_Like").setValue(fdMap.get("chkMeta_Sounds_Like"));
            $$("chkMeta_TMOO_Keywords").setValue(fdMap.get("chkMeta_TMOO_Keywords"));
            $$("chkMeta_Copyright").setValue(fdMap.get("chkMeta_Copyright"));
            $$("chkMeta_Copyright_Info").setValue(fdMap.get("chkMeta_Copyright_Info"));
            $$("chkMeta_CopyParts").setValue(fdMap.get("chkMeta_CopyParts"));
            $$("chkMeta_CopyBlanks").setValue(fdMap.get("chkMeta_CopyBlanks"));
            $$("chkMeta_Cue_Type").setValue(fdMap.get("chkMeta_Cue_Type"));
            $$("chkMeta_Prod_Type").setValue(fdMap.get("chkMeta_Prod_Type"));
            $$("chkMeta_Ideal_For").setValue(fdMap.get("chkMeta_Ideal_For"));
        }
        
}
// ------------------------------------------------------------ //
function wzGetSelected()
{
    var wzSelectedTracks = []; 
    $$("pitchWZTrackSelectTable").data.each(function(obj)
    { 
        if (obj.wzIs_Checked && obj.wzIs_Checked == 'on') 
        {
            wzSelectedTracks.push(webix.copy(obj));
        }
    });  
    return wzSelectedTracks;
}
// ------------------------------------------------------------ //
function wzAddPitch()
{
    //console.log("wzAddPitch():");
    wzSelected = [];
    wzPitchName = '';
    if (gCurrTab == 'Catalog')
    {
        wzSelected = catalogTagged();
        if (wzSelected.length == 0)
        {
            webix.message({type: "error", text: "<b>Error:</b>&nbsp;No tracks selected to pitch.", expire: 7000});
            return; 
        } 
 
        wzSelectContact();  // have to get a valid contact first in order to create a target and opportunity for this route
        
    }
    else
    {
        if (gCurrTarget.hasOwnProperty('Target') == false)
        {
            webix.message({type: "error", text: "<b>Error:</b>&nbsp;&nbsp;Please select a Target first", expire: 10000});
            return;
        }
        
        if (gCurrTargetProd.hasOwnProperty('TargetProd') == false)
        {
            webix.message({type: "error", text: "<b>Error:</b>&nbsp;&nbsp;Please select an Opportunity first", expire: 10000});
            return;
        }    
        
        wzSelected = wzGetSelected();    
        if (wzSelected.length == 0)
        {
            webix.message({type: "error", text: "<b>Error:</b>&nbsp;&nbsp;Please select some Tracks for the Pitch first", expire: 10000});
            return;
        }  
        lcDefVal = gCurrTargetProd.TargetProd.Prod_Title;
        lcMsg = '<br/>Add a new pitch for this opportunity with your <b><span style="font-size:18px;color:purple;">' + wzSelected.length + '</span></b> selected Tracks?<br/>';        
        
    }    
}
// ------------------------------------------------------------ //
async function wzAddPitchGoFinal()
{
    //console.log("wzAddPitchGoFinal():"); 
    if (gForm_Data.Action == 'Upload') 
        {gForm_Data.Mark_Done = $$("wzPitchUploadConfirm").getValue();}
    else if (gForm_Data.Action == 'DISCO') 
        {gForm_Data.Mark_Done = $$("wzPitchDISCOConfirm").getValue();}    
    else if (gForm_Data.Action == 'Share') 
        {gForm_Data.Mark_Done = $$("wzPitchShareSubmittedButton").getValue();}                  
    else {gForm_Data.Mark_Done = 0;}
    
    gForm_Data.Pitch_Subject = $$("wzPitchMessageSubject").getValue();
    
        
    webix.message({type: "success", text: "<b>OK:</b>&nbsp;Creating a new Pitch.", expire: 900});
    url = '/data_pitches/?mde=newpitch&cid='+gXID+'&seq='+seq();
    response = await axios.post(url, gForm_Data)
    gRes = response;
    resData = response.data;
    if (resData.status == 'error')
    {
      webix.message({type: "error", text: resData.Message, expire: 10000});
    }
    else
    {
        if (resData.status == 'success')
        {
            webix.message({type: "success", text: resData.Message, expire: 2000});
            lcMsg = resData.Pitch.Pitch_Wizard_Status.replaceAll('|','<br/>');
            if (gForm_Data.Action == 'Share') 
            {
                copyTextToClipboard(resData.Pitch.Pitch_Link_URL);
                lcMsg += '<br/>The Share Link has now been copied to the clipboard.<br/>';
            }
            

	    $$("catalogTable").data.each(function(obj)
	    { 
		if (obj.chkCatalog == 'on')
		{
		    obj.chkCatalog = 'off';
		    $$("catalogTable").refresh(obj.id);  
		}
	    }); 

            
            dataWH.Pitches.dataStore.add(resData.Pitch); 
            for (ndx =0; ndx < resData.Pitch_Tracks.length; ndx++)
            {
                PT = resData.Pitch_Tracks[ndx];  
                dataWH.Pitch_Tracks.dataStore.add(PT);
            }    
	    catalogSetPitches();
	    npPitch = {'Pitch': resData.Pitch};
            setTimeout('switchToNewPitch();',1000);
	    
	    setTimeout('$$("refPitchTargetProd.TargetProd.Prod_Project_Name").setValue(refPitchTargetProd.TargetProd.Prod_Project_Name);',8000);
	    setTimeout('$$("Pitch.Full_Share_Link").setValue(gCurrPitch.Pitch.Pitch_Link_URL);',8000);
	    
	    if (gForm_Data.Action != 'Upload' && gForm_Data.Action != 'DISCO') 
	    {
		setTimeout('webix.html.triggerEvent($$("btnTestShareLink2").getInputNode(), "MouseEvents", "click");',8300);
	    }
	    
        }
        else
            {webix.message({type: "error", text: resData.Message, expire: 10000});}
    }   


}

// ------------------------------------------------------------ //
function wzSelectTarget2License()
{
    Make_ContLookup("catalogAddLicense",{row: gXID}); 
    // flows to targetNewSubmit();
}
// ------------------------------------------------------------ //
function wzSelectContact()
{
    Make_ContLookup("catalogAddPitch",{row: gXID}); 
    // flows to targetsPitchPull ... it flows to wzAddPitchGo
}
// ------------------------------------------------------------ //
function wzAddPitchGo()
{
    if ($$("pitchWZCategorySelect").getValue() == '')
    {
        webix_message({type: "error", text: "<b>ERROR:</b><br/>You must select a Pitch action first", expire: 10000},6);
        webix.UIManager.setFocus($$("pitchWZCategorySelect"));
        return;
    }   

    lcName = $$("NewPitch.Pitch_Project").getValue();
    lcAction = $$("pitchWZCategorySelect").getValue();
    lcEmailBlurb = $$("wzPitchBlurb").getValue();
    
    if ($$("wzPitchMessageSubject").getValue().length == 0 && lcAction == 'Email')
    {
        webix.message({type: "error", text: '<b>Error</b><br/>The email subject line is a required field.', expire: 5000});
        $$("wzPitchMessageSubject").focus();
        return;
    }     
    
    if (gCurrTab == 'Catalog') 
    {
        mde='Catalog';
        gForm_Data = {'Mode': mde, 'Pitch_Name': lcName, 'Action': lcAction, 'Email_Blurb':  lcEmailBlurb, 'Pitch_ID': gXID, 'Target_ID': gCurrTarget.Target.Target_ID, 'Prod_ID': gCurrTargetProd.TargetProd.Prod_ID, 'Tracks': wzSelected}  
        //console.log("wzAddPitchGo(): catalog ->  name=",lcName,"selected=",wzSelected);
    } 
    else 
    {   mde='Targeted';
        gForm_Data = {'Mode': mde, 'Pitch_Name': lcName, 'Action': lcAction, 'Email_Blurb':  lcEmailBlurb, 'Pitch_ID': gXID, 'Target_ID': gCurrTarget.Target.Target_ID, 'Prod_ID': gCurrTargetProd.TargetProd.Prod_ID, 'Tracks': wzSelected}
        //console.log("wzAddPitchGo(): targeted -> name=",lcName,"selected=",wzSelected);
    }        

    webix.confirm(
     {
      title: "<span style='line-height:2.8;'>Create Your Pitch Now?<br/></span>",
      text:"<span style='padding-top:20px;line-height:1.8;'>Press <b>Yes</b> to record your pitch and take action</span><br/><br/>",
      ok: "Yes",
      cancel: "No",
      width:380,
    }).then(function(result)
    {
        webix.message({type: "debug", text: "Creating Pitch/taking action", expire: 3000});
         setTimeout('wzAddPitchGoFinal();',500);
        
    }).fail(function(){
        webix.message({type: "error", text: "No Pitch created/action taken..", expire: 5000});       
    });                      
    
}
npPitch = {}
// ------------------------------------------------------------ //
function switchToNewPitch()
{

    try {webix.html.triggerEvent($$("pitchWindowClose").getInputNode(), "MouseEvents", "click");} catch(err) {a=1;}  
    pitchesCurrID = {"row": npPitch.Pitch.Pitch_ID}
    gCurrTab = 'Pitches';
    gotoModule('Pitches');
    cpPitch_tItem = $$("pitchesTable").getItem(npPitch.Pitch.Pitch_ID);
    setTimeout('$$("pitchesTable").select(npPitch.Pitch.id);',1600);
    setTimeout("gotoPitchesTab('pitchesInfo');",3300); 
    setTimeout('$$("pitchesEditForm").clear();',4100);
    setTimeout('dataWH.Pitches.keepRecord = gCurrPitch["Pitch"];$$("pitchesEditForm").parse(gCurrPitch);',5400);   
    setTimeout('webix.html.triggerEvent($$("btnTargetsCancel").getInputNode(), "MouseEvents", "click");',5800);
    

}
// ------------------------------------------------------------ //
function findPitchRef(inID,inType='prod')
{
    out = {};fnd = false;
    if (inType == 'prod')
    {
        dataWH.Productions.dataStore.data.each(function(obj)
        {
            if (obj.Prod_ID == inID) 
            {
                out = {'TargetProd': obj}
                fnd = true;
            }
        });   
	if (fnd == true) {return out;}
	console.log('prod not found');
    }
    
    if (inType == 'target')
    {
        dataWH.Targets.dataStore.data.each(function(obj)
        {
            if (obj.Target_ID == inID) 
            {
                out = {'Target': obj}
                fnd = true;
            }
        }); 
	if (fnd == true) {return out;}
	console.log('target not found');
    }
        
    if (inType == 'pitch')
    {
        dataWH.Pitches.dataStore.data.each(function(obj)
        {
            if (obj.Pitch_ID == inID) 
            {
                out = {'Pitch': obj}
                fnd = true;
            }
        }); 
        if (fnd == true) {return out;}
	console.log('pitch not found');
    }    
    
    return out;
}
// ------------------------------------------------------------ //
function wzShowSelected(inID='wzSelectedTrackNames')
{
    html = '';
    tmplte = `
            <div id='wzShowTrack_##id##' style=''>##icon## ##trackname##</div>
    `;
        
    $$("pitchWZTrackSelectTable").data.each(function(obj)
    { 
        if (obj.wzIs_Checked && obj.wzIs_Checked == 'on') 
        {
                        trackline = tmplte.replaceAll('##id##',obj.Track_ID).replaceAll('##icon##',icon_status_pitched_purple).replaceAll('##trackname##',obj.TIT2_TrackName) + '\n';
                        html = html + trackline;
        }
    });  
        
        html = "<div style='margin:10px;'>" + html + "</div>";
        $$(inID).setHTML(html);
        return;
}
// ------------------------------------------------------------ //
function wzSetDisplay(newValue, oldValue, config)
{
    // first, hide them all
    $$("wzPitchEmail").hide();
    $$("wzPitchDISCO").hide();
    $$("wzPitchUpload").hide();
    $$("wzPitchShare").hide();
    
    $$("wzPitchMessageSubject").hide();
    $$("wzPitchBlurb").hide();
    $$("wzPitchEmailInstructsHeader").hide();
    $$("wzPitchEmailInstructs").hide();
    $$("wzPitchDISCOInstructsHeader").hide();
    $$("wzPitchDISCOInstructs").hide();
    $$("wzPitchDISCOInstructs2").hide();
    $$("wzPitchUploadInstructsHeader").hide();
    $$("wzPitchUploadInstructs").hide();
    $$("wzPitchShareInstructsHeader").hide();
    $$("wzPitchShareInstructs").hide();
    $$("wzPitchUploadSavePitch").hide();
    $$("wzPitchEmailButton").hide();
    $$("wzPitchDISCOButton").hide();
    $$("wzPitchUploadButton").hide();
    $$("wzPitchUploadCreateButton").hide();
    $$("wzPitchDISCOConfirm").hide();
    $$("wzPitchUploadConfirm").hide();    
    $$("wzPitchShareButton").hide();    
    $$("wzPitchShareSubmittedButton").hide();    
    
    
    // then, show by selection
    if (newValue == 'DISCO')
    {
        $$("wzPitchBlurb").setValue('');
        if (gMonitorStatus == 'offline') 
        {   
            webix_message({type: "error", text: "<b>REMINDER</b>:</br><br/>Your TrackSync is currently not running.<br/>TrackSync must be running in order to upload Tracks.<br/>", expire: 10000},6);
        }
        // show the DISCO things here
        $$("wzPitchDISCO").show();
        $$("wzPitchDISCOInstructs").show();
        $$("wzPitchDISCOInstructs2").show();
        $$("wzPitchDISCOButton").show();
        $$("wzPitchDISCOCreateButton").show();
        $$("wzPitchUploadCreateButton").hide();
        $$("wzPitchDISCOConfirm").show();
        
    }
    else if (newValue == 'Upload')
    {
        $$("wzPitchBlurb").setValue('');
        if (gMonitorStatus == 'offline') 
        {   
            webix_message({type: "error", text: "<b>REMINDER</b>:</br><br/>Your TrackSync is currently not running.<br/>TrackSync must be running in order to upload Tracks.<br/>", expire: 10000},6);
        } 
        // show the upload things here
        $$("wzPitchUpload").show();
        $$("wzPitchUploadInstructsHeader").show();
        $$("wzPitchUploadInstructs").show();
        $$("wzPitchUploadSavePitch").show();
        $$("wzPitchUploadButton").show();
        $$("wzPitchUploadCreateButton").show();
        $$("wzPitchDISCOCreateButton").hide();
        $$("wzPitchUploadConfirm").show();

    }
    else if (newValue == 'Email')
    {
        // show the email things here
        $$("wzPitchEmail").show();
        $$("wzPitchEmailButton").show();
        $$("wzPitchUploadCreateButton").hide();
        $$("wzPitchDISCOCreateButton").hide();
        $$("wzPitchEmailInstructsHeader").show();
        $$("wzPitchEmailInstructs").show();
        $$("wzPitchMessageSubject").show();
        $$("wzPitchBlurb").show();
        
        lcBlurb = gUser_Profile.Artist.Pitch_Email_Blurb;
        lcName = (gCurrTarget.Target.Target_First.length > 0) ? gCurrTarget.Target.Target_First : gCurrTarget.Target.Target_Company;
        lcProd = (isQuick == false) ? gNewPitch.NewPitch.Pitch_Project : 'your past projects';
        lcBlurb = lcBlurb.replace('#contact_first_name#',lcName)
        lcBlurb = lcBlurb.replace('#production_name#',lcProd)    
        apn = gUser_Profile.Artist.Phone_Number
        if ('US|CA|'.indexOf(gUser_Profile.Artist.Country) > -1) {apn = apn.substring(0,3) + ' ' + apn.substring(3,6) + ' ' + apn.substring(6,);}
        apn = '<!' + apn + '!>';
        lcBlurb = lcBlurb.replace('#phone_number#',apn)
        lcBlurb = lcBlurb.replace('#artist_email#','<!' + gUser_Profile.Artist.Email + '!>')
        lcBlurb = lcBlurb.replace('#artist_name#',gUser_Profile.Artist.First_Name + ' ' + gUser_Profile.Artist.Last_Name)
        $$("wzPitchBlurb").setValue(lcBlurb);
    }
    else if (newValue == 'Share')
    {
        $$("wzPitchBlurb").setValue('');
        // show the share things here
        $$("wzPitchShare").show();
        $$("wzPitchShareInstructsHeader").show();
        $$("wzPitchShareInstructs").show();
        $$("wzPitchShareButton").show();    
        $$("wzPitchShareSubmittedButton").show();    
        
    }  
}
// ------------------------------------------------------------ //
function setPitchTracks()
{
    pitchTracks = [];pitchTrackCurrID = ''; 
	dataWH.Pitch_Tracks.dataStore.sort("#PT_Track_Order#","asc","string");
    dataWH.Pitch_Tracks.dataStore.data.each(function(obj)
    {
        if (obj.Pitch_ID == gCurrPitch.Pitch.Pitch_ID)
        {
            pitchTracks.push({"Pitch_Track": obj} );
        }
    }); 
    
    $$("pitchTracksList").clearAll();
    $$("pitchTracksList").define("data",pitchTracks);
    $$("pitchTracksList").refresh();
}
// ------------------------------------------------------------ //
function showListPopup(control, callback) {
    var view = $$(control.id || control);
    var popup = view.getPopup();
    var body = popup.getBody();

    body.attachEvent("onItemClick", webix.once(function(id) {
        view.setValue(id);

        if (typeof(callback) === "function")
            callback();
    }));
    popup.show(view.getInputNode()); 
}
// ------------------------------------------------------------ //
async function pitchesFUPGoFinal()
{
    //console.log("pitchesFUPGoFinal():");
    webix.message({type: "debug", text: "Processing request...", expire: 4000});
    url = '/data_pitches/?mde=fuppitch&pid='+gCurrPitch.Pitch.Pitch_ID+'&seq='+seq();
    gForm_Data = {}
    gForm_Data.Pitch_ID = gCurrPitch.Pitch.Pitch_ID
    gForm_Data.Subject = $$("wzPitchMessageFUPSubject").getValue();
    gForm_Data.FollowUp = $$("pitchFollowUp").getValue();
    gForm_Data.Message = $$("wzPitchFUPBlurb").getValue();
    webix.html.triggerEvent($$("pitchWindowClose").getInputNode(), "MouseEvents", "click");
    response = await axios.post(url, gForm_Data)
    gRes = response;
    resData = response.data;
    if (resData.status == 'error')
    {
      webix.message({type: "error", text: resData.Message, expire: 10000});
    }
    else
    {
	if (resData.status == 'success')
	{
	    webix.message({type: "success", text: resData.Message, expire: 2000});
	    lcMsg = resData.Message;
	    
	    webix.alert({
		title: "Pitch Follow Up",
		text: lcMsg,
		type: "alert-success",
		width: 380,
	    }); 
	    
	    dataWH.Pitches.dataStore.updateItem(resData.Pitch.Pitch_ID,resData.Pitch); 
	    gCurrPitch['Pitch'] = dataWH.Pitches.dataStore.getItem(pitchesCurrID);
	    $$("Pitch.Pitch_Status").setValue(gCurrPitch.Pitch.Pitch_Status);
	    $$("Pitch.Pitch_Last_FUp").setValue(gCurrPitch.Pitch.Pitch_Last_FUp);
	    $$("Pitch.Pitch_Next_FUp").setValue(gCurrPitch.Pitch.Pitch_Next_FUp);
	    $$("Pitch.Pitch_Last_FUp").refresh();
	    $$("Pitch.Pitch_Next_FUp").refresh();
	    $$("Pitch.Pitch_Status").refresh();
	    setTimeout('webix.html.triggerEvent($$("btnPitchesSave").getInputNode(), "MouseEvents", "click");',500);
		      
	}
	else
	    {webix.message({type: "error", text: resData.Message, expire: 10000});}
    }
}
// ------------------------------------------------------------ //
function pitchesFUPGo()
{
    //console.log("pitchesFUPGo():");
    if ($$("pitchFollowUp").getValue().length == 0 || $$("wzPitchMessageFUPSubject").getValue().length == 0 || $$("wzPitchFUPBlurb").getValue().length == 0)
    {
	webix.message({type: "error", text: "Please complete all required fields first", expire: 8000});
	return;
    }
    
    webix.confirm(
     {
      title: "<span style='line-height:2.8;'>Please Confirm<br/></span>",
      text:"<span style='padding-top:20px;line-height:1.8;'>Send this Pitch Follow Up email now?</span><br/><br/>",
      ok: "Yes",
      cancel: "No",
      width:380,
    }).then(function(result)
    {    	           
       pitchesFUPGoFinal();   
    });     

}
// ------------------------------------------------------------ //
function pitchesFollowUp()
{

    if (refPitchTarget.Target.Target_Email.length == 0)
    {
	webix.message({type: "error", text: "<b>ERROR</b><br/><br/>The Target of this Pitch has <b>no email address</b>.  An email address is required in order to send out a follow-up email.<br/><br/>", expire: 12000});
	return;    
    }
    
    fup_inst = `Use the field below to edit and/or create your follow up message, then click <b>Send Follow Up</b>. 
    The playlist link leading to your selected tracks will be sent to <span title="##target_email##" style="font-weight:bold;color:purple;">##target_name##</span>, cc'd to your email address, 
    and the pitch record will be updated for the next follow up date. `;
    
    fup_inst = fup_inst.replace('##target_name##', refPitchTarget.Target.Target_Name)
    fup_inst = fup_inst.replace('##target_email##', refPitchTarget.Target.Target_Email);
    
    lcBlurb = gUser_Profile.Artist.Pitch_Followup_Blurb;
    lcBlurb = lcBlurb.replace('##sharelink##',gCurrPitch.Pitch.Full_Share_Link);
    lcBlurb = lcBlurb.replace('##contact_first_name##',refPitchTarget.Target.Target_First);
    lcBlurb = lcBlurb.replace('##artist_name##',gUser_Profile.Artist.First_Name + ' ' + gUser_Profile.Artist.Last_Name);
    lcBlurb = lcBlurb.replace('##artist_email##',gUser_Profile.Artist.Email);
    lcBlurb = lcBlurb.replace('##artist_phone##',gUser_Profile.Artist.Phone_Number);
    
    pitch_subject = 're: ' + gCurrPitch.Pitch.Pitch_Subject;
    
    varPitchFUP = 
      [
    {   view: "layout", id: "pitchWZFUPLayout",
	rows: [
       // ----------------------------------------------------------------- //
	{   id: "wzPitchEmailFUP", 
	    rows: [
		{   view: "template", id: "wzPitchEmailInstructsFUPHeader",    
		    height: 30,
		    template: "Follow up this Pitch via Email:",
		    borderless:1,
		    css:{"font-weight":"500"},
		},
		//{   cols: [
			//{   view: "template", id: "wzPitchEmailFUPInstructs",                                        
			    //height: 120,
			    //width: 480,
			    //template: fup_inst,
			    //borderless:1,
			    //css:{"color":"#666666", "line-height":"1.8", "padding-top":"10px"},
			//}, 
			//{   width: 20,
			    //borderless: 1,
			//},
			//{   view: "template",
			    //template: "<img src='/static/assets/images/wigit_100.png' height='90px',>",
			    //width: 100,
			    //borderless: 1,
			    //gravity: 5,
			//},
		    //]
		//},                                           
		{   view: "text",
		    inputWidth: ww*.34,
		    id: "wzPitchMessageFUPSubject",
		    inputHeight: 40,
		    required: true,
		    label: "Subject",
		    labelPosition: "top",
		    value: pitch_subject,
		    css:{"padding-top":"10px"},
		},
		{   view: "textarea",
		    inputWidth: ww*.34,
		    id: "wzPitchFUPBlurb",
		    height: hh*.4,
		    label: "Message",
		    required: true,
		    labelPosition: "top",
		    value: lcBlurb,
		    css:{"padding-top":"10px"},
		},
		
		{   view: "layout",
		    cols: [
			{   view: "richselect", id:"pitchFollowUp",
			    inputWidth: ww*.16,
			    inputHeight: 40,
			    width: ww*.17,
			    required: true,
			    label: "Follow Up In",
			    labelPosition: "top",		    
			    options: [
			     { id: "1 Day", value: "1 Day"},
			     { id: "2 Days", value: "2 Days"},
			     { id: "1 Week", value: "1 Week"},
			     { id: "2 Weeks", value: "2 Weeks"},
			     { id: "1 Month", value: "1 Month"},
			     { id: "3 Months", value: "3 Months"},
			     { id: "No Follow Up", value: "No Follow Up"},
			    ],                                                         
			},
			{   width: 20 },
			{   rows: [
				{   height: 22 },
				{   view: "button", id:"wzPitchEmailFUPButton",
				    width: ww*.16,
				    height: 40,
				    label: "Send Follow Up",
				    click: pitchesFUPGo,
				},
			    ]
			},
		    ]
		},
		{   height: 20 },
	    ]
	},   
	// ----------------------------------------------------------------- //
    
	{   width: 20 },
      ]
      }
      ];


  genPitchWindow('Pitch Follow Up',hh*0.78,ww*0.4,varPitchFUP,makeSquare=false,isModal=false,noPct=true,scrollBar=false,frmName="pitchWZFUPForm");
  
}
// ------------------------------------------------------------ //
function pitchesChecked()
{
    var checked = [];
    
    $$("pitchesTable").data.each(function(obj)
    {
        if (obj.chkPitch && obj.chkPitch == 'on') 
        {
            obj.Tag_Done = 0;
            checked.push(webix.copy(obj));
        }
    });    

    return checked;
}
// ------------------------------------------------------------ //
function pitchesDelete()
{
    marks = pitchesChecked(); 
    //console.log('marks = ', marks);
    if (marks.length == 0)
    {
        webix.message({type: "debug", text: "Please select the Pitches you wish to delete, first.", expire: 5000});
    } 
    else
    { 
        //gMarks = [];
        //gMarks.push(marks[0]);
        //marks = gMarks;
	
	gMarks = marks;
        title = 'Delete Pitches';
        delMessage = `
        
        Are you sure you want to DELETE the selected <b>##cnt##</b>&nbsp;Pitches?
        `;
        
        if (marks.length == 1) 
        {
            oCo = dataWH.Pitches.dataStore.getItem(marks[0].id);
            title = 'Delete Pitch';
  
            delMessage = 'Are you sure you want to DELETE this Pitch? <b><br/><br/>' + oCo.Pitch_Project + '</b><br/><br/>';
            if (oCo.Pitch_Access_Count > 0) {delMessage += 'This Pitch is <span style="color:darkRed;"><b>active</b></span> and has been accessed by outside parties <b><span style="color:purple;font-size:18px;">' + oCo.Pitch_Access_Count + '</span></b>&nbsp;times.'}
        }
        delMessage = delMessage.replace('##cnt##',marks.length+'');
        
        ConfirmIt(title=title, description=delMessage, txtYes='Ok', txtNo='Cancel', fncForYes='pitchesDeleteGo', 
        keyID=undefined, cancel_Msg=undefined, boxType='new');    
    }
}
// ------------------------------------------------------------ //
function setLicenseDetails(id, e, trg)
{
    //console.log("setLicenseDetails(id, e, trg):",id,e,trg);
    // update visibility, etc
    
    
    if (gCurrLicense.hasOwnProperty('License') == false) {return;}
    
    $$("licenseTrackName").setHTML(Spacer(gCurrLicense.License.Track.TIT2_TrackName));    
    
    if (gCurrLicense.License.PT_AddDoc.length > 0)
    {
	$$("licensesUpload2").define("disabled",true);
	$$("licensesUpload2").refresh();
	$$("licensesUploadButton2").define("disabled",true);
	$$("licensesUploadButton2").refresh();    
    }
    else
    {
	$$("licensesUpload2").define("disabled",false);
	$$("licensesUpload2").refresh();
	$$("licensesUploadButton2").define("disabled",false);
	$$("licensesUploadButton2").refresh();      
    }
    
    if (gCurrLicense.License.PT_Contract.length > 0)
    {
	$$("licensesUpload").define("disabled",true);
	$$("licensesUpload").refresh();
	$$("licensesUploadButton").define("disabled",true);
	$$("licensesUploadButton").refresh();    
    }
    else
    {
	$$("licensesUpload").define("disabled",false);
	$$("licensesUpload").refresh();
	$$("licensesUploadButton").define("disabled",false);
	$$("licensesUploadButton").refresh();      
    }   
    
    setTimeout("licensesShowDocs();",1200);

}
// ------------------------------------------------------------ //
function setPitchDetails(id, e, trg)
{
    //console.log("setPitchDetails(id, e, trg):",id,e,trg);
}
// ------------------------------------------------------------ //
async function pitchesDeleteGo()
{
    webix.message({type: "success", text: "<b>OK:</b>&nbsp;Processing request", expire: 500});
    gForm_Data = {'Pitches': gMarks}
    url = '/data_pitches/?mde=del_pitches&seq='+seq();
    response = await axios.post(url, gForm_Data)
    gRes = response;
    resData = response.data;
    if (resData.status == 'error')
    {
      webix.message({type: "error", text: resData.message, expire: 10000});
    }
    else
    {
        if (resData.status == 'success')
        {
            objList = resData.delsList;            
            webix.message({type: "success", text: resData.message, expire: 3000});
            for (ndx =0; ndx < objList.length; ndx++)
            {
                tObj = objList[ndx];
                dataWH.Pitches.dataStore.remove(tObj.id);     

		dataWH.Pitch_Tracks.dataStore.data.each(function(obj)
		{
		    if (obj.Pitch_ID == tObj.Pitch_ID)
		    {
			dataWH.Pitch_Tracks.dataStore.remove(obj.id); 
		    }
		});		
		catalogSetPitches();
            }
        }        
        else
            {webix.message({type: "error", text: resData.message, expire: 10000});}
                    
        setTimeout("pitchesRefresh();",2500);
    } 
}

// ------------------------------------------------------------ //
function tooltipDateTime(inDT,inMode)
{
    lcDate = '';
    if (inDT == null || inDT == '') {return '';}
    if (inMode == 'time')
    {
        lcDate = tConvert(inDT.substring(11,22));
    }
    else
    {
        lcDate = tDate(inDT) + ' ' + tConvert(inDT.substring(11,22));
    }
    return lcDate;
}
// ------------------------------------------------------------ //
gcon_html = '';
function Announcer(lcCall,lcEvent,inData)
{
    if (lcCall = 'pitch_share')
    {
        
        if (lcEvent == 'Initial Open')
        {        
	    if (isMac == true) {es = 100;} else {es = 60;}
            jsConfetti.addConfetti({emojis: confetti_30,emojiSize: es,confettiNumber: 120,});
            var html = `
            
                <div id="divAnnouncerWindow">                
                    <div style="height: 422px;text-align:center; padding: 40px;background-image: url('/static/assets/images/TrackStageBG.svg'); background-size: cover;">                    
                        <h1 style="color: #551a8b; line-height:1;">Pitch Playlist Opened</h1>
                        <div style="line-height: 2; font-size: 15px; text-align:left!important; padding-left: 20px;">
                            <b>Pitch:</b>  ##pitch_project##<br/>
                            <b>Target:</b>  ##target_name##<br/>
                            <b>Subject:</b>  ##pitch_subject##<br/>	                                        
                            <b>Sent Via:</b>  ##pitch_category##<br/>	                            
                        </div>
                    </div>
                </div>            
            `;
            
            html = html.replace('##pitch_project##', inData.Pitch_Project);
            html = html.replace('##target_name##', inData.Target_Name);
            html = html.replace('##pitch_subject##', inData.Pitch_Subject);
            html = html.replace('##pitch_category##', inData.Pitch_Category);
            gcon_html = html;
            $$("announcerMain").show();            
            setTimeout(`            
                $$("announcerContent").setHTML(gcon_html);
            `,700);                         
        }
        else if (lcEvent == 'Track Played')
        {
	    if (isMac == true) {es = 100;} else {es = 60;}
            jsConfetti.addConfetti({emojis: confetti_30,emojiSize: es,confettiNumber: 120,});
            var html = `
            
                <div id="divAnnouncerWindow">                
                    <div style="height: 422px;text-align:center; padding: 40px;background-image: url('/static/assets/images/TrackStageBG.svg'); background-size: cover;">                    
                        <h1 style="color: #551a8b; line-height:1;">Pitched Track Played</h1>
                        <div style="line-height: 2; font-size: 15px; text-align:left!important; padding-left: 20px;">
                            <b>Pitch:</b>  ##pitch_project##<br/>
                            <b>Target:</b>  ##target_name##<br/>
                            <b>Subject:</b>  ##pitch_subject##<br/>	                                        
                            <b>Sent Via:</b>  ##pitch_category##<br/>	                            
                            <b>Track Name:</b>  ##trackname##<br/>
                            <b>Run Length:</b>  ##runlength##<br/>
                            <b>Genre:</b>  ##genre##<br/>
                        </div>
                    </div>
                </div>            
            `;
            
            html = html.replace('##pitch_project##', inData.Pitch_Project);
            html = html.replace('##target_name##', inData.Target_Name);
            html = html.replace('##pitch_subject##', inData.Pitch_Subject);
            html = html.replace('##pitch_category##', inData.Pitch_Category);
            html = html.replace('##trackname##', inData.TIT2_TrackName);
            html = html.replace('##genre##', Spacer(inData.TCON_Genre));
            html = html.replace('##runlength##', formatMinSec(inData.Run_Length));
            gcon_html = html;
            $$("announcerMain").show();            
            setTimeout(`            
                $$("announcerContent").setHTML(gcon_html);
            `,700);         
        }
        else if (lcEvent == 'Track Downloaded')
        {
	    if (isMac == true) {es = 100;} else {es = 60;}
            jsConfetti.addConfetti({emojis: confetti_30,emojiSize: es,confettiNumber: 120,});
            var html = `
            
                <div id="divAnnouncerWindow">                
                    <div style="height: 422px;text-align:center; padding: 40px;background-image: url('/static/assets/images/TrackStageBG.svg'); background-size: cover;">                    
                        <h1 style="color: #551a8b; line-height:1;">Pitched Track Downloaded</h1>
                        <div style="line-height: 2; font-size: 15px; text-align:left!important; padding-left: 20px;">
                            <b>Pitch:</b>  ##pitch_project##<br/>
                            <b>Target:</b>  ##target_name##<br/>
                            <b>Subject:</b>  ##pitch_subject##<br/>	                                        
                            <b>Sent Via:</b>  ##pitch_category##<br/>	
                            <b>Track Name:</b>  ##trackname##<br/>
                            <b>Run Length:</b>  ##runlength##<br/>
                            <b>Genre:</b>  ##genre##<br/>                            
                            
                        </div>
                    </div>
                </div>            
            `;
            
            html = html.replace('##pitch_project##', inData.Pitch_Project);
            html = html.replace('##target_name##', inData.Target_Name);
            html = html.replace('##pitch_subject##', inData.Pitch_Subject);
            html = html.replace('##pitch_category##', inData.Pitch_Category);
            html = html.replace('##trackname##', inData.TIT2_TrackName);
            html = html.replace('##genre##', Spacer(inData.TCON_Genre));
            html = html.replace('##runlength##', formatMinSec(inData.Run_Length));            
            gcon_html = html;
            $$("announcerMain").show();            
            setTimeout(`            
                $$("announcerContent").setHTML(gcon_html);
            `,700);         
        }        
    }
}

function findHighestZIndex(elem)
{
  var elems = document.getElementsByTagName(elem);
  var highest = Number.MIN_SAFE_INTEGER || -(Math.pow(2, 53) - 1);
  for (var i = 0; i < elems.length; i++)
  {
    var zindex = Number.parseInt(
      document.defaultView.getComputedStyle(elems[i], null).getPropertyValue("z-index"),
      10
    );
    if (zindex > highest && zindex < 10000)
    {
      highest = zindex;
      elems[i].id;
    }
  }
  return highest;
}
// ------------------------------------------------------------ //
arr_Prod_All_KW = []
function makeProdKWS()
{
	arr_Prod_All_KW = []; x = 1;
	lstKW = genSub(gUser_Profile.Artist_Pref.Keywords_TCON_Genre);

	lstKW.forEach(function (item, index)
	{
		x += 1;
		try
		{
			arr_Prod_All_KW.push({"id": item.id, "value": item.value});
		}
		catch(err)
		{
			arr_Prod_All_KW.push({"id": item.id, "value": item.value});            
		}
	});
}
// ------------------------------------------------------------ //
function showUserResults(inData)
{
    //console.log(inData);
    out = `
	<div style="color:#351b5b;font-weight:500;font-size:18px;">##name##&nbsp;&nbsp;&nbsp;##fblink##</div>

	<hr/>
	<div style="color:#262626;font-weight:500;">##q1##</div>
	<div style="padding-bottom:10px;">##a1##</div>
	<hr/>
	<div style="color:#262626;font-weight:500;">##q2##</div>
	<div style="padding-bottom:10px;">##a2##</div>
	<hr/>
	<div style="color:#262626;font-weight:500;">##q3##</div>
	<div style="padding-bottom:10px;">##a3##</div>
	<hr/>
	<div style="color:#262626;font-weight:500;">##q4##</div>
	<div style="padding-bottom:10px;">##a4##</div>
	<hr/>
	<div style="color:#262626;font-weight:500;">##q5##</div>
	<div style="padding-bottom:10px;">##a5##</div>
	<hr/>
	<div style="color:#262626;font-weight:500;">##q6##</div>
	<div style="padding-bottom:10px;">##a6##</div>
	<hr/>
    `;
    
    out = out.replaceAll("##name##",inData.value);
    out = out.replaceAll("##q1##",gCurrSurvey.Survey_Data.Question_01);
    out = out.replaceAll("##a1##",inData.rdata.VSAnswer_01);
    
    out = out.replaceAll("##q2##",gCurrSurvey.Survey_Data.Question_02);
    out = out.replaceAll("##a2##",inData.rdata.VSAnswer_02);
    
    out = out.replaceAll("##q3##",gCurrSurvey.Survey_Data.Question_03);
    out = out.replaceAll("##a3##",inData.rdata.VSAnswer_03);
    
    out = out.replaceAll("##q4##",gCurrSurvey.Survey_Data.Question_04);
    out = out.replaceAll("##a4##",inData.rdata.VSAnswer_04);
    
    out = out.replaceAll("##q5##",gCurrSurvey.Survey_Data.Question_05);
    out = out.replaceAll("##a5##",inData.rdata.VSAnswer_05);
    
    out = out.replaceAll("##q6##",gCurrSurvey.Survey_Data.Question_06);
    out = out.replaceAll("##a6##",inData.rdata.VSAnswer_06);
    
    
    
    out = out.replaceAll("##fblink##",inData.rdata.FBLink);   
    
    $$("surveyResultsData").setHTML(out);
    setTimeout('$(".webix_icon.webix_sidebar_icon.fas.fa-comment-music").next().addClass("deep_purple_it");',20);
    setTimeout('$(".webix_icon.webix_sidebar_icon.fas.fa-ellipsis").next().addClass("deep_purple_it");',20);

}
// ------------------------------------------------------------ //
function loopVU()
{
    for (ndx =0; ndx < gVSUsers.length; ndx++)
    {
	vu = gVSUsers[ndx];
	$$("surveyResultsSidebar").select(vu.VSUser_Num);
    }
}
// ------------------------------------------------------------ //
function genVSMenu()
{
    mnu = [];
    for (ndx =0; ndx < gVSUsers.length; ndx++)
    {
	    vu = gVSUsers[ndx];
	    for (ndx2 =0; ndx2 < gSurvey_Results.length; ndx2++)
	    {
		    sd = gSurvey_Results[ndx2];
		    if (sd.VSUser_Num == vu.VSUser_Num)
		    {
			if (vu.VSUser_Status == 'Sent' || vu.VSUser_Status == 'Pending') {uic = 'fas fa-ellipsis purple_it';} else {uic = 'fas fa-comment-music purple_it';}
			mi = {id: vu.VSUser_Num, icon: uic, tooltip: vu.VSUser_Email, value: vu.VSUser_Name, rdata: sd, css:{"color":"#351b5b"}}; 
			mnu.push(mi);			
		    }
	    }
    }
    return mnu;
}

function tryIt()
{
    realtime = new Ably.Realtime({ authUrl: gcBaseURL+"ablyauth/", clientId: "tester"})
    realtime.connection.once("connected", () => {
      const user = realtime.auth.tokenDetails.clientId || "anonymous";
	
      const capability = realtime.auth.tokenDetails.capability;
      alert(
	`You are now connected to Ably \nUser: ${user}\nCapabilities: ${capability}`
      );
    }); 
    
}

// ------------------------------------------------------------ //
function knowledgeBaseURL()
{
 window.open('https://trackstage.ladesk.com/', '_blank');
}
// ------------------------------------------------------------- //
function cpShowStats()
{

    $$("projectsTot").setHTML("<span class='dbProjTot' style='font-weight:bold;font-size:16px;'>" + gProjectsActive + " </span> Projects");
    $$("pitchesYTDTot").setHTML("<span class='dbPitchYTD' style='font-weight:bold;font-size:16px;'>" + gPitchesYTD + " </span> Submitted");
    $$("newTracksTot").setHTML("<span style='font-weight:bold;font-size:16px;'>" + gNewTracksYTD + " </span> New");
    $$("conceptsTot").setHTML("<span style='font-weight:bold;font-size:16px;'>" + gConcepts + " </span> Concepts");
    $$("openOppsTot").setHTML("<span style='font-weight:bold;font-size:16px;'>" + gOpenOppos + " </span> Open");
    $$("pendingPitchesTot").setHTML("<span style='font-weight:bold;font-size:16px;'>" + gPitchesPending + " </span> Pitches");
    $$("unpitchedPitchesTot").setHTML("<span style='font-weight:bold;font-size:16px;'>" + gPitchesUnsubmitted + " </span> Unsubmitted");
    $$("licensesYTDTot").setHTML("<span style='font-weight:bold;font-size:16px;'>" + gLicensesYTD + " </span> Tracks");


    licenses_by_category = _.sortBy(licenses_by_category, 'orderNum');
    $$("licensesByCategory").clearAll();
    $$("licensesByCategory").parse(licenses_by_category);
    
    
    monthlyPitchLicense = _.sortBy(monthlyPitchLicense, 'monthNum');
    $$("monthlyPitchLicense").clearAll();
    $$("monthlyPitchLicense").parse(monthlyPitchLicense);
    
    projectsStartFinish = _.sortBy(projectsStartFinish, 'monthNum');
    $$("projectsStartFinish").clearAll();
    $$("projectsStartFinish").parse(projectsStartFinish);    
    
}


// ------------------------------------------------------------- //
async function setGoal(inType='pitches')
{
    if (inType == 'pitches') 
	{lcType = 'Pitches Submitted';treq = 'artist-ytdpitches';} 
    else 
	{lcType = 'New Tracks';treq = 'artist-ytdnewtracks';}

    lcTitle = "<span style='line-height:2.5;'><span style='color:purple;'>##type##</span> Goal</span>"
    lcTitle = lcTitle.replace('##type##',lcType);
    lcText = 'How many ##type## do you want to complete this year?';
    lcText = lcText.replace('##type##',inType.toProperCase());
    
    
    webix.prompt(
     {
      title: lcTitle,
      text: lcText,
      ok: "Ok",
      cancel: "Cancel",
      width: 412,
    }).then(function(result)
    {
	console.log('got', result);
	setGoalGo(inType,treq,result);	
	
    });

}
// ------------------------------------------------------------- //
async function setGoalGo(inType,treq,result)
{

    url = '/setval/?req='+treq+'&rid=' + gUser_Profile.Artist.Arti_ID + '&newval=' + result + '&seq=' + seq();
    pkge = {};
    response = await axios.post(url, pkge)

    gRes = response;
    resData = response.data; 

    if (resData.status == 'error')
    {
	webix.message({type: "error", text: "<b>Error:</b>&nbsp;&nbsp;"+resData.Message, expire: 10000});
    }
    else
    {
	if (resData.NewValue > 0) 
	{
	    if (inType == 'pitches') 
	    {
		gUser_Profile.Artist.YTD_Pitches_Goal = resData.NewValue;
		
	    }
	    else 
	    {
		gUser_Profile.Artist.YTD_NewTracks_Goal = resData.NewValue;
	    }
	    
	    $$("gage_TracksToGoal").config.maxRange = gUser_Profile.Artist.YTD_NewTracks_Goal;
	    $$("gage_TracksToGoal").setValue(gNewTracksYTD);
	    $$("gage_TracksToGoal").refresh();
	    
	    $$("gage_PitchesToGoal").config.maxRange = gUser_Profile.Artist.YTD_Pitches_Goal;
	    $$("gage_PitchesToGoal").setValue(gPitchesYTD);
	    $$("gage_PitchesToGoal").refresh();	    
	}
	webix.message({type: "success", text: "<b>Success:</b>&nbsp;&nbsp;"+resData.Message, expire: 3000});
    } 	

}
xxinMsg = {};md_tagsDone = []; 
// ------------------------------------------------------------- //
function tagFilesUpdate(inMsg)
{
     
    mdid = inMsg.data.pkge.Track_ID;
    for (ndx =0; ndx < catalogTags.length; ndx++)
    {
	    tt = catalogTags[ndx]; 
	    if (mdid == tt.id)
	    {
		    tt.Tag_Done = 1; 
		    md_tagsDone.push(tt.id);
	    }
    }		
    $$("catalogMetaTable").refresh();     
     
     xxinMsg = inMsg;
     if (xxinMsg.data.pkge.Tracks2Process > 0)
	{setTimeout("tagFilesShowProgress(mde='start', title='&nbsp;Processing Tracks', tracks=xxinMsg.data.pkge.Tracks2Process+'', images=xxinMsg.data.pkge.Images2Process+'')",200);}
    else
	{setTimeout("tagFilesShowProgress(mde='close');",1600);}

}
// ------------------------------------------------------------- //
async function batchMark(item='tags_pending', md_tagsDone)
{
    url = '/batchmark/?item=tags_pending_off&seq='+seq();
    data = {'md_tagsDone': md_tagsDone};
    response = await axios.post(url, data);
    gRes = response;
    resData = response.data;
    if (resData.status == 'Error')
    {
      webix.message({type: "error", text: resData.Message, expire: 10000});
    }
    else
    {
	// all good.
    }
}

lkbcc = false;
// ------------------------------------------------------------- //
function lagKBCardCheck()
{
    if ($(".webix_view.webix_window.webix_kanban_editor").is(":visible") == false && lkbcc == true)
    {
		lkbcc = false;
		setTimeout('x1x = gCurrProjectItem.id;tCard = $$("projectsKB").getItem(x1x);$$("projectsKB").showEditor(tCard);',600);
    }
    else
    {
    $$("loadingDataScreen").hide();
    }
	
	setTimeout(`
		if (ww > 1250 || ww < 940)
		{
			editor = $$("$kanbaneditor1");
			editor.config.width = 1200;
			editor.resize();
		}	
	`,80);
}
// ------------------------------------------------------------- //
function addPitchedLicense()
{
    fnd = '';
    $$("catalogTable").data.each(function(obj)
    { 
	if (obj.chkCatalog == 'on') {fnd = obj;}
    }); 
    
    if (fnd.hasOwnProperty('chkCatalog') == true)
    {
	console.log('fnd=',fnd);
	gotoTab('pitches');
	theTrack = dataWH.Catalog.dataStore.getItem(fnd.id);
	genAddLicenseWindow();
    }

}
// ------------------------------------------------------------- //
function addPitchAction(inAction)
{
    inAction = inAction.trim();
    $$("cmenuPALF").hide();
    
    if (inAction == 'Mark Track Forwarded')
    {
	addPitchedMarkItGo(inAction);
    }
    else if (inAction == 'Mark Track Signed')
    {
	addPitchedMarkItGo(inAction);    
    }
    else if (inAction == 'Add License to Track')
    {
	addPitchedLicenseGo();
    }    
}
gtActionType = '';mmde = '';
// ------------------------------------------------------------- //
function addPitchedMarkItGo(inAction)
{
    tmpPT = {};
    lpt = $$("catalogPitchesList").getSelectedId();
    for (ndx =0; ndx < catalogTrackPitches.length; ndx++)
    {
	tt = catalogTrackPitches[ndx]; 
	if (tt.id == lpt.id)
	{
	    tmpPT = tt;
	    break;
	}
    }
    
    if (tmpPT.hasOwnProperty('Track_Pitch'))
    {
	console.log('found',tmpPT);
	trk = tmpPT.Track_Pitch;

	// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ //
	if (inAction.toLowerCase().indexOf('signed') > -1)
	{	    
	    gtActionType = 'signed';
	    title = 'Mark Track as Signed'; 
	    if (trk.Track_Signed == true) {mmde = 'UN-Mark'; title = 'UN-Mark Track as Signed'} else {mmde = 'Mark';}
	    addMessage = mmde + '&nbsp;the Track... <br/><br/><span style="color:purple;font-weight:Bold;">' + trk.TIT2_TrackName + '</span><br/><br/>&nbsp;with&nbsp;<br/>' + tmpPT.Track_Pitch.Target.Target_Name;
	    gtObj = trk;
	    ConfirmIt(title=title, description=addMessage, txtYes='Ok', txtNo='Cancel', fncForYes='addPitchedMarkItSubmit', 
	    keyID=undefined, cancel_Msg=undefined, boxType='new');  	
	}
	// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ //	
	else if (inAction.toLowerCase().indexOf('forwarded') > -1)
	{	    
	    gtActionType = 'forwarded';
	    title = 'Mark Track as Forwarded'; 
	    if (trk.Track_Forwarded == true) {mmde = 'UN-Mark';title = 'UN-Mark Track as Forwarded';} else {mmde = 'Mark';}
	    addMessage = mmde + '&nbsp;the Track... <br/><br/><span style="color:purple;font-weight:Bold;">' + trk.TIT2_TrackName + '</span><br/><br/>&nbsp;with&nbsp;<br/>' + tmpPT.Track_Pitch.Target.Target_Name;
	    gtObj = trk;
	    ConfirmIt(title=title, description=addMessage, txtYes='Ok', txtNo='Cancel', fncForYes='addPitchedMarkItSubmit', 
	    keyID=undefined, cancel_Msg=undefined, boxType='new');  	
	}
	// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ //		

    }
    else
    {
	webix.message({type: "error", text: 'Unable to select Pitched Track for action...', expire: 7000});
    }
}
// ------------------------------------------------------------ //
async function addPitchedMarkItSubmit()
{
    url = '/data_pitch_tracks/?mde=marktrack&seq=' + seq();
    
    pkge = {'Pitch_Track': gtObj, 'Action_Type': gtActionType};
    response = await axios.post(url, pkge)
    gRes = response;
    resData = response.data; 
    if (resData.status == 'Error')
    {
      webix.message({type: "error", text: resData.Message, expire: 10000});
    }
    else
    {
	// update the pitch_track in the dataWH
	dataWH.Pitch_Tracks.dataStore.updateItem(resData.newPitchTrackObj.id, resData.newPitchTrackObj);
	catalogSetPitches();
	if (mmde == 'Mark') {webix.message({type: "success", text: "<b>Success</b>&nbsp;This Track has been successfully Marked.", expire: 5000});goCrazy();}
	else {webix.message({type: "success", text: "<b>Success</b>&nbsp;This Track has been successfully UN-Marked.", expire: 5000});}
    }
}
// ------------------------------------------------------------- //
function addPitchedLicenseGo()
{
    tmpPT = {};
    lpt = $$("catalogPitchesList").getSelectedId();
    for (ndx =0; ndx < catalogTrackPitches.length; ndx++)
    {
	tt = catalogTrackPitches[ndx]; 
	if (tt.id == lpt.id)
	{
	    tmpPT = tt;
	    break;
	}
    }
    
    if (tmpPT.hasOwnProperty('Track_Pitch'))
    {
	console.log('found',tmpPT);
	trk = tmpPT.Track_Pitch;
	if (trk.PT_Status == 'Licensed')
	{
	    webix.message({type: "error", text: 'Oops.  That Pitched Track has already <b>Licensed</b>.', expire: 10000});
	    return;
	}
	// go...
	title = 'Add Track License'; 
	addMessage = 'License the Track... <br/><br/><span style="color:purple;font-weight:Bold;">' + trk.TIT2_TrackName + '</span><br/>&nbsp;to&nbsp;<br/>' + tmpPT.Track_Pitch.Target.Target_Name + '?';
	gtObj = trk;
	ConfirmIt(title=title, description=addMessage, txtYes='Ok', txtNo='Cancel', fncForYes='addPitchedLicenseSubmit', 
	keyID=undefined, cancel_Msg=undefined, boxType='new');  
    }
    else
    {
	webix.message({type: "error", text: 'Unable to select Pitched Track for licensing...', expire: 7000});
    }
}
// ------------------------------------------------------------ //
function waitNoBlock()
{
    if (gSessStat > -1) {console.log('SUCCESS: gSessStat is ' + gSessStat + 'tries = ' + gSessTry + '');return;}
    gSessTry += 1;
    if (gSessTry > 20) {console.log('FAILED: gSessStat is ' + gSessStat + 'tries = ' + gSessTry + '');return;}
    setTimeout('waitNoBlock();',500);
}
// ------------------------------------------------------------ //
function waitBlocked(ms){
   var start = new Date().getTime();
   var end = start;
   while(end < start + ms) {
   
   if (gSessStat > -1) {console.log('gSessStat is ' + gSessStat);return;}
     end = new Date().getTime();
  }
}
gSessStat = -1;gSessTry = 0;
// ------------------------------------------------------------ //
async function isSessUp()
{
    url = '/issessup/?aj=y&seq=' + seq();
    pkge = {};
    try
    {response = await axios.post(url, pkge)}
    catch(err) 
    {
	if (err.response.status == 502) 
	{
	    setTimeout('window.location = "/";',5200);
	    webix.message({type: "error", text: '<b>System Unavliable</b><br/>TrackStage is currently unavailable.  Please try again in a few minutes.' , expire: 5000}); 
	    gSessStat = 0;
	    return gSessStat;
	}
	gSessStat = 0;
	return gSessStat;
    }

    gRes = response;
    resData = response.data; 
    if (response.status == 200 && response.data.indexOf("meta http-equiv") > -1) 
    {
	setTimeout('window.location = "/";',4200);
	webix.message({type: "error", text: '<b>Session Expired</b><br/>Your session was closed due to no activity.  Please login again.' , expire: 4300});  
	gSessStat = 0;
	return gSessStat;
    }
 
    
    if (resData.status == 'Error')
    {
      webix.message({type: "error", text: resData.Message, expire: 10000});
      gSessStat = 0;
      return gSessStat;
    }
    else
    {
	gSessStat = 1;
	return gSessStat;
    }
}
// ------------------------------------------------------------ //
async function addPitchedLicenseSubmit()
{
    url = '/data_pitch_tracks/?mde=licensetrack&seq=' + seq();
    
    pkge = {'Pitch_Track': gtObj, 'Manual_License': gManualLicense};
    response = await axios.post(url, pkge)
    gRes = response;
    resData = response.data; 
    if (resData.status == 'Error')
    {
      webix.message({type: "error", text: resData.Message, expire: 10000});
    }
    else
    {
	// update the pitch_track in the dataWH
	dataWH.Pitch_Tracks.dataStore.updateItem(resData.newPitchTrackObj.id, resData.newPitchTrackObj);
	catalogSetPitches();
	// go to Licenses .. and open it
	gotoModule('Licenses');
	setLicensedTracks();
	setTimeout(`
	    gtrec = resData.newPitchTrackObj.PT_ID;         
	    licensesCurrID = gtrec; 
	    gCurrLicense['License'] = dataWH.Pitch_Tracks.dataStore.getItem(licensesCurrID);
	    refPitch = dataWH.Pitches.dataStore.getItem(gCurrLicense['License'].Pitch_ID);
	    refPitchTargetProd = findPitchRef(refPitch.Prod_ID,'prod');
	    refPitchTarget = findPitchRef(refPitchTargetProd.TargetProd.Target_ID,'target');		
	    $$("licensesTable").select(licensesCurrID);		
	`,800);
	
	setTimeout('$$("licensesTable").select(gCurrLicense.License.id);',1200);
	setTimeout("gotoLicensesTab('licensesInfo');",1500);
	
	setTimeout('$$("licensesEditForm").clearValidation();$$("licensesEditForm").clear();',1600);
	setTimeout('$$("licensesEditForm").parse(gCurrLicense);',1700);
	setTimeout(`
	    $$("License.Pitch.Target_Name").setValue(gCurrLicense.License.Target.Target_Name);
	    $$("License.Pitch.Prod_Title").setValue(gCurrLicense.License.Production.Prod_Title);
	`,1900);
	setTimeout('setLicenseDetails();',1800); 
	goCrazy();
    }
}
// ------------------------------------------------------------ //
function catalogTagsPendingTip(updatedTrack)
{
    if (gWasTags_Pending == 'N' && updatedTrack.Tags_Pending == 'Y')
    {
	//console.log("ready to show tags pending tip");
	    //lcWarning = 
	    //`
	    //<table>
		//<tr>
		    //<td>
		    //<img src="/static/assets/images/wigit_100.png" width="60px;"> 
		    //</td>
		    //<td style="padding-left:10px">
		    //When a Track in your Catalog is hihighted orange, it means there are metadata changes that need to be written to the track file on your hard drive.
		    //</td>
		//</tr>
	    //</table>
	    //`;
	    
	    //ph = 120; pw = 230;
	    //setTimeout("genSmallPopup('btnCollabInvite',lcWarning,ph,pw);",1200);	    
	    
    }
}
// ------------------------------------------------------------ //
function checkForCollabs()
{
    if (gCurrProjectItem.Collaborators.length > 0 && gCurrProjectItem.Other_Collabs != '|')
    {
	for (ndx =0; ndx < gCurrProjectItem.Collaborators.length; ndx++)
	{
	    col = gCurrProjectItem.Collaborators[ndx]; 	
	    if (col.eid != gUser_Profile.Artist.Arti_ID) {return true;}
	}	
    }

    return false; 	
}
// ------------------------------------------------------------ //
function userHold(mde='show')
{
    
    if (mde == 'show')
    {
	if (pitchesCurrTab == '') {return;}
	
	if (pitchesCurrTab == 'pitchesInfo') 
	{
	    th = $$("pitchesTabInfo").$height;
	    tw = $$("pitchesTabInfo").$width;
	    
	} else 
	{
	    th = $$("pitchesTabTracks").$height;
	    tw = $$("pitchesTabTracks").$width;
	}
	ofs = $(".webix_icon_btn.far.fa-arrow-to-right").offset();
	tw = tw - 4;
	th = th + 50;
	tl = ofs.left + 60;
	tt = ofs.top + 10;
	th = th - 60;
	
	$$("userHold").define("left",tl);
	$$("userHold").define("height",th);
	$$("userHold").define("top",tt);
	$$("userHold").define("width",tw);
	$$("userHold").show();
	$(".userHoldClass").css("opacity",0.64);
	$$("userHold").resize();
    }
    else
    {
	$$("userHold").hide();
    }
}
// ------------------------------------------------------------ //
function jpprocResponse(response){
  console.log (response);
}


function tryHint()
{

    if ($$("hint") !== undefined)
    {
        $$('hint').hide();$$('hint').destructor();
    }

    webix.ui({
	view: "hint",
	id: "hint",
	steps: [
	    {
		el: "catalogSearchFld",
		title: "Search Field",
		text: "Click here to check out regular flights",
		event:"click"
	    },
	    {
		el: "catalogFilterForm",
		title: "Filter buttons",
		text: "Click here to take a look at all flights info",
		event:"click"
	    },
	    {
		el: "userBtn",
		eventEl: "button",
		title: "User Profile",
		text: "Fill in the form and press 'enter' to book your flight",
		event:"enter"
	    },
	    {
		el: "mainSidebar",
		eventEl: "button",
		title: "Side menu",
		text: "Fill in the form and press 'enter' to book your flight",
		event:"enter"
	    },
	]
    });   

}
// ------------------------------------------------------------------ //
function getBriefByKey(inKey)
{
    out = null;
    if (isNaN(parseInt(inKey)) == false && parseInt(inKey) != 0) {inKey = 'BJ' + inKey};
    for (ndx =0; ndx < cat_refs.Briefs.length; ndx++)
    {
	brf = cat_refs.Briefs[ndx]; 	
	if (brf.Brief_Key.toLowerCase() == inKey.toLowerCase())
	{
	    if (brf.Brief_Category.indexOf('hardto_classify_specialty_novelty') > -1) {brf.Brief_Category = brf.Brief_Category.replaceAll('hardto_classify_specialty_novelty|','hard_to_classify|specialty|novelty|');}
	    if (brf.Brief_Category.indexOf('rap_hip_hop') > -1) {brf.Brief_Category = brf.Brief_Category.replaceAll('rap_hip_hop','rap|hip_hop');}
	    if (brf.Brief_Category.indexOf('christmas_holiday') > -1) {brf.Brief_Category = brf.Brief_Category.replaceAll('christmas_holiday|','christmas|holiday|');}
	    if (brf.Brief_Category.indexOf('indie_alternative|') > -1) {brf.Brief_Category = brf.Brief_Category.replaceAll('indie_alternative|','indie|alternative|');}
	    if (brf.Brief_Category.indexOf('singer_songwriter|') > -1) {brf.Brief_Category = brf.Brief_Category.replaceAll('singer_songwriter|','Singer-Songwriter|');}
	    if (brf.Brief_Category.indexOf('world_music|') > -1) {brf.Brief_Category = brf.Brief_Category.replaceAll('world_music|','World-Music|');}
	    if (brf.Brief_Category.indexOf('rb_soul|') > -1) {brf.Brief_Category = brf.Brief_Category.replaceAll('rb_soul|','r&b|soul|');}
	    
	    
	    if (brf.Brief_Type == 'TAXI')
	    {
		lstGE = brf.Brief_Category.split('|');
		ges = '';
		for (ndx2 =0; ndx2 < lstGE.length; ndx2++)
		{
		    ge = lstGE[ndx2]; 
		    if (ge.length > 0)
		    {
			ge2 = ge.replaceAll('_',' ');
			ge2 = ge2.toProperCase();
			ge2 = ge2.replaceAll('R&b','R&B');
			ge2 = ge2.replaceAll('Hard To Classify','Hard-To-Classify');
			ge2 = ge2.replaceAll('World-music','World-Music');
			ge2 = ge2.replaceAll('Singer-songwriter','Singer-Songwriter');
			ges = ges + ge2 + ', ';
		    }
		}
		
		if (ges.endsWith(', ') == true) {ges = ges.substring(0,ges.length-2);}
		brf.Brief_Genre = ges;
	    }
	    else
	    {
		// all ok for broadjam
	    }
	    
	    if (brf.Brief_Deadline != null)
	    {
		brf.Brief_Deadline = brf.Brief_Deadline.replaceAll(' 11:59:00',' 23:59:00')
	    }
	    out = brf
	    break;
	}
    }
    return out
}

 // ------------------------------------------------------------ //
function artistsRefresh()
{
    doneSetUp = true;
    dataWH.Artists.dataStore.clearAll();
    url = "/data_artists/";
    dataWH.Artists.dataStore.load(url);
	setTimeout('loadUserProfileData();',2500);
	setTimeout('afflShowTots();',2800); 

}
 // ------------------------------------------------------------ //

// ------------------------------------------------------------------ //
    
	//tryHint();
	//$$("hint").start();
	//return;


// ----------------------------------------------------------------- //
function genSplit_Presets()
{
    plSpl = gUser_Profile.Artist.Splits_Presets; 
    
    //plSpl = `Splits One~Splits Two|{"id":12920,"fn":"Fred","mn":"Q.T.","ln":"Jones","co":"This Company Inc","ph":"111-222-3333","em":"sbarker@eee.com","wr":50,"ma": 50,"os":true,"pr":"BMI","ip":"12322u28"}^
    //{"id":23988,"fn":"Bob","mn":"W","ln":"Smith","co":"ABC Inc","ph":"444-222-3333","em":"fred@eerer.com","wr":100,"ma": 100,"os":false,"pr":"ASCAP","ip":"a3233-30"}`

    preSplList = plSpl.split('|');gout = '';
	
    if (preSplList.length == 1 && preSplList[0] == '')
    {
	sp_presets = '';sp_presets2 = '';sp_presets3 = ''; 
    }
    else
    {
	pSplitems = preSplList[1];
	pSplItemsList = pSplitems.split('=');
	spl_presets = new Map();
	pgSpl = preSplList[0];
	pSplgrps = pgSpl.split('~');
	for (ndx=0; ndx < pSplgrps.length; ndx++)
	{
	    grpSpl = pSplgrps[ndx].trim();
	    gout += "'" + grpSpl + "'~";
	    try {spl_presets.set(grpSpl,pSplItemsList[ndx]);} catch(err) {a=1;}
	}
	if (gout.endsWith('~') == true) {gout = gout.substring(0,gout.length-1);}
	sp_presets = genSplitsSub(gout,'sp_presets');
	sp_presets2 = genSplitsSub(gout,'sp_presets2');
	sp_presets3 = genSplitsSub(gout,'sp_presets3');
    }
    
    var menu_data_splits_toolbar = 
    [

	{ id:"sp12", value: "My Saved Split Groups", width: true, submenu:
	    [
		{value: "Insert Split Group", autowidth:true, config: {scroll: true, height: 500, width: 200}, submenu: sp_presets},
		{ $template:"Separator" },
		{value: "Create New Split Group", autowidth:true, config: {scroll: true, height: 500, width: 200},},
		{value: "Delete Split Group", autowidth:true, config: {scroll: true, height: 500, width: 200}, submenu: sp_presets3},
		
	    ]                                      
	},        

    ];

    return menu_data_splits_toolbar;
}
// ----------------------------------------------------------------- //
function genSplitsSub(fld,f1='',f2='')
{
    out = [];
    if (f1 == 'sp_presets' || f1 == 'sp_presets2' || f1 == 'sp_presets3') {arr = fld.split('~');} else {arr = fld.split(',');}
    
    //if (f1 == 'presets') {a=1;}
    arr.forEach(function (item, index)
    {
	if (f1 == '' || f1 == 'sp_presets' || f1 == 'sp_presets2' || f1 == 'sp_presets3')
	{
	    if (f1 == '')
	    {
		out.push({"id": item.replaceAll("'",""), "value": item.replaceAll("'","")});
	    }
	    else
	    {
		if (f1 == 'sp_presets') 
		{
		
		    out.push({"id": 'preset->' + item.replaceAll("'",""), "value": item.replaceAll("'","").replaceAll(",",", ")});
		}
		if (f1 == 'sp_presets2') 
		{
		    out.push({"id": 'preset-remove->' + item.replaceAll("'",""), "value": item.replaceAll("'","").replaceAll(",",", ")});
		}
		if (f1 == 'sp_presets3') 
		{
		    out.push({"id": 'preset-delete->' + item.replaceAll("'",""), "value": item.replaceAll("'","").replaceAll(",",", ")});
		}
	    }
	}
	else
	{
	    item = item.replaceAll("'","");
	    if (item.substring(0,1).toLocaleLowerCase() >= f1.toLocaleLowerCase() && item.substring(0,1).toLocaleLowerCase() <= f2.toLocaleLowerCase())
	    {
		out.push({"id": item, "value": item});
	    }
	}       
	
    });
    
    return out;
}
gSplits = [];
// ------------------------------------------------------------ //
function Create_Splits_Group()
{
    if (catalogPartsRights.length == 0) 
    {
	webix.message({type: "error", text: "<b>ERROR:</b>&nbsp;There are no Rights records to create from", expire: 7000});
	return;
    }
    
    gSplits = catalogPartsRights;
    if (gSplits.length == 1) {lcText = "Are you sure you want to create a Splits Group from this Rights record?"}
    else {lcText = "Are you sure you want to create a Splits Group from these&nbsp;<br/><b><span style='font-size:20px;color:purple;'>" + gSplits.length + "</span></b>&nbsp;Rights records?"}
    
    webix.confirm(
     {
      title: "<span style='line-height:2.5;'>Create a NEW Splits Group</span>",
      text: lcText,
      ok: "OK",
      cancel: "Cancel",
      width:380,
    }).then(function(result)
    {
        Create_Splits_GroupName();
    });
    
}
// ------------------------------------------------------------ //
function Create_Splits_GroupName()
{
    webix.prompt(
     {
      title: "Add/Update a Splits Group",
      text: "Splits Group Name:",
      ok: "Ok",
      cancel: "Cancel",
      input: {
	required: true,
	placeholder: "....",
      },
      width:380,
    }).then(function(result)
    {
	Create_Splits_GroupGo2(result);
	
    });                    	
}
// ------------------------------------------------------------ //
function Create_Splits_GroupGo(inNewName)
{
    if (inNewName.length == 0) {return;}    
    webix.confirm(
     {
      title: "<span style='line-height:2.5;'>Remove Existing Records</span>",
      text: "Do you want to DELETE all existing records first?",
      ok: "OK",
      cancel: "Cancel",
      width:380,
    }).then(function(result)
    {
        Create_Splits_GroupGo2(true,inNewName);
    })
    .fail(function(){
	Create_Splits_GroupGo2(false,inNewName);
    });    
}
// ------------------------------------------------------------ //
function makeSplitItem(inRec)
{
    RT = inRec.Right_Holder;
    jo = {"id": RT.Cont_ID, "fn": RT.First_Name, "mn": RT.Middle_Name, "ln": RT.Last_Name, "co": RT.Company_Name, "ph": RT.Holder_Phone, "em": RT.Holder_Email, "wr": RT.Cowriting_Pct, 
	 "ma": RT.Master_Pct, "os": RT.One_Stop, "pr": RT.PRO_Name, "ip": RT.IPI_Num, "fn": RT.First_Name};
	 
    out = JSON.stringify(jo)
    return out;
}
// ------------------------------------------------------------ //
async function Create_Splits_GroupGo2(inName)
{
    inName = inName.replaceAll('^','').replaceAll('~','').replaceAll('|','').replaceAll("'","");
    // Create a splits group dataaset for the rights records
    lstRecs = gSplits;
    grpList = '';
    for (ndx=0; ndx < lstRecs.length; ndx++)
    {
	pItem = lstRecs[ndx];  
	splitItem = makeSplitItem(pItem);
	grpList += '^' + splitItem;
	
    }
    if (grpList.startsWith('^') == true) {grpList = grpList.substring(1);}
    cp = gUser_Profile.Artist.Splits_Presets; 
    if (cp == '')
    {
	fnd = false;
	currNames = '';currItems = [];
    }
    else
    {
	cpl = cp.split('|');
	currNames = cpl[0];
	currItems = cpl[1];
	fnd = false;    
	chkLst = currNames.split('~');
	chkItems = currItems.split('=');
	for (ndx=0; ndx < chkLst.length; ndx++)
	{
	    chkName = chkLst[ndx].trim(); 
	    if (chkName == inName)
	    {
		// update item list for found group name
		fnd = true;
		chkItems[ndx] = grpList;
		break;
	    }
	}
    }
    if (fnd == false)
    {
	currNames += '~' + inName;
	if (currNames.startsWith('~')) {currNames = currNames.substr(1);}
	currItems += '=' +  grpList;
	if (currItems.startsWith('=')) {currItems = currItems.substr(1);}
	
	gUser_Profile.Artist.Splits_Presets = currNames + '|' + currItems; 
    }
    else
    {
	currItems = chkItems.join('^');
	gUser_Profile.Artist.Splits_Presets = currNames + '|' + currItems;
    }

    menu_data_splits_toolbar = genSplit_Presets(); 
    $$("splits_category_menu").clearAll();
    $$("splits_category_menu").parse(menu_data_splits_toolbar);
    $$("splits_category_menu").refresh();   
    
    webix.message({type: "success", text: "<b>OK:</b>&nbsp;Processing request", expire: 5000});
    gForm_Data = {'Splits': gSplits}    
    
    //  submit it to server
    url = '/data_catalog/?mde=storesplitspresets&seq=' + seq();
    pkge = {'Arti_ID': gUser_Profile.Artist.Arti_ID, 'splits_presets': gUser_Profile.Artist.Splits_Presets};
    response = await axios.post(url, pkge)    
    
    gRes = response;
    resData = response.data;
    if (resData.status == 'error')
    {
      webix.message({type: "error", text: resData.message, expire: 10000});
    }
    else
    {
        if (resData.status == 'success')
        {
            webix.message({type: "success", text: resData.message, expire: 3000});
        }        
        else
            {webix.message({type: "error", text: resData.message, expire: 10000});}
    } 
}
gSplitsCheck = 'no';
// -------------------------------------------------------------------- //
function scbv()
{
    if ($("#chkRemoveFirst").is(':checked')) {gSplitsCheck = 'yes';} else {gSplitsCheck = 'no';}
}
// -------------------------------------------------------------------- //
function presetsSplitsInsertGroup(inName,presetItems)
{
    gSplitsCheck = 'no';
    lcCheck = "Delete all existing records first?&nbsp;&nbsp;<input id='chkRemoveFirst' onChange='scbv();' type='checkbox'/>"
    lcText = "Are you sure you want to INSERT this splits group:<br/><br/><b><span style='color:purple;'>" + inName + "</span></b><br/><br/>&nbsp;" + lcCheck + "<br/>";
    webix.confirm(
     {
      title: "<span style='line-height:2.5;'>Insert Splits Group</span>",
      text: lcText,
      ok: "OK",
      cancel: "Cancel",
      width:380,
    }).then(function(result)
    {
        presetsSplitsInsertGroupGo(inName,presetItems)
    });
}
// -------------------------------------------------------------------- //
async function presetsSplitsInsertGroupGo(inName,presetItems)
{
    webix.message({type: "success", text: "<b>OK:</b>&nbsp;Processing request", expire: 5000});
    gForm_Data = {'Splits': gSplits}    
    
    //  submit it to server
    url = '/data_catalog/?mde=insertsplits&seq=' + seq();
    pkge = {'Arti_ID': gUser_Profile.Artist.Arti_ID, 'splits_presets': presetItems, 'delFirst': gSplitsCheck, 'Track_ID': gCurrTrack.Track_ID};
    response = await axios.post(url, pkge)    
    
    gRes = response;
    resData = response.data;
    if (resData.status == 'error')
    {
      webix.message({type: "error", text: resData.message, expire: 10000});
    }
    else
    {
        if (resData.status == 'success')
        {
            webix.message({type: "success", text: resData.message, expire: 3000});
	    dataWH.Participants.dataStore.clearAll();
	    dataWH.Participants.dataStore.parse(resData.allParts);
	    setParticipants();	    
	    $$("rightsList").clearAll();
	    $$("rightsList").define("data",catalogPartsRights);
	    $$("rightsList").refresh();  
	    setTimeout(`webix.UIManager.setFocus($$('rightsList'));`,600);
        }        
        else
            {webix.message({type: "error", text: resData.message, expire: 10000});}
    }     
}
// -------------------------------------------------------------------- //
function add2Splits(inItem)
{
    isPreset = false;
    if (inItem.startsWith('preset->'))
    {
	isPreset = true;
	inItem = inItem.replaceAll('preset->','');
	presetItems = spl_presets.get(inItem);
	presetsSplitsInsertGroup(inItem,presetItems);
    }
    else if (inItem.startsWith('preset-delete->')) 
    {
	isPreset = true;
	inItem = inItem.replaceAll('preset-delete->','');
	presetItems = spl_presets.get(inItem);
	
	presetsSplitsDeleteGroup(inItem);
    }    
}
// -------------------------------------------------------------------- //
function presetsSplitsDeleteGroup(inName)
{
    lcText = "Are you sure you want to REMOVE this group:<br/><br/><b><span style='color:purple;'>" + inName + "</span></b><br/><br/>";
    webix.confirm(
     {
      title: "<span style='line-height:2.5;'>Remove Splits Group</span>",
      text: lcText,
      ok: "OK",
      cancel: "Cancel",
      width:380,
    }).then(function(result)
    {
        presetsSplitsDeleteGroupGo(inName)
    });
}
// -------------------------------------------------------------------- //
async function presetsSplitsDeleteGroupGo(inName)
{
    inName = inName.replaceAll('^','').replaceAll('~','');
    cp = gUser_Profile.Artist.Splits_Presets; 
    if (cp == '')
    {
	return;
    }
    else
    {
	cpl = cp.split('|');
	currNames = cpl[0];
	currItems = cpl[1];
	fnd = false;    
	chkLst = currNames.split('~');
	chkItems = currItems.split('^');
	newItems = '';newNames = '';
	for (ndx=0; ndx < chkLst.length; ndx++)
	{
	    chkName = chkLst[ndx].trim(); 
	    if (chkName == inName)
	    {
		// drop the entire group 
	    }
	    else
	    {
		newNames += '~' + chkName;
		newItems += '^' + chkItems[ndx];
	    }
	}
	if (newNames.startsWith('~')) {newNames = newNames.substr(1);}
	if (newItems.startsWith('^')) {newItems = newItems.substr(1);}
    }

    gUser_Profile.Artist.Splits_Presets = newNames + '|' + newItems; 
    if (gUser_Profile.Artist.Splits_Presets == '|') {gUser_Profile.Artist.Splits_Presets = '';}
    menu_data_splits_toolbar = genSplit_Presets();
    $$("splits_category_menu").clearAll();
    $$("splits_category_menu").parse(menu_data_splits_toolbar);
    $$("splits_category_menu").refresh();   
    
    //  submit it to server
    url = '/data_catalog/?mde=storesplitspresets&seq=' + seq();
    pkge = {'Arti_ID': gUser_Profile.Artist.Arti_ID, 'splits_presets': gUser_Profile.Artist.Splits_Presets};
    response = await axios.post(url, pkge)

    gRes = response;
    resData = response.data; 

    if (resData.status == 'error')
    {
	webix.message({type: "error", text: "<b>Error:</b>&nbsp;&nbsp;"+resData.message, expire: 12000});
    }
    else
    {  
	webix.message({type: "success", text: "<b>Success:</b>&nbsp;&nbsp;"+resData.message, expire: 12000});
    }      
}
// -------------------------------------------------------------------- //
function CleanUS(inVal)
{
    out = inVal.replaceAll('_',' ');
    return out;
}
// -------------------------------------------------------------------- //
function announceShow(openMe=true)
{
    if (openMe == "trackstageAnnouncements") {openMe = true;}
    announceBuild(openIt=openMe);
    webix.html.removeCss($$("trackstageAnnouncements").getNode(), "fa-fade");
}
// -------------------------------------------------------------------- //
function announceRattle()
{
    if (gUser_Profile.User.Notice_Sounds == true && annDinger == true)
    {
	audio.volume = 0.25;
	audio.play();    
    }
    webix.html.addCss($$("trackstageAnnouncements").getNode(), "fa-beat-fade");
    setTimeout('webix.html.removeCss($$("trackstageAnnouncements").getNode(), "fa-beat-fade");',1000);
}
aru = 0;
// -------------------------------------------------------------------- //
function announceSetBadge(inVal)
{
    aru = inVal;
    if (inVal == 0)
    {
	$$("trackstageAnnouncements").config.badge = 0;
	$$("trackstageAnnouncements").define("tooltip",'');
    	$$("trackstageAnnouncements").refresh();
	$(".webix_badge").css("background", "transparent");
    }
    else
    {	
	announceRattle();
	aru = inVal;
	$(".webix_badge").css("background", "");
	setTimeout(`
	$$("trackstageAnnouncements").config.badge = aru;
	$$("trackstageAnnouncements").define("tooltip",aru + ' unread notices..');
	$$("trackstageAnnouncements").refresh();
	`,1600);
    }
}
announceRawData = [];announceMenuData = [];announceDataLines = [];
announceData = [];announceLoaded = false;annFtrFnc = 0;
gUnreadTot = 0;announcePage = 0;announceTotPages = 0;
// -------------------------------------------------------------------- //
async function announceBuild(openIt=true)
{
    if (announceLoaded == false)
    {
	announceDataLines = [];
	announceRawData = [];
	announceMenuData = [];
	announceData = [];
	await getAnnounceData();
    }
    
    if (openIt == true) {$$("announceMenu").show();}
}
// -------------------------------------------------------------------- //
function announceBuildGo()
{
    hdrline = "<table width='100%' border='0'><tr><td><div id='announceMenuHeader' style='text-align:left;width:100%;background:#fff;font-weight:400;font-size:15px;color:#666666;border-bottom: 1px solid #ab8dbf;pointer-events: none;'>Notifications</div></td><td id='ann_checker' style='text-align:right;margin-right:8px;'><input id='ann_hdr_chkbx' title='Select/Un-Select All' class='annHdrCheckBox' onclick='annFtrFnc=4;' value='0' type='checkbox'/></td</tr></table>";
    
    
    ftrline = "<div id='ann_foot' style='float:left;'><span  onclick='annFtrFnc=2;' id='ann_mark_read'><span style='font-size:17px;color: #ab8dbf' class='far fa-check-circle'></span>&nbsp;&nbsp;&nbsp;Mark as Read</span></div>";
    ftrline = ftrline + "<div id='ann_foot' style='float:right;'><span  onclick='annFtrFnc=1;' id='ann_tog_sound'><span id='ann_tog_sound_icon' style='font-size:17px;color: #ab8dbf' class='far ##bell##'></span>&nbsp;&nbsp;&nbsp;Sound</span></div>";
    //ftrline = ftrline + "<div id='ann_' style='float:left;margin-left:50px;'><span onclick='annFtrFnc=4;' id='ann_view_all'><span style='font-size:17px;color: #ab8dbf' class='fas fa-circle-ellipsis'></span>&nbsp;&nbsp;&nbsp;View All</span></div>";
    ftrline = ftrline + "<div id='ann_' style='float:left;margin-left:230px;'><span onclick='annFtrFnc=5;' id='ann_view_prev'><span style='font-size:17px;color: #ab8dbf' class='far fa-circle-arrow-left'></span>&nbsp;&nbsp;&nbsp;Prev</span></div>";
    ftrline = ftrline + "<div id='ann_' style='float:left;margin-left:12px;'><span onclick='annFtrFnc=6;' id='ann_view_next'>Next&nbsp;&nbsp;&nbsp;<span style='font-size:17px;color: #ab8dbf' class='far fa-circle-arrow-right'></span></span></div>";
    ftrline = ftrline + "<div id='ann_' style='float:right;margin-right:48px;'><span  onclick='annFtrFnc=3;' id='ann_dismiss_all'><span style='font-size:17px;color: #ab8dbf' class='far fa-circle-xmark'></span>&nbsp;&nbsp;&nbsp;Delete</span></div>";
    
    if (gUser_Profile.User.Notice_Sounds == true)
    {
	ftrline = ftrline.replaceAll('##bell##','fa-bell');
    }
    else
    {
	ftrline = ftrline.replaceAll('##bell##','fa-bell-slash');
    }

    
    announceData.unshift(hdrline);
    for (i = 0; i < announceDataLines.length; i++) 
    {
	adl = announceDataLines[i];
	announceData.push(adl);
    }
    announceData.push({ $template:"Separator" });
    announceData.push(ftrline);
	    
    $$("announceMenu").clearAll();
    $$("announceMenu").parse(announceData);
    unReadTot = gUser_Profile.Artist.Notices_Unread;
    announceSetBadge(unReadTot);
    gUnreadTot = unReadTot;
    announceLoaded = true;
    setTimeout('annAddTips();',1200);
}
// -------------------------------------------------------------------- //
function annAddTips()
{
    $("#annTable tr").each(function(i, row) {
	    //console.log(i,row)
      webix.TooltipControl.addTooltip(row.id+"_dtl", {
	$tooltipIn:function(node){
	  let tooltip = webix.TooltipControl.getTooltip();
	  tooltip.define("template", function(){
	    return annTooltip(row.id);
	  });
	  return node;
	}
      });	
    });
}
// -------------------------------------------------------------------- //
function annTooltip(row_id)
{
    rid = row_id.replaceAll('ann_row_','');
    for (ndx =0; ndx < announceRawData.length; ndx++)
    {
	ann = announceRawData[ndx];    
	if (ann.Comm_ID == rid)
	{
	    break;
	}
	else
	{  ann = null;}
    }
    if (ann != null)
    {
	return ann.Comm_Subject;
    }
    
}
// -------------------------------------------------------------------- //
async function getAnnounceData()
{
    url = '/data_announce/?mde=list&seq=' + seq();
    response = await axios.get(url)

    gRes = response;
    resData = response.data; 

    if (resData.status == 'error')
    {
        webix.message({type: "error", text: "<b>Error:</b>&nbsp;&nbsp;"+resData.Message, expire: 10000});
	return 0;
    }
    else
    {
	cnt = 0;
	notices = resData.Notices;
	announceRawData = notices;
	pgLen = 11;
	
	// filter to remove dismissed...
	notices2 = [];
	for (ndx =0; ndx < notices.length; ndx++)
	{
	    msg = notices[ndx];
	    if (msg.Dismissed == true) {continue;}
	    notices2.push(msg);
	}
	
	notices2 = sortArrayOfObjects(notices2, "Create_Date", "descending");
	
	// process the messages
	for (ndx =0; ndx < notices2.length; ndx++)
	{
	    if (ndx >= (announcePage*pgLen) && ndx < ((announcePage*pgLen)+pgLen))
	    {	    
		msg = notices2[ndx]; 

		cnt += 1;
		AddMsgLine(msg);
		announceMenuData.push(msg);
	    }
	}	
	
	gUser_Profile.Artist.Notices_Unread = resData.Tot_Unread;
	if (notices2.length == 0)
	{
	    announceTotPages = 0;
	}
	else
	{
	    announceTotPages = (notices2.length / 11);
	    announceTotPages = Math.ceil(announceTotPages);
	}
	announceBuildGo();
    }
    gUser_Profile.Artist.Notices_Unread = resData.Tot_Unread;
    return;
}
// -------------------------------------------------------------------- //
function AddMsgLine(inMsg)
{
    i_system = "<span style='font-size:17px;padding-right:1px;color: darkRed' class='fas fa-do-not-enter'></span>";
    i_announcement = "<span style='font-size:17px;padding-right:1px;color: #800080' class='far fa-megaphone'></span>";
    i_filetrans = "<span style='font-size:17px;padding-right:1px;color: purple' class='fal fa-folder-arrow-down'></span>";
    i_billing = "<span style='font-size:17px;padding-right:1px;color: #778F41' class='fas fa-square-dollar'></span>";
    i_collab_update = "<span style='font-size:17px;padding-right:1px;color: purple' class='fal fa-microphone'></span>";
    i_collab_invited = "<span style='font-size:17px;padding-right:1px;color: purple' class='fal fa-microphone'></span";
    i_collab_accepted = "<span style='font-size:17px;padding-right:1px;color: purple' class='fal fa-microphone'></span";
    i_collab_declined = "<span style='font-size:17px;padding-right:1px;color: purple' class='fal fa-microphone'></span>";
    i_vet_survey = "<span style='font-size:17px;padding-right:1px;color: #652487' class='fal fa-comment-music'></span>";
    i_user_msg = "<span style='font-size:17px;padding-right:1px;color: orange' class='fas fa-message-smile'></span>";
    i_share_accessed = "<span style='font-size:17px;padding-right:1px;color: gold' class='far fa-bow-arrow'></span>";
    i_track_played = "<span style='font-size:15px;padding-right:1px;color: #ffc300' class='far fa-headphones'></span>";
    i_track_downloaded = "<span style='font-size:14px;padding-right:1px;color: orange' class='far fa-cloud-arrow-down'></span>";
    
    dv_s = "<div id='ann_div_##id##' style='margin-left:2px;'>";
    dv_e = "</div>"
    
    
    t_s = "<table id='annTable' width=100% style='table-layout:fixed;  border-collapse:collapse;border-spacing:0;'>";t_e = "</table>";
    r_s = "<tr id='ann_row_##id##'>";r_e = "</tr>";c_e = "</td>";
    c_s_i = "<td id='ann_row_##id##_icn' class='##summ_class##' style='text-align:left;width:22px;'>";  
    c_s_c = "<td id='ann_row_##id##_sum' class='##summ_class##' style='text-align:left;width:110px;'>";
    c_s_s = "<td id='ann_row_##id##_dtl' class='##dtls_class##' style='text-align:left;width:510px;'>";
    c_s_d = "<td id='ann_row_##id##_dte' class='##DT_class##' style='text-align:right;width:100px;'>";
    c_s_k = "<td id='ann_row_##id##_chk' class='##summ_class##' style='text-align:right;width:20px;'>";
    
    if      (inMsg.Comm_UsageType == 'System') {theIcon = i_system;theCategory = 'System Notice';theSummary = inMsg.Comm_Summary;}
    else if (inMsg.Comm_UsageType == 'Announcement') {theIcon = i_announcement;theCategory = 'Announcement';theSummary = inMsg.Comm_Summary;}
    else if (inMsg.Comm_UsageType == 'File Transfer') {theIcon = i_filetransfer;theCategory = 'File Transfer';theSummary = inMsg.Comm_Summary;}
    else if (inMsg.Comm_UsageType == 'Billing') {theIcon = i_billing;theCategory = 'Billing Notice';theSummary = inMsg.Comm_Summary;}
    else if (inMsg.Comm_UsageType == 'Collaborator Note') {theIcon = i_collab_update;theCategory = 'Project Update';theSummary = inMsg.Comm_Summary;}
    else if (inMsg.Comm_UsageType == 'Collaborator Invite') {theIcon = i_collab_invited;theCategory = 'Project Invite';theSummary = inMsg.Comm_Summary;}
    else if (inMsg.Comm_UsageType == 'Collaborator Accepted') {theIcon = i_collab_accepted;theCategory = 'Project Accepted';theSummary = inMsg.Comm_Summary;}
    else if (inMsg.Comm_UsageType == 'Collaborator Declined') {theIcon = i_collab_declined;theCategory = 'Project Declined';theSummary = inMsg.Comm_Summary;}
    else if (inMsg.Comm_UsageType == 'Vetting Survey Results') {theIcon = i_vet_survey;theCategory = 'Survey Results';theSummary = inMsg.Comm_Summary;}
    else if (inMsg.Comm_UsageType == 'User Message') {theIcon = i_user_msg;theCategory = 'User Message';theSummary = inMsg.Comm_Summary;}
    else if (inMsg.Comm_UsageType == 'Share Link Opened') {theIcon = i_share_accessed;theCategory = 'Pitch Opened';theSummary = inMsg.Comm_Summary;}
    else if (inMsg.Comm_UsageType == 'Pitched Track Played') {theIcon = i_track_played;theCategory = 'Track Played';theSummary = inMsg.Comm_Summary;}
    else if (inMsg.Comm_UsageType == 'Pitched Track Downloaded') {theIcon = i_track_downloaded;theCategory = 'Track Download';theSummary = inMsg.Comm_Summary;}
    else {theIcon = '';theCategory = '';theSummary = '';}
    
    if (theSummary.length > 80) {theSummary = theSummary.substring(0,80)};

    current_date = new Date();
    cdate = inMsg.Create_Date;
    msg_date = new Date(cdate);
    difference = current_date.getTime() - msg_date.getTime();
    diffsecs = difference/1000;
    diffhours = Math.abs(diffsecs)/3600;
    if (diffhours < 24)
    {
	    // show the time
	    theDT = formatAMPM(msg_date);
    }
    else
    {
	    // show the date
	    month = msg_date.toLocaleString('default', { month: 'short' });
	    theDT = cdate.substring(0,4) + '-' + month + '-' + cdate.substring(8,10);
    }
    
    theCheck = "<input id='ann_row_##id##_chkbx' class='annCheckBox' onclick='this.value=1;' value='0' type='checkbox'/>";
    trow = dv_s + t_s + r_s + c_s_i + theIcon + c_e + c_s_c + theCategory + c_e + c_s_s + theSummary + c_e + c_s_d + theDT + c_e + c_s_k + theCheck + c_e + r_e + t_e + dv_e;
    trow = trow.replaceAll('##id##',msg.Comm_ID);
    if (msg.Comm_Level == 'System')
    {
	trow = trow.replaceAll('##summ_class##','annSystem').replaceAll('##DT_class##','annSystem').replaceAll('##dtls_class##','annSystem');    
    }
    else if (msg.Displayed == true)
    {
	trow = trow.replaceAll('##summ_class##','annRead').replaceAll('##DT_class##','annRead').replaceAll('##dtls_class##','annRead');
    }
    else
    {
	trow = trow.replaceAll('##summ_class##','annNotRead').replaceAll('##DT_class##','annNotRead').replaceAll('##dtls_class##','annNotRead');    
    }
    
    announceDataLines.push(trow);	    
}
// -------------------------------------------------------------------- //
function announceMore(id,e,trg)
{
    annid = trg.firstChild.id;
    //console.log("announceMore():",annid);
    //webix.message({type: "info", text: "We will do something with id: " + annid, expire: 2000});
}
// -------------------------------------------------------------------- //
function annTogSound()
{
    if ($("#ann_tog_sound_icon").hasClass('fa-bell-slash') == true)
    {
	$("#ann_tog_sound_icon").removeClass('fa-bell-slash');
	$("#ann_tog_sound_icon").addClass('fa-bell');
	gUser_Profile.User.Notice_Sounds = true;
	announceSetBadge(gUnreadTot);
	updateAnnounceData('sound', {"Notice_Sounds": true});
    }
    else
    {
    	$("#ann_tog_sound_icon").removeClass('fa-bell');
	$("#ann_tog_sound_icon").addClass('fa-bell-slash');
	gUser_Profile.User.Notice_Sounds = false;
	announceSetBadge(gUnreadTot);
	updateAnnounceData('sound', {"Notice_Sounds": false});
    }
}
// -------------------------------------------------------------------- //
function annMarkAll()
{
    console.log('annMarkAll():');
    annMarks = annGetChecked();
    if (annMarks.length == 0)
    {
	lcText = "No Notices are selected.<br/><br/>Do you want to MARK <b>ALL Notices</b> as READ?" + "<br/><br/>";
	lcTitle = "<span style='line-height:2.5;'>Mark ALL Notices as Read</span>";
    }
    else
    {
        lcText = "Do you want to MARK these " + annMarks.length + " Notices as READ?" + "<br/><br/>";
	lcTitle = "<span style='line-height:2.5;'>Mark Seleted Notices as Read</span>";
    }

    webix.confirm(
     {
      title: lcTitle,
      text: lcText,
      ok: "OK",
      cancel: "Cancel",
      width:380,
    }).then(function(result)
    {
        updateAnnounceData('mark', annMarks)
    });    
}
// -------------------------------------------------------------------- //
function annViewAll()
{
    console.log('annViewAll():');
}
// -------------------------------------------------------------------- //
function annDismissAll()
{
    console.log('annDismissAll():');
    annMarks = annGetChecked();
    if (annMarks.length == 0)
    {
	lcText = "No notifications are selected.<br/><br/>Do you want to delete <b>ALL Notifications</b>?" + "<br/><br/>";
	lcTitle = "<span style='line-height:2.5;'>Delete All Notifications</span>"
    }
    else
    {
        lcText = "Do you want to delete these " + annMarks.length + " Notifications?" + "<br/><br/>";
	lcTitle = "<span style='line-height:2.5;'>Delete Selected Notifications</span>";
    }

    webix.confirm(
     {
      title: lcTitle,
      text: lcText,
      ok: "OK",
      cancel: "Cancel",
      width:380,
    }).then(function(result)
    {
        updateAnnounceData('dismiss', annMarks)
    });     
}
// -------------------------------------------------------------------- //
function annGetChecked()
{
    out = [];
    for (ndx =0; ndx < announceMenuData.length; ndx++)
    {
	tItem = announceMenuData[ndx];
	chk_id = 'ann_row_' + tItem.Comm_ID + '_chkbx';
	isChkd = $("#"+chk_id).is(':checked')
	if (isChkd == true)
	{
	    out.push(tItem);
	}
    }
    return out;
}
// -------------------------------------------------------------------- //
async function updateAnnounceData(inItem, inData={})
{
    url = '/data_announce/?mde=update&seq=' + seq();
    pkge = {'Item': inItem, 'Update_Data': inData};
    response = await axios.post(url, pkge)

    gRes = response;
    resData = response.data; 

    if (resData.status == 'error')
    {
        webix.message({type: "error", text: "<b>Error:</b>&nbsp;&nbsp;"+resData.Message, expire: 6000});
	return;
    }
    else
    {
        webix.message({type: "success", text: "<b>Sucess:</b>&nbsp;&nbsp;"+resData.Message, expire: 1400}); 
	if (inItem == 'mark' || inItem == 'dismiss') {announceLoaded = false;}
	announceShow();
    }
}
annDinger = true;
// -------------------------------------------------------------------- //
function announcePaginate(inDir)
{
    if (inDir.toLowerCase() == 'next')
    {
	announcePage += 1;
	if (announcePage > announceTotPages) {announcePage -= 1;} 
    }
    else
    {
	announcePage -= 1;
	if (announcePage < 0) {announcePage = 0;} 
    }
    announceLoaded = false;
    annDinger = false;
    announceShow(); 
    setTimeout('annAddTips();annDinger = true;',1800);
}
// -------------------------------------------------------------------- //
function uploadBlobAsk()
{
    try {clearInterval(screenInterval);} catch(err) {a=1;}
    webix.prompt(
     {
      title: "Submit Screen Recording Session?",
	width: 500,
	text: 'Include Note',
      ok: "Yes",
      cancel: "No",
      input: {
	placeholder: "Addtl notes for the support team",
      },
      width:700,
    }).then(function(result)
    {
	addtl_notes = result;  
	uploadBlob(addtl_notes);

	
    }).fail(function(){

  
    }); 

}
// -------------------------------------------------------------------- //
function uploadBlob(inNtes='') 
{
    clnNotes = encodeURI(inNtes);
    url = gcBaseURL + 'artisthelp/?go=y&arti=' + gUser_Profile.Artist.Arti_ID + '&ntes=' + clnNotes;
    fetch(url, {
	method: "POST",
	body: blobData
    })
    .then(response => 
	webix.message({type: "success", text: "<b>Submission Completed:</b><br/><br/>Your recorded screen session has been sent to our support team.<br/> We will review this and get back to you shortly.<br/><br/>", expire: 12000})
	)
    .catch(err => alert(err));
}
// -------------------------------------------------------------------- //
function annCheckAll(inMode=1)
{
    acnt = 0;
    // detect inMode based on something being checked
    $(".annCheckBox").each(function(i, obj) 
    {
	if ($(this).prop('checked'))
	{
	    acnt += 1;
	}
    });
    
    if (acnt > 0) {inMode = 0;} else {inMode = 1;}
    
    $(".annCheckBox").each(function(i, obj) 
    {
	if (inMode == 1)
	    {$(this).prop('checked', true);}
	else
	    {$(this).prop('checked', false);}
    });
    
    if (inMode == 1) {$("#ann_hdr_chkbx").prop('checked', true);} else {$("#ann_hdr_chkbx").prop('checked', false);}

}
// -------------------------------------------------------------------- //
function screenCapSetup()
{
	if (combine != undefined && combine != null)
	{
		try 
		{
			combine.getTracks()[0].stop();
			combine.getTracks()[1].stop();
			combine = null;
			$('#recorder_Setup_Text').html('Enable Screen Recorder');
			$('#recorder_Setup_Icon').removeClass('fa-video-slash').addClass('fa-video');
			
			$$("recMini_Enable").config.tooltip.template = 'Enable screen recorder';
			$$("recMini_Enable").config.icon = 'fa fa-video';
			$$("recMini_Enable").refresh();
			
			$(".webix_icon.fa.fa-circle-play.deep_purple_it").removeClass('deep_purple_it').addClass('dim_it');
			$(".webix_icon.fa.fa-circle-pause.deep_purple_it").removeClass('deep_purple_it').addClass('dim_it');
			$(".webix_icon.fa.fa-circle-stop.deep_purple_it").removeClass('deep_purple_it').addClass('dim_it');
			//$(".webix_icon.fa.fa-times.deep_purple_it").removeClass('deep_purple_it').addClass('dim_it');
			
			screenCapControls('off');
			screenTimer = 0;
			$$("recMini_Time").setHTML('');
			try {clearInterval(screenInterval);} catch(err) {a=1;}
			
		}
		catch(err)
		{
			a=1;
		}
		return;
	}
	
	screenTimer = 0;
	$$("recMini_Time").setHTML('');
	$$("recMini_Start").config.tooltip.template = 'Start recording';
	$("#recorder_Start_Text").html('Start recording');	
	aaa = $("#vidtester");
	if (aaa.html() != undefined) 
	{
	    $("#recorder_Review_Icon").css('color','purple');
	    $("#recorder_Review_Text").css('color','purple');
	}
	else
	{
	    $("#recorder_Review_Icon").css('color','#aaaaaa');
	    $("#recorder_Review_Text").css('color','#aaaaaa');	
	}
	
	recording = navigator.mediaDevices.getDisplayMedia(
	{
		video: 
		{
			mediaSource: 'screen',
		},
		audio: true,
	})
		.then(async (e) => {
	
			// For recording the mic audio
			let audio = await navigator.mediaDevices.getUserMedia({
				audio: true, video: false })
	
			// Assign the recorded mediastream to the src object
			video.srcObject = e;
	
			// Combine both video/audio stream with MediaStream object
			combine = new MediaStream(
				[...e.getTracks(), ...audio.getTracks()])
	
			/* Record the captured mediastream
			with MediaRecorder constructor */
			recorder = new MediaRecorder(combine);
	
			$('#recorder_Setup_Text').html('Disable Screen Recorder');
			$('#recorder_Setup_Icon').removeClass('fa-video').addClass('fa-video-slash');
			
			$$("recMini_Enable").config.tooltip.template = 'Disable screen recorder';
			$$("recMini_Enable").config.icon = 'fa fa-video-slash';
			$$("recMini_Enable").refresh();
			
			$(".webix_icon.fa.fa-circle-play.dim_it").removeClass('dim_it').addClass('deep_purple_it');
			$(".webix_icon.fa.fa-circle-pause.dim_it").removeClass('dim_it').addClass('deep_purple_it');
			$(".webix_icon.fa.fa-circle-stop.dim_it").removeClass('dim_it').addClass('deep_purple_it');
			//$(".webix_icon.fa.fa-times.dim_it").removeClass('dim_it').addClass('deep_purple_it');			
			
			start.addEventListener('click', (e) => {
	
				// Starts the recording when clicked
				recorder.start();
				alert("recording started")
	
				// For a fresh start
				data = []
			});
	
			stop.addEventListener('click', (e) => {
	
				// Stops the recording
				recorder.stop();
				//alert("recording stopped")
			});
	
			/* Push the recorded data to data array
			when data available */
			recorder.ondataavailable = (e) => {
				data.push(e.data);
			};
	
			recorder.onstop = () => {
	
				/* Convert the recorded audio to
				blob type mp4 media */
				blobData = new Blob(data, { type: 'video/mp4' });
	
				// Convert the blob data to a url
				let url = URL.createObjectURL(blobData)
	
				// Assign the url to the output video tag and anchor
				output.src = url
				anc.href = url
			};
			
			screenCapControls('on');
		});
}
// -------------------------------------------------------------------- //
function screenCapControls(inMode)
{
    console.log("screenCapControls():");
    
    if (inMode == 'on')
    {
	$("#recorder_Start").css('color','purple');
	$("#recorder_Start_Text").css('color','purple');
	$("#recorder_Pause").css('color','purple');
	$("#recorder_Pause_Text").css('color','purple');
	$("#recorder_Stop").css('color','purple');
	$("#recorder_Stop_Text").css('color','purple');	
	
	$$("recorderMini").show();
    }
    else
    {
	$("#recorder_Start").css('color','#aaaaaa');
	$("#recorder_Start_Text").css('color','#aaaaaa');
	$("#recorder_Pause").css('color','#aaaaaa');
	$("#recorder_Pause_Text").css('color','#aaaaaa');
	$("#recorder_Stop").css('color','#aaaaaa');
	$("#recorder_Stop_Text").css('color','#aaaaaa');
	
	$$("recorderMini").hide();
    }
    
    if (bailcnt != 0)
    {
	bailcnt = 0;
	catalogTotals();
    }

}
recIsPaused = false;
// -------------------------------------------------------------------- //
function recorderAction(inMode)
{
    if (inMode == 'start')
    {
	try
	{
	    if (combine == undefined && combine == null) {return;}
	    try{ if (recorder.state && recorder.state == 'paused') {recIsPaused = true;} else {recIsPaused = false;}} catch(err) {recIsPaused = false;}
	    if (recIsPaused == true) 
	    {
		recorder.resume();
		recIsPaused = false;
		$$("recMini_Start").config.tooltip.template = 'Start recording';
		$("#recorder_Start_Text").html('Start recording');
		webix.message({type: "info", text: "<b>Screen Recording</b> has RESUMED", expire: 1400});
	    } 
	    else
	    {
		recorder.start();
		screenInterval = setInterval(timerScreenCap, 1000);
		webix.message({type: "info", text: "<b>Screen Recording</b> has STARTED", expire: 1400});
	    }
	    
	}
	catch (err) {a=1;}
    }
    else if (inMode == 'pause')
    {
	try
	{
	    if (combine == undefined && combine == null) {return;}	
	    recorder.pause();
	    recIsPaused = true;
	    $$("recMini_Start").config.tooltip.template = 'Resume recording';
	    $("#recorder_Start_Text").html('Resume recording');
	    webix.message({type: "info", text: "<b>Screen Recording</b> has PAUSED", expire: 1400});
	}
	catch (err) {a=1;}
    }  
    else if (inMode == 'stop')
    {
	try
	{
	    if (combine == undefined && combine == null) {return;}	
	    recorder.stop();
	    try {clearInterval(screenInterval);} catch(err) {a=1;}
	    screenTimer = 0;
	    webix.message({type: "info", text: "<b>Screen Recording</b> has STOPPED", expire: 1400});
	    $$("recMini_Start").config.tooltip.template = 'Start recording';
	    $("#recorder_Start_Text").html('Start recording');
	    aaa = $("#vidtester");
	    if (aaa.html() != undefined) 
	    {
		$("#recorder_Review_Icon").css('color','purple');
		$("#recorder_Review_Text").css('color','purple');
	    }
	    else
	    {
		$("#recorder_Review_Icon").css('color','#aaaaaa');
		$("#recorder_Review_Text").css('color','#aaaaaa');	
	    }
	    screenCapSetup();
	}
	catch (err) {a=1;}
    }   
    else if (inMode == 'view')
    {
	try
	{
	aaa = $("#vidtester");
	if (aaa.html() == undefined || aaa.html() == null)
	    {webix.message({type: "info", text: "There is no screen recording to VIEW.", expire: 2000});}
	else
	{
	    webix.message({type: "info", text: "<b>Screen Recording</b> loaded..", expire: 800});
	    genSmallPopup('bogus',aaa.html(),hh*0.8,ww*0.7);
	    setTimeout(`
		$$("tmpPopup").attachEvent("onHide", function()
		{
		    aaa = $("#vidtester");
		    if (aaa.html() != undefined)
		    {
			uploadBlobAsk();
		    }
		}); 
	    `,400);
	    }
	}
	catch (err) {a=1;}
    }  
    else if (inMode == 'close')
    {
	$$("recorderMini").hide();
	if (isMac == true) {webix.message({type: "info", text: "Press <b>Command-Shift-S</b> to re-open Screen Recorder controls", expire: 3800});}
	else {webix.message({type: "info", text: "Press <b>Ctrl-Shift-S</b> to re-open Screen Recorder controls", expire: 3800});}
    
    }
}
// -------------------------------------------------------------------- //
function catalogLoadSVAsk()
{
    ConfirmIt(title='Create Writers/Publishers Records' , 
	description='Ready to ADD records from your PRO Data now?', 
	txtYes='Yes', txtNo='No', fncForYes='catalogInsertSVDataGo', 
	fncForNo='cancelMsg', keyID=undefined, cancel_Msg='Request cancelled.');  
}
// -------------------------------------------------------------------- //
function catalogLoadSVGo()
{
    ConfirmIt(title='Remove Existing Records First?' , 
	description='Do you want to REMOVE any existing Rights/Publisher record first?', 
	txtYes='Yes, Remove', txtNo='No, Keep them', fncForYes='svDataRemoveFirst', 
	fncForNo='svDataKeepThem', keyID=undefined, cancel_Msg='Request cancelled.');      
}
// -------------------------------------------------------------------- //
function svDataRemoveFirst()
{
    svData_RemoveFirst = true;
    catalogLoadSVAsk();
}
// -------------------------------------------------------------------- //
function svDataKeepThem()
{
    svData_RemoveFirst = false;
    catalogLoadSVAsk();
}
// -------------------------------------------------------------------- //
async function catalogInsertSVDataGo()
{
    webix.message({type: "success", text: "<b>OK:</b>&nbsp;Processing request", expire: 5000});
  
    SV_Data = [];writers = [];publishers = [];
    var ndx=-1;
    for (ndx =0; ndx < proData.Writers.length; ndx++)
    {
	tWriter = proData.Writers[ndx]; 
	try
	{
	    sval = $$("svFrm_Split_" + pad(ndx+1,2)).getValue();
	    tWriter.writer_pct = sval;
	    writers.push(tWriter);
	}
	catch(err) {a=1;}
    }
    
    var ndx=-1;
    for (ndx =0; ndx < proData.Writers.length; ndx++)
    {
	tPubl = proData.Publishers[ndx]; 
	try
	{
	    sval = $$("svFrm_PubSplit_" + pad(ndx+1,2)).getValue();
	    tPubl.publisher_pct = sval;
	    publishers.push(tPubl);
	}
	catch(err) {a=1;}
    }    
	
    SV_Data = {'writers': writers, 'publishers': publishers}
    //  submit it to server
    url = '/data_catalog/?mde=insertsvdata&seq=' + seq();
    pkge = {'Arti_ID': gUser_Profile.Artist.Arti_ID, 'SV_Data': SV_Data, 'delFirst': svData_RemoveFirst, 'Track_ID': gCurrTrack.Track_ID};
    response = await axios.post(url, pkge)    
    
    gRes = response;
    resData = response.data;
    if (resData.status == 'error')
    {
      webix.message({type: "error", text: resData.message, expire: 10000});
    }
    else
    {
        if (resData.status == 'success')
        {
	    webix.html.triggerEvent($$("proFormWindowClose").getInputNode(), "MouseEvents", "click");
            webix.message({type: "success", text: resData.message, expire: 3000});
	    dataWH.Participants.dataStore.clearAll();
	    dataWH.Participants.dataStore.parse(resData.allParts);
	    setParticipants();	    
	    $$("rightsList").clearAll();
	    $$("rightsList").define("data",catalogPartsRights);
	    $$("rightsList").refresh();  
	    
	    $$("targetsList").clearAll();
	    $$("targetsList").define("data",catalogPartsTargets);
	    $$("targetsList").refresh();  	    
	    setTimeout(`webix.UIManager.setFocus($$('rightsList'));`,600);
        }        
        else
            {webix.message({type: "error", text: resData.message, expire: 10000});}
    }     
}
// ---------------------------------------------------------------------------- //
function rightsTotals()
{
    wTot = 0.00;mTot = 0.00;
    $$("rightsList").eachRow(function(item_id) 
    {
	row = $$("rightsList").getItem(item_id);
	wTot = wTot + row.Right_Holder.Cowriting_Pct;
	mTot = mTot + row.Right_Holder.Master_Pct;
	
    }, true);
    
    if (mTot != 100.00 && mTot != 0.00) 
	{mTot = Math.round((mTot + Number.EPSILON) * 100) / 100;mOut = '<span style="color:red;">' + mTot + '</span>';}
    else
	{mTot = Math.round((mTot + Number.EPSILON) * 100) / 100;mOut = mTot + '';}
    if (wTot != 100.00 && wTot != 0.00) 
	{wTot = Math.round((wTot + Number.EPSILON) * 100) / 100;wOut = '<span style="color:red;">' + wTot + '</span>';}
    else
	{wTot = Math.round((wTot + Number.EPSILON) * 100) / 100;wOut = wTot + '';}	
    
    $$("rightsList").getColumnConfig('Right_Holder.Master_Pct').footer[0].text = mOut;
    $$("rightsList").getColumnConfig('Right_Holder.Cowriting_Pct').footer[0].text = wOut;
    $$("rightsList").refreshColumns();
}
// ---------------------------------------------------------------------------- //
function targetsTotals()
{
    wTot = 0.00;mTot = 0.00;
    $$("targetsList").eachRow(function(item_id) 
    {
	row = $$("targetsList").getItem(item_id);
	wTot = wTot + row.Target.Publishing_Pct; 
	mTot = mTot + row.Target.Cowriting_Pct;
	
    }, true);
    
    if (mTot != 100.00 && mTot != 0.00) 
	{mTot = Math.round((mTot + Number.EPSILON) * 100) / 100;mOut = '<span style="color:red;">' + mTot + '</span>';}
    else
	{mTot = Math.round((mTot + Number.EPSILON) * 100) / 100;mOut = mTot + '';}
    if (wTot != 100.00 && wTot != 0.00) 
	{wTot = Math.round((wTot + Number.EPSILON) * 100) / 100;wOut = '<span style="color:red;">' + wTot + '</span>';}
    else
	{wTot = Math.round((wTot + Number.EPSILON) * 100) / 100;wOut = wTot + '';}	
    
    $$("targetsList").getColumnConfig('Target.Cowriting_Pct').footer[0].text = mOut;
    $$("targetsList").getColumnConfig('Target.Publishing_Pct').footer[0].text = wOut;
    $$("targetsList").refreshColumns();
}

pofid = '';
// ---------------------------------------------------------------------------- //
function cpBriefCreateOppoAsk()
{
    fnd = false;oProd = {};
    dataWH.Productions.dataStore.data.each(function(prod, index) 
    {
	if (prod.Prod_Ref_Num == gCurrBrief.Brief_Key)
	{
	    fnd = true;
	    oProd = prod;
	}
    });
    
    if (fnd == true)
    {
	webix.message({type: "debug", text: "<b>Hey!</b>&nbsp;You already have this set up - loading it now...", expire: 5000});
	gCurrTab = 'Targets';
	gotoModule('Targets');	
	targetsCurrID = oProd.Target_ID;
	
	setTimeout(`
	    $$("targetsTable").select(targetsCurrID);
	`,1800)
	
	setTimeout(`
	    tgtSkipIt = false;
	    gotoTargetsTab('targetsProductions');
	    gCurrTarget['Target'] = dataWH.Targets.dataStore.getItem(targetsCurrID);	
	    setProductions();	
	`,2600);
	
	setTimeout("targetsSetVisibility();",3100);	
	
	setTimeout(`	 
	    pfnd = false;pofid = '';
	    dataWH.Productions.dataStore.data.each(function(p_obj)
	    {
		if (p_obj.Prod_Ref_Num == gCurrBrief.Brief_Key)
		{
		    pfnd = true;
		    pofid = p_obj.id;
		}
	    });	
	    if (pfnd == true)
	    {	    
		var tpid = 0;pfid = 0;
		for (pndx=0; pndx < targetsProductions.length; pndx++)
		{
		    tpod = targetsProductions[pndx];
		    
		    if (tpod.Production.Prod_ID == pofid)
		    {
			pfid = tpod.id;
		    }	
		}
		
		if (pfid > 0)
		{
		    $$("productionsList").select(pfid);
		    targetsProdCurrID = pofid;
		}
	    }
	`,3500)
	
	return;
    }

    lcDesc = ('Create a NEW Opportunity for this <br/><br/>' + 
    '<span style="color:purple;font-weight:bold;">' + 
    gCurrBrief.Brief_Type.toProperCase() + '</span><br/><br/>listing?');
    
    ConfirmIt(title='Create New Target-Opportunity' , 
	description=lcDesc, 
	txtYes='Yes', txtNo='No', fncForYes='cpBriefCreateOppoGo', 
	fncForNo='cancelMsg', keyID=undefined, cancel_Msg='Request cancelled.');  
}
// ---------------------------------------------------------------------------- //
async function cpBriefCreateOppoGo()
{
    pkge = {'Arti_ID': gUser_Profile.Artist.Arti_ID, 'Brief': gCurrBrief}
    url = '/data_productions/?mde=brief_oppo&seq=' + seq();
    response = await axios.post(url, pkge)    
    
    gRes = response;
    resData = response.data;
    if (resData.status == 'error')
    {
      webix.message({type: "error", text: resData.message, expire: 10000});
    }
    else
    {
        if (resData.status == 'success')
        {
	    if (resData.added_Target == true)
	    {
		webix.message({type: "success", text: response.data.message, expire: 6000});
		dataWH.Targets.dataStore.add(response.data.newTarget);
		// refresh list and also select new record
	    }
	    if (resData.added_Production == true)
	    {
		dataWH.Productions.dataStore.add(response.data.newProduction);
		// refresh list and select select new record
	    }
	    
	    if (resData.added_Contact == true)
	    {
		dataWH.Contacts.dataStore.add(response.data.newContact);
		// refresh list and select select new record
	    }	    
	    	    	    
	    fnd = false;oProd = {};
	    dataWH.Productions.dataStore.data.each(function(prod, index) 
	    {
		if (prod.Prod_Ref_Num == gCurrBrief.Brief_Key)
		{
		    fnd = true;
		    oProd = prod;
		}
	    });
	    
	    if (fnd == true)
	    {
		webix.message({type: "debug", text: "<b>OK!</b>&nbsp;New Opportunity set up completed - loading it now...", expire: 5000});
		gCurrTab = 'Targets';
		gotoModule('Targets');	
		targetsCurrID = oProd.Target_ID;
		
		setTimeout(`
		    $$("targetsTable").select(targetsCurrID);
		`,1800)
		
		setTimeout(`
		    tgtSkipIt = false;
		    gotoTargetsTab('targetsProductions');
		    gCurrTarget['Target'] = dataWH.Targets.dataStore.getItem(targetsCurrID);	
		    setProductions();	
		`,2600);
		
		setTimeout("targetsSetVisibility();",3100);	
		
		setTimeout(`	 
		    pfnd = false;pofid = '';
		    dataWH.Productions.dataStore.data.each(function(p_obj)
		    {
			if (p_obj.Prod_Ref_Num == gCurrBrief.Brief_Key)
			{
			    pfnd = true;
			    pofid = p_obj.id;
			}
		    });	
		    if (pfnd == true)
		    {	    
			var tpid = 0;pfid = 0;
			for (pndx=0; pndx < targetsProductions.length; pndx++)
			{
			    tpod = targetsProductions[pndx];
			    
			    if (tpod.Production.Prod_ID == pofid)
			    {
				pfid = tpod.id;
			    }	
			}
			
			if (pfid > 0)
			{
			    $$("productionsList").select(pfid);
			    targetsProdCurrID = pofid;
			}
		    }
		`,3500)
		
		return;
	    }

	    
	    
	    
	    
	    
	    
        }        
        else
            {webix.message({type: "error", text: resData.message, expire: 10000});}
    }  

}
gTracks2Tag = [];
// ---------------------------------------------------------------------------- //
async function admAutoTag(inMode='init',All_Or_Pending='all')
{
    if (Import_Mode != 'Y')
    {
	webix.message({type: "error", text: "<b>Error:</b>&nbsp;&nbsp;Not in bulk import mode", expire: 10000});
	return false;
    }
    
    nNext = 0;
    url = '/data_metatag/?mde=autotag&tauri='+gTauri.toString()+'&seq=' + seq();
    if (inMode=='init')
    {
	pkge = {'Step': 'autotag', 'Acct': gUser_Profile.Artist.Email, 'Mode': 'init', 'Next_ID': 0, 'All_Or_Pending': All_Or_Pending};
    }
    else
    {
	if (gTracks2Tag.length == 0) 
	{
	    webix.message({type: "error", text: "<b>Error:</b>&nbsp;&nbsp;No Pending Tracks left to Tag.", expire: 3000});
	    return false;
	}
	
	if (gTracks2Tag.length > 0)
	{
	    nNext = gTracks2Tag[0]
	    gTracks2Tag.shift();
	}
	pkge = {'Step': 'autotag', 'Acct': gUser_Profile.Artist.Email, 'Mode': 'next', 'Next_ID': nNext};
    }
    
    if (nNext > 0)
	{
	    //webix.message({type: "debug", text: "<b>Starting:</b>", expire: 3000});
	}
    else
	{webix.message({type: "debug", text: "<b>Initializing:</b>&nbsp;&nbsp; ... ", expire: 1600});}
    
    response = await axios.post(url, pkge)
    gRes = response;
    resData = response.data; 
    if (resData.status == 'error')
    {
        webix.message({type: "debug", text: "<b>Error:</b>&nbsp;&nbsp;"+resData.Message, expire: 4000});
	return false;
    }
    else
    {
	if (resData.Mode == 'init')
	    {gTracks2Tag = resData.Pending_Tracks;}
	else 
	    {a=1;}
	    
	var trkMsg = '';
	if (gTracks2Tag.length > 0)
	{
	    try 
	    {
		var tmpTrack = $$("catalogTable").getItem(resData.ETrack_Sent);
		trkMsg = 'Tagging Track:&nbsp;&nbsp;<b>' + tmpTrack.File_Name + tmpTrack.File_Ext + '</b>&nbsp;&nbsp;&nbsp;(' + gTracks2Tag.length + '&nbsp;to go)';
		
	    } catch(err) {trkMsg = '';}
	    
	    if (trkMsg.length > 0) {webix.message({type: "success", text: "<b>Sent:</b>&nbsp;&nbsp;"+trkMsg, expire: 3000});}
	}
	else
	{
	    webix.message({type: "debug", text: "<b>Please Note:</b>&nbsp;&nbsp;No Tracks to Tag.", expire: 2200});
	}
	return true;
    }
}
// ---------------------------------------------------------------------------- //
async function admAutoFill(sort_dir='down', currOffset=0)
{
    if (Import_Mode != 'Y')
    {
	webix.message({type: "error", text: "<b>Error:</b>&nbsp;&nbsp;Not in bulk import mode", expire: 10000});
	return;
    }
    
    url = '/data_metatag/?mde=autofill&tauri='+gTauri.toString()+'&offset='+currOffset+'&seq=' + seq();
    pkge = {'Step': 'autofill', 'Acct': gUser_Profile.Artist.Email, 'Sort_Dir': sort_dir};
    response = await axios.post(url, pkge)
    gRes = response;
    resData = response.data; 
    if (resData.status == 'error')
    {
        webix.message({type: "error", text: "<b>Error:</b>&nbsp;&nbsp;"+resData.Message, expire: 10000});
    }
    else
    {
	webix.message({type: "success", text: "<b>Completed:</b>&nbsp;&nbsp;"+resData.Message, expire: 10000});
	webix.message({type: "success", text: "<b>REFRESH REQUIRED:</b>&nbsp;&nbsp;To see the updates...", expire: 10000});
    }
}
// ---------------------------------------------------------------------------- //
async function admAutoLink(mp3_are_primary=false,track_folder_level=0,sort_dir='down')
{
    if (Import_Mode != 'Y')
    {
	webix.message({type: "error", text: "<b>Error:</b>&nbsp;&nbsp;Not in bulk import mode", expire: 10000});
	return;
    }
    
    url = '/data_metatag/?mde=autolink&tauri='+gTauri.toString()+'&seq=' + seq();
    pkge = {'Step': 'autolink', 'Acct': gUser_Profile.Artist.Email, 'MP3_Are_Primary': mp3_are_primary, 'Track_Folder_Level': track_folder_level, 'Sort_Dir': sort_dir};
    response = await axios.post(url, pkge)
    gRes = response;
    resData = response.data; 
    if (resData.status == 'error')
    {
        webix.message({type: "error", text: "<b>Error:</b>&nbsp;&nbsp;"+resData.Message, expire: 10000});
    }
    else
    {
	webix.message({type: "success", text: "<b>Completed:</b>&nbsp;&nbsp;"+resData.Message, expire: 10000});
	webix.message({type: "success", text: "<b>REFRESH REQUIRED:</b>&nbsp;&nbsp;To see the updates...", expire: 10000});
    }
}
// ---------------------------------------------------------------------------- //
async function updatePT_Order()
{

	// get the new order
	newOrder = [];
	var tid = $$("pitchTracksList").getIdByIndex(0);
	if (tid == undefined) {gPTOrder_Dirty = false;return;}
	
	var tRec = $$("pitchTracksList").getItem(tid);
	newOrder.push(tRec.Pitch_Track);
	
    for (var ndx=0; ndx < 500; ndx++)
    {
		var tnxt = $$("pitchTracksList").getNextId(tid);
		if (tnxt == undefined) {break;}
		var tRec = $$("pitchTracksList").getItem(tnxt);
		newOrder.push(tRec.Pitch_Track);
		tid = tnxt;
    }	
	
	console.log(newOrder);
	// submit it
    url = '/data_pitch_tracks/?mde=neworder&seq=' + seq();
    data = {'NewOrder': newOrder};
	console.log(data);
    axios.post(url, data).then(response => 
    {
		gRes = response;
		var resData = response.data;
		console.log('got back', resData);
		// update pitch tracks
		wasOK = resData.status;
		if (wasOK == 'OK')
		{
			thePTs = resData.Pitch_Tracks;
			for (var ndx=0; ndx < thePTs.length; ndx++)
			{
				// update each Pitch_Track in the dataWH
				thisPT = thePTs[ndx];
				tst = dataWH.Pitch_Tracks.dataStore.getItem(thisPT.PT_ID);
				if (typeof(tst) == 'object')
				{ 					
					dataWH.Pitch_Tracks.dataStore.updateItem(tst.PT_ID,thisPT);
				}
			}
		}
		// drop flag
		gPTOrder_Dirty = false;		
    },
    (error) => 
    { 
		console.log("Error");
    }); 	
	
}
// ---------------------------------------------------------------------------- //
// service modules end