﻿var maxQueueLen = 500;
var _queue = "";
var _queueCount = 0;
var _queueCounties = null;
var addQueueXmlHttp, removeQueueXmlHttp, refreshQueueXmlHttp, 
    refreshQueueCountiesXmlHttp;
var populateQueueCountiesList = false;

object_AddEventListener(window, 'load', refreshQueue, false);

function County(state, fips, county, count) {
    this.state = state;
    this.fips = fips;
    this.county = county;
    this.count = count;
}

/*****************************
****** QUEUE FUNCTIONS *******
*****************************/

function MyPicksHelp() {
    //Show or Hide Queue Help Window, after above confirm may have popped, so it stays in foreground
	if(readCookieParam("SiteHelp", "QueueHowTo") != "Hide")
	{
	    var url;
	    var xmlHttp;
    
        url = ServerURL + "/lists/tutorial/mypicksinternal.asp";        
        xmlHttp = GetSynchronousXmlHttpObject();	
        xmlHttp.open("GET", url, false); 		
        xmlHttp.send(null);        
        
        document.getElementById("genericInfoDialogTitle").innerHTML = "What is \"My Picks\"?";
        document.getElementById("genericInfoDialogContent").innerHTML = xmlHttp.responseText;
        
	    showModalBox("genericInfoDialog", 500, 350, "", "CloseMyPicksHelpHandler()");
    }
} 


function getDailyExportCount() {
    var url, paramString;
    var count;
    var xmlHttp;
    
    url = ServerURL + "/lists/webmethods/_dailyexportcount.aspx";		
    paramString = "?x=1";    
    paramString += "&accountno=" + escape(ACCOUNTNO);
    
    xmlHttp = GetSynchronousXmlHttpObject();	
    xmlHttp.open("POST", url, false); 
    xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");		
    xmlHttp.send(paramString);
    
    count = xmlHttp.responseText;
    return parseInt(count);
}


function fetchQueue() {
    if (_queue == "" || _queue == null) refreshQueueSync();
    return _queue;
}

function refreshQueueSync() {
    var url, paramString;
    
    url = ServerURL + "/lists/webmethods/_queueretrieve.aspx";		
    paramString = "?x=1";    
    paramString += "&id=" + QueueID;
    
    refreshQueueXmlHttp = GetSynchronousXmlHttpObject();	
    refreshQueueXmlHttp.open("POST", url, false); 
    refreshQueueXmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");		
    refreshQueueXmlHttp.send(paramString);
    
    _queue = refreshQueueXmlHttp.responseText;
    if (_queue == null || _queue == "") _queueCount = 0;
    else _queueCount = _queue.split(',').length;
    return _queue;
}

function refreshQueue() {
    var url, paramString;
    
    url = ServerURL + "/lists/webmethods/_queueretrieve.aspx";		
    paramString = "id=" + QueueID;
    
    refreshQueueXmlHttp = GetXmlHttpObject(refreshQueue_StateChanged);	
    refreshQueueXmlHttp.open("POST", url, true); 	
    refreshQueueXmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    refreshQueueXmlHttp.send(paramString);
}

function refreshQueue_StateChanged() {
    if (refreshQueueXmlHttp.readyState == 4 || refreshQueueXmlHttp.readyState == "complete")
    {
        _queue = refreshQueueXmlHttp.responseText;
        
        if (_queue == null || _queue == "") _queueCount = 0;
        else _queueCount = _queue.split(',').length;
        
        refreshQueueCounties();
    }
}

function refreshQueueCounties() {
    var url, paramString;
    
    url = ServerURL + "/lists/webmethods/_queuecounties.aspx";		
    paramString = "x=1";    
    paramString += "&listings=" + _queue;
    
    refreshQueueCountiesXmlHttp = GetXmlHttpObject(refreshQueueCounties_StateChanged);	
    refreshQueueCountiesXmlHttp.open("POST", url, true); 
    refreshQueueCountiesXmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    refreshQueueCountiesXmlHttp.send(paramString);
}

