﻿var divArray = new Array();
var selectedCategory = "";
var highlightedTab = null;
var regenCategories = false;
var newCategory = false;
var deletionCounter = 0;
var categoriesCount = 0;

function Watchlist_LoadWatchlist(container, loadingContainer, countContainer, listname, edit, userID, symbol, editcategory, switchtab) {
    if(regenCategories){
        Watchlist_GenerateTabs( container, loadingContainer, countContainer, edit);
        regenCategories = false;
        //newCategory = true;
    }
    selectedCategory = listname;

    var params;
    if(listname == null)
        listname = "";
        
    params = 'editmode=' + edit + '&TabContainer=' + tabContainer + '&ContainerID=' + container + '&LoadingContainerID=' + loadingContainer + '&CountContainerID=' + countContainer + '&WatchlistName='+encodeURIComponent(listname) + "&Limit=" + rowsLimit;
    if(userID > 0)
        params = 'userID=' + userID + "&" + params;
        
    if(symbol != "-1" && symbol != undefined)
        params += '&symbol=' + symbol;

    if(showRecent)
        params += "&ShowRecent=" + showRecent;

    if(editcategory)
        params += "&editcategory=1";

    var req = new Ajax.Request('/AJAX/PostPages/Watchlist/GenerateWatchlistEntries.aspx', 
                               { method: 'post', 
                                 parameters: params, 
                                 onSuccess: function(AJAXResponse) {  Watchlist_PopulateWatchlist(AJAXResponse, container, loadingContainer, countContainer); selectedTab = listname; },
                                 onFailure: function(AJAXResponse) {  Watchlist_PopulateWatchlist(AJAXResponse, container, loadingContainer, countContainer);},
                                 onComplete: function(AJAXResponse){  if(switchtab && Watchlist_CountEntries(AJAXResponse.responseText) != 0){
                                                                        Watchlist_HiglightTabs($_(watchlistTabs_spanEditCategories), "watchlistTabs_divEditStocks");
                                                                        Watchlist_EditCategories("", container, true, container, loadingContainer, countContainer, listname, edit, userID, symbol, editcategory);
                                                                      }
                                                                   }
                               });
                               
    Watchlist_ShowLoading(loadingContainer,container, req);
}

function Watchlist_ShowLoading(loadingContainer,container, ajaxRequest) {
    if (ajaxRequest != null && ajaxRequest.transport.readyState != 4) {
        $_(loadingContainer).style.display = 'block';
        $_(container).style.display = 'none';
        $_(pnlNoWatchlist).style.display = 'none';
        return;
    }
    
    if ($_(loadingContainer).style.display == 'none'){
        $_(loadingContainer).style.display = 'block';
        $_(container).style.display = 'none';
        $_(pnlNoWatchlist).style.display = 'none';
    }
        
}

function Watchlist_HideLoading(loadingContainer, container) {
    if ($_(loadingContainer).style.display == 'block'){
        $_(loadingContainer).style.display = 'none';
        $_(container).style.display = '';
    }
}


function Watchlist_PopulateWatchlist(AJAXResponse, container, loadingDiv, countContainer) {
    if (AJAXResponse.status == 200) {
        $_(container).innerHTML = AJAXResponse.responseText;
        var count = Watchlist_CountEntries($_(container).innerHTML);
        $_(countContainer).innerHTML = count;

        var pnlWatchlist = $_(pnlNoWatchlist);
        if(count == 0){
            var textContainer = $_("txtContainer");
            textContainer.style.display = '';
            textContainer.style.marginTop='0px';
            Watchlist_AddStock(container, false);
        }else{
            pnlWatchlist.style.display = 'none';
            $_(txtWatchlistName).style.display = 'none';
        }
    }
    else
        $_(container).innerHTML = "Error loading watchlist, please refresh your browser";
    
    
    Watchlist_HideLoading(loadingDiv, container);
    
    
}

function Watchlist_BubbleManagement(divId){
    var showThisDiv = true;
    if(divArray.length >0){
        for(i=0; i<= divArray.length-1; i++){
            $_(divArray[i]).style.display = 'none';
            if(divArray[i] == divId)
               showThisDiv = false;
        }
        divArray = new Array();
     }
     if(showThisDiv){
        divArray.push(divId);  
        $_(divId).style.display = 'block';     
     }
}

function Watchlist_CountEntries(body){
    var indx = 0;
    var count = 0;
    var base = "lblCompanyName";
    while(body.indexOf(base,indx) != -1){
        indx = (body.indexOf(base,indx) + base.length);
        count++;
    }
    
    var categoriesBase = "lnkEditCategory";
    indx = 0;
    
    var tempCategoriesCount = categoriesCount;
    categoriesCount = 0;
    while(body.indexOf(categoriesBase,indx) != -1){
        indx = (body.indexOf(categoriesBase,indx) + categoriesBase.length);
        categoriesCount++;
    }

    if(tempCategoriesCount != categoriesCount)
        newCategory = true;
    
    return count;
}

function Watchlist_SubmitTickers(watchlistname, tickers, redirect, addPanel, container, loadingContainer, entryCountDiv, edit,
                                 countContainer, userID, symbol) 
{    
    if(redirect == "True")
        document.location = "/";
    else{
        var lblError = $_("lblError");
        if(watchlistname == "" || tickers == "")
            lblError.innerHTML = "To create your watchlist, a ticker and category name are required.";
        else{
            new Ajax.Request('/AJAX/PostPages/Watchlist/CreateWatchlist.aspx', 
                                        {method: 'post', 
                                         parameters: 'WatchlistName=' + encodeURIComponent(watchlistname) + '&Tickers=' + encodeURIComponent(tickers),
                                         onSuccess: function(AJAXResponse) {
                                                                            if(AJAXResponse.responseText == "True"){
                                                                                lblError.innerHTML = "";
                                                                                
                                                                                if(addPanel != undefined)
                                                                                    $_(addPanel).style.display = 'none';
                                                                                
                                                                               
                                                                                if($_("txtContainer").style.display == "" || watchlistname == "My Stocks"){
                                                                                    newCategory = true;
                                                                                    regenCategories = true;
                                                                                }else
                                                                                    Watchlist_GenerateTabs(container, loadingContainer, entryCountDiv, edit);
                                                                                    
                                                                                selectedCategory = null; 
                                                                                Watchlist_LoadWatchlist(container, loadingContainer, countContainer, selectedCategory, edit, userID, symbol, "-1");
                                                                                 
                                                                             }else{
                                                                                lblError.innerHTML = AJAXResponse.responseText;
                                                                             }
                                                                           }}
                                       );  
            }
    }
}

function Watchlist_GenerateTabs( rowContainerDiv, loadingDiv, entryCountDiv, edit) {
    $_(tabContainer).innerHTML = "<div class='watchlist_repopulatingTabs'>Repopulating...</div>&nbsp;";
    //newCategory = true;
    highlightedTab = null;
    var req = new Ajax.Request('/AJAX/PostPages/Watchlist/GetWatchlistTabs.aspx', {method: 'post', parameters: 'editmode=' + edit + '&TabContainerID=' + tabContainer + '&ContainerID='+rowContainerDiv+'&LoadingContainerID='+loadingDiv+'&CountContainerID='+entryCountDiv+'&ShowViewAllTab='+showViewAllTab, onSuccess: function(AJAXResponse) { Watchlist_PopulateTabs(AJAXResponse); } });  
}

function Watchlist_PopulateTabs(AJAXResponse, selectedTab) {
    if (AJAXResponse.status == 200){
        $_(tabContainer).innerHTML = AJAXResponse.responseText;
        sideInit();
        }
    else
        $_(tabContainer).innerHTML = "Error loading tabs, please refresh your browser";
    
}

function Watchlist_ToggleTag(toggleElement, tag, item, userID, categoriesBox) {
    if ($_(toggleElement).style.display == 'none') {
        new Ajax.Request('/AJAX/PostPages/SubmitStockTag.aspx', {method: 'post', parameters: 'tagtype=watchlist&ticker=' + item + '&tag=' + encodeURIComponent(tag) });
        $_(toggleElement).style.display = '';
        newCategory = true;
    }
    else {
        new Ajax.Request('/AJAX/PostPages/RemoveStockTag.aspx', {method: 'post', parameters: 'userID=' + userID + '&tagtype=watchlist&ticker=' + item + '&tag=' + encodeURIComponent(tag) });
        regenCategories = true;
        newCategory = true;
        $_(toggleElement).style.display = 'none';
        deletionCounter++;
    }   
    
    Watchlist_BubbleManagement(categoriesBox);
}

function Watchlist_Select(ddl, option, categoriesBox){ 
   $_(ddl).innerHTML = $_(option).innerHTML;
   var text = $_(txtWatchlistName);
   var textContainer = $_("txtContainer");
   if($_(option).id.indexOf("optionFooter") > -1) 
   {
       text.value = "My Stocks";
       text.style.display= '';
       textContainer.style.display = '';
       textContainer.style.marginTop='10px';
   }
   else
   {
       textContainer.style.display = 'none';
       text.value = $_(option).getAttribute("categoryName");
   } 
   
    Watchlist_BubbleManagement(categoriesBox);
}