function refreshQueueCounties_StateChanged() {
    if (refreshQueueCountiesXmlHttp.readyState == 4 || refreshQueueCountiesXmlHttp.readyState == "complete")
    {
        var counties = refreshQueueCountiesXmlHttp.responseXML.getElementsByTagName("county");
        _queueCounties = new Array();
                
        for (var index = 0; index < counties.length; index++) {
            var state = counties[index].attributes[0].value;
            var fips = counties[index].attributes[1].value;
            var county = counties[index].attributes[2].value;
            var count = counties[index].attributes[3].value;
            _queueCounties[index] = new County(state, fips, county, count);
        }
        
        if (populateQueueCountiesList) {
            refreshQueueCountiesSelect();
        }
    }
}

function refreshQueueCountiesSelect() {
    var div = document.getElementById("queueCountiesDivTop");
    var div2 = document.getElementById("queueCountiesDivBottom");
    var sel = document.getElementById("queueCountiesTop");
    var sel2 = document.getElementById("queueCountiesBottom");
    var selFIPS = document.QueueAction.selFIPS.value;   
    var index;
    var selFIPSStillExists = false;  // False if all the listings in the selected county were removed
    
    var offset = 0;

    if (sel != null) {
        if (sel.options.length > 0) {
            for (index = sel.options.length-1; index >= 0; index--) {
                sel.options[index] = null;
            }
        }
        
        if (_queueCounties == null || _queueCounties.length == 0) {
            div.style.visibility = "hidden";
        } 
        else {
            div.style.visibility = "visible";        
            
            if (_queueCounties.length > 1) {
                sel.options[0] = new Option("All Counties (" + _queueCount + " total picks)", "");
                offset = 1;
            }
            for (index = 0; index < _queueCounties.length; index++) {
                sel.options[index + offset] = 
                    new Option(_queueCounties[index].county + " County, " + _queueCounties[index].state + " (" + _queueCounties[index].count + " picks)"
                        , _queueCounties[index].fips);
                if (_queueCounties[index].fips == selFIPS) {
                    sel.selectedIndex = index + offset;
                    selFIPSStillExists = true;
                }
            }      
            
            if (!selFIPSStillExists && selFIPS != null && selFIPS.length > 0) {
                window.location.href='/Lists/ListQueue.asp?ordby=' + orderUpDn + orderBy;
            }
        }
        
        if (sel2 != null) {
            
            div2.style.visibility = div.style.visibility;
            for (index = sel2.options.length-1; index >= 0; index--) {
                sel2.options[index] = null;
            }
            for (index = 0; index < sel.options.length; index++) {
                sel2.options[index] = new Option(sel.options[index].text, sel.options[index].value);
            } 
            sel2.selectedIndex = sel.selectedIndex;
        }
    }
}


// Takes string as parameter
function addToQueue(value) {
    var picksFull = false;  
    
    if (_queueCount >= maxQueueLen)
        alert("My Picks is full.  Your listing cannot be added at this time.");
    else {
        if(("," + _queue).indexOf("," + value + ",") == -1) // do not have it
	    {
    	    // Check for first time in current Session
	        if(funcSessVars("RefreshQueue") != "Hide" && _queueCount > 0) 
	        {	
	            subSessVars ("RefreshQueue", "Hide");
		        var msg;
    		    
		        if (_queueCount == 1) 
		        {
		            msg = "There is 1 listing in My Picks.";
		        } else 
		        {
		            msg = "There are " + _queueCount + " listings in My Picks.";
		        }
		        msg += "  Would you like to empty My Picks before adding the new listing?";
    		    
		        document.getElementById("pendingResultsMsg").innerHTML = msg;
                showModalBox('replaceQueueDialog', 300, 90, "", 
                             "replaceQueueDialogHandler('" + value + "', 1, false)");		            
	        }
	        else addToQueueInternal(value, false);
	    } 
	    else 
	    {
	        showListingsTableMessage("The selected listing is already in My Picks.");
	    }
	}  
}