function Watchlist_RemoveTag(tag, symbol, userID, container, loadingContainer, countContainer, isCategory) { 
    if(tag == null)
        tag = "";

    var alertMsg = "Are you sure you want to remove this stock from all watchlists?";
    
    if(tag != "")
        alertMsg = "Are you sure you want to remove this stock?"
        
    var confirmation = false;
    
    if(!isCategory)
        confirmation = confirm(alertMsg);
    
    if(isCategory || confirmation)    
    new Ajax.Request('/AJAX/PostPages/RemoveStockTag.aspx', 
                        {method: 'post', 
                         parameters: 'tag=' + encodeURIComponent(tag) + '&ticker=' + symbol + '&UserID=' + userID + '&tagtype=4', 
                         onSuccess: function(AJAXResponse) { 
                                                              
                                                              if($_(entryCount).innerHTML=="1" || isCategory){
                                                                  tag = null;
                                                                  regenCategories = true;
                                                                  newCategory = true;
                                                              }else
                                                                Watchlist_GenerateTabs(container, loadingContainer, countContainer, true);
                                                                
                                                              selectedCategory = null;          
                                                              Watchlist_LoadWatchlist(container, loadingContainer, countContainer, tag, true, userID, "-1"); 
                                                             }
                        });
}

function Watchlist_GetCategories() {
    new Ajax.Request('/AJAX/PostPages/Watchlist/GetWatchlistCategories.aspx', {method: 'post', 
                                                             parameters: 'valueFieldId=' + encodeURIComponent(txtWatchlistName), 
                                                             onComplete: function(AJAXResponse) { 
                                                                var container = $_("ddlContainer");
                                                                container.style.display = '';
                                                                container.innerHTML = AJAXResponse.responseText.replace("ddlCategoriesAjax_ddlWatchlist",ddlCategories);
                                                             }
                                                            });
}

function Watchlist_AddStock(watchlistTable, showDropDown, caller){
    
    var panel = $_(pnlNoWatchlist);
    var combo = $_(ddlCategories);
    var textContainer = $_("txtContainer");//$_(txtWatchlistName);
    var text = $_(txtWatchlistName);
    
    if(caller == null ||(caller == "AddNewStockTab" && panel.style.display == 'none')){
        if(text.style.display == 'none' && textContainer.style.display == ''){
            text.style.display = '';
            textContainer.style.display = 'none';
        }
            
        var counter = $_(entryCount);

        if(newCategory){
            Watchlist_GetCategories();
            textContainer.style.display = 'none';
        }
        
        var txtTickers = $_(pnlNoWatchlist.replace("pnlNoWatchlist","txtTickers"));
        txtTickers.value = "Enter Symbol...";

        if(carriedSymbol != "")
            txtTickers.value = carriedSymbol.toUpperCase();
       
        if(panel.style.display == ''){
            panel.style.display = 'none';
            $_(watchlistTable).style.display = '';
        }else{
            panel.style.display = '';
            $_(watchlistTable).style.display='none';
        }
        
       if(counter.innerHTML == "0" || parseInt(counter.innerHTML)-deletionCounter == 0){
            if(combo != null){
                if(combo.style.display == 'none' || (newCategory && counter.innerHTML == "0"))
                    textContainer.style.display = '';
            }else
                textContainer.style.display = '';
                  
            deletionCounter = 0;
       }
       
       newCategory = false;
   }
}

function Watchlist_HiglightTabs(tab, viewAllId){
    if(highlightedTab == null)
        highlightedTab = $_(viewAllId);

    highlightedTab.style.color = '';
    highlightedTab.style.fontWeight = '';
    highlightedTab = tab;
    highlightedTab.style.color = '#94000b';
    highlightedTab.style.fontWeight = 'bold';
}

function Watchlist_EditTabs(rowContainer){
        new Ajax.Request('/AJAX/PostPages/Watchlist/GenerateWatchlistEntries.aspx', {method: 'post', 
                                                             parameters: 'editcategory=1', 
                                                             onComplete: function(AJAXResponse) { 
                                                                var container = $_(rowContainer);
                                                                //container.style.display = '';
                                                                container.innerHTML = AJAXResponse.responseText;//.replace("ddlCategoriesAjax_ddlWatchlist",ddlCategories);
                                                             }
                                                            });

}

function Watchlist_EditCategoryActions(link){
    var lnkEditCategory;
    var lnkCancel;
    
    if(link.id.indexOf("lnkEditCategory") > -1){
        lnkEditCategory = link;
        lnkCancel = $_(link.id.replace("lnkEditCategory","lnkCancel"));
    }else{
        lnkEditCategory = $_(link.id.replace("lnkCancel","lnkEditCategory"));  
        lnkCancel = link;  
    }
            
    var trError = $_("trError");
    trError.style.display = 'none';
        
    var lnkSaveCategory = $_(lnkEditCategory.id.replace("lnkEditCategory","lnkSaveCategory"));
    var lnkDeleteCategory = $_(lnkEditCategory.id.replace("lnkEditCategory","lnkDeleteCategory"));
    var lblCategory = $_(lnkEditCategory.id.replace("lnkEditCategory","lblCategory"));
    var txtCategory = $_(lnkEditCategory.id.replace("lnkEditCategory","txtCategory"));

    if(lblCategory.style.display == ''){
        lblCategory.style.display = 'none';
        lnkEditCategory.style.display = 'none';
        lnkDeleteCategory.style.display = 'none';
        
        txtCategory.value = lblCategory.innerHTML;
        txtCategory.style.display = '';
        lnkSaveCategory.style.display = '';
        lnkCancel.style.display = '';
    }else{
        lblCategory.style.display = '';
        lnkEditCategory.style.display = '';
        lnkDeleteCategory.style.display = '';
        
        txtCategory.style.display = 'none';
        lnkSaveCategory.style.display = 'none';
        lnkCancel.style.display = 'none';
    }
}

function Watchlist_RenameCategory(id){
    var lblCategory = $_(id.replace("lnkSaveCategory","lblCategory"));
    var previousCategoryName = lblCategory.innerHTML;
    var newCategoryName = $_(id.replace("lnkSaveCategory","txtCategory")).value;
    
    var params = "PreviousWatchlistName=" + encodeURIComponent(previousCategoryName) + "&NewWatchlistName=" + encodeURIComponent(newCategoryName);
    var trError = $_("trError");
    trError.style.display = 'none';
    
        if(newCategoryName == ""){
            Watchlist_RowLoading(id);
            trError.style.display = '';
        }
        else
            new Ajax.Request('/AJAX/PostPages/Watchlist/RenameWatchlistCategory.aspx', {method: 'post', 
                                                                                         parameters: params, 
                                                                                         onSuccess: function(AJAXResponse) { 
                                                                                            if(AJAXResponse.responseText == "True"){
                                                                                                lblCategory.innerHTML = newCategoryName.replace(/\s/g,'-');
                                                                                                regenCategories = true;
                                                                                                newCategory = true;
                                                                                            }
                                                                                             
                                                                                         },
                                                                                         onComplete: function(AJAXResponse){
                                                                                            Watchlist_EditCategoryActions($_(lblCategory.id.replace("lblCategory","lnkCancel")));
                                                                                            Watchlist_RowLoading(id);
                                                                                         }
                                                                                        });
            
                                
}

function Watchlist_RowLoading(id){
    var trLoading = $_(id.replace("lnkSaveCategory","trLoading"));
    var trFields = $_(id.replace("lnkSaveCategory","trFields"));
    
    if(trLoading.style.display == ''){
        trLoading.style.display = 'none';
        trFields.style.display = '';
    }else{
        trLoading.style.display = '';
        trFields.style.display = 'none';
    }   
}

function Watchlist_EditCategories(id, watchlistTable, showDropDown, container, loadingContainer, countContainer, listname, edit, userID, symbol, editcategory){
    var pnlEditCategories = $_(id+"watchlistContent_pnlEditCategories");
    var pnlEditStocks = $_(id+"watchlistContent_pnlEditStocks");
    if(regenCategories)
        Watchlist_LoadWatchlist(container, loadingContainer, countContainer, listname, edit, userID, symbol, editcategory, true);      

    pnlEditCategories.style.display = '';
    pnlEditStocks.style.display = 'none';
   
    if($_(pnlNoWatchlist).style.display == '')
       Watchlist_AddStock(watchlistTable, showDropDown);
}

function Watchlist_EditStocks(id, container, loadingContainer, countContainer, listname, edit, userID, symbol, editcategory) {
    if(regenCategories)
        Watchlist_LoadWatchlist(container, loadingContainer, countContainer, listname, edit, userID, symbol, editcategory);
    else{
        var _pnlNoWatchlist = $_(pnlNoWatchlist);
        var pnlEditCategories = $_(id+"watchlistContent_pnlEditCategories");
        var pnlEditStocks = $_(id+"watchlistContent_pnlEditStocks");
        pnlEditCategories.style.display = 'none';
        pnlEditStocks.style.display = '';
        
        if(_pnlNoWatchlist.style.display == '')
            Watchlist_AddStock(container, true);
    }
}

function Watchlist_EnableIntro(){
    $_("watchlistIntro").style.display = 'none';
    new Ajax.Request('/AJAX/PostPages/Watchlist/SwitchWatchlistIntro.aspx', {method: 'post'});
}