// Takes array as parameter
function addMultipleToQueue(values) {
    var numToAdd = 0;
    var listingsToAdd = "";
    
    if (_queueCount >= maxQueueLen)
        alert("My Picks is full.  Your listings cannot be added at this time.");
    else 
    {
        for (var i = 0; i < values.length; i++) 
        {
            if(("," + _queue).indexOf("," + values[i] + ",") == -1) // do not have it
	        {	            
	            if (numToAdd > 0) listingsToAdd += ",";
	            listingsToAdd += values[i];
	            numToAdd++;
        	    
		        if (_queueCount + numToAdd >= maxQueueLen)
		        {
			        break;
		        } 
	        }  
        }
        
        if (numToAdd > 0) 
        {
            // Check for first time in current Session
	        if(funcSessVars("RefreshQueue") != "Hide" && _queueCount > 0) 
	        {	
	            subSessVars ("RefreshQueue", "Hide");
		        var msg;
    		    
		        if (_queueCount == 1) {
		            msg = "There is 1 listing in My Picks.";
		        } else {
		            msg = "There are " + _queueCount + " listings in My Picks.";
		        }
		        msg += "  Would you like to empty My Picks before adding the new listings?";
    		    
    		    document.getElementById("pendingResultsMsg").innerHTML = msg;
                showModalBox('replaceQueueDialog', 300, 90, "", 
                             "replaceQueueDialogHandler('" + listingsToAdd + "')");		            
	        }
	        else {
                addToQueueInternal(listingsToAdd, false);  	    
	        }      
	    } 
	    else 
	    {
	        showListingsTableMessage("All the selected listings are already in My Picks.");
	    }
    }    
}

function addToQueueInternal(values, replace) {
    ListsService.AddToQueue(QueueID, values, replace, addToQueueInternal_Complete, addToQueueInternal_Error, null);
}

function addToQueueInternal_Complete(result, args) {
    var summary = eval(result);
    
    // If it was a success
    if (summary.Status == 1) 
    {
        var picksFull;
        var message, singular, countMsg;
                    
        picksFull = (summary.QueueCount >= maxQueueLen);        
        singular = " listing" + (summary.AddedCount == 1) ? " has " : "s have ";
        
        if (summary.QueueCount == 1) countMsg = "There is now " + summary.QueueCount + " listing in My Picks.";
        else countMsg = "There are now " + summary.QueueCount + " listings in My Picks.";
                    
        if (picksFull) {            
            message = summary.AddedCount + singular + "been added.  My Picks is now full.";
        } else {
            message = summary.AddedCount + singular + "been added to My Picks.  " + countMsg;
        }          
        showListingsTableMessage(message);        
        refreshQueue();  
        MyPicksHelp();  
    }
}
function addToQueueInternal_Error(result, args) {}

// Takes string as parameter
function removeFromQueue(value) {
    removeFromQueueInternal(value);
}

// Takes array as parameter
function removeMultipleFromQueue(values) {
    removeFromQueueInternal(values.join(','));
}
     
function removeFromQueueInternal(valueStr) {
    ListsService.RemoveFromQueue(QueueID, valueStr, removeFromQueueInternal_Complete, removeFromQueueInternal_Error, null);
}

function removeFromQueueInternal_Complete(result, args) {
    var summary = eval(result);
    
    if (summary.Status == 1) {
        var message, singular, countMsg;
             
        if (summary.RemovedCount > 150) {
    	    window.location.href = "/Lists/ListQueue.asp?d=" + numRemoved + "&c=" + queueCount;
        } else {       
            singular = " listing" + (summary.RemovedCount == 1) ? " has " : "s have ";
            
            if (summary.QueueCount == 1) countMsg = "There is now " + summary.QueueCount + " listing in My Picks.";
            else countMsg = "There are now " + summary.QueueCount + " listings in My Picks.";
                        
            message = summary.RemovedCount + singular + "been removed from My Picks.  " + countMsg;
            
            showListingsTableMessage(message);          
            refreshQueue();  
        }
    }
}
function removeFromQueueInternal_Error(result, args) {}

function UpdateQueueTitle(obj) {
    obj.title = "My Personal Hot List (" + _queueCount + " items)";
}