﻿// Presentation Logic for Query services

//every external Javascript file that is being referenced from ScriptManager must have a call to Sys.Application.
if (typeof(Sys) !== "undefined") Sys.Application.notifyScriptLoaded();

var today = new Date();
var days = 365;
var expires_date = new Date(today.getTime() + (days * 86400000));
var SortFld = "Description";
var SortSeq = "ASC";

function GetTrackingDetails()
{
    BrassCraft.Query.GetTrackingDetails($get("_ctl0_ContentMain_spOrderRelease").innerText, OnSucceededWithContext);
}

function AddTrackDetails(Details)
{
    var child;
    var tbl;
    var tr;
    var td;
    for (var i=0;i<Details.length;i++)
    {
        child = $get("_ctl0_ContentMain_dv" + Details[i].TrackNo);
        if (child != null)
        {
            // Show the detail icon
            child.children[0].style.visibility = "visible";
            // Get the child table
            tbl = child.children[1];
            tr = tbl.insertRow(-1);
            td = tr.insertCell(-1);
            td.innerHTML = Details[i].ItemId;
            td = tr.insertCell(-1);
            td.style.textAlign = "right";
            td.innerHTML = Details[i].Qty;
        }
    }
}

function DocLibInstructions() {
    var div = $get("_ctl0_ContentMain_dvContents");
    var divInstructions = document.createElement("div");
    divInstructions.className = "DocLibInst";
    divInstructions.innerHTML = "<div class='Instructions'>Select Document Types, Product Families, and or enter search text</div>";
    div.appendChild(divInstructions); 
}

function DocLibQuery() {
    var tbl;
    var inp;
    var SearchText = $get("txtSearch").value;
    var SearchBy = "0";
    SearchBy = GetValue_sel("selSearchBy");
    SetCookie("DocLibSearchBy", SearchBy, expires_date);
    var showInactive = 0;
    if ($get("_ctl0_ContentMain_lblEdit").innerHTML == "1")
        showInactive = 1;
    // clear previous content
    $get("_ctl0_ContentMain_dvContents").innerHTML = ""
    //$get("_ctl0_ContentMain_tblContentTypes");

    // loop though "Content Type" checkboxes
    var ContentTypes = "";
    tbl = $get("_ctl0_ContentMain_tblContentTypes");
    var cells = tbl.getElementsByTagName("td");
    for (var i = 0; i < cells.length; i++) {
        inp = cells[i].getElementsByTagName("input");
        for (var y = 0; y < inp.length; y++) {
            if (inp[y].type == 'checkbox') {
                if (inp[y].checked == true) {
                    if (ContentTypes.length > 0) ContentTypes = ContentTypes + ",";
                    ContentTypes = ContentTypes + inp[y].value;
                }
            }
        }
    };

    // Loop through "Product Family" checkboxes
    var ProductFamilies = "";
    tbl = $get("_ctl0_ContentMain_tblProductFamilies");
    var cells = tbl.getElementsByTagName("td");
    for (var i = 0; i < cells.length; i++) {
        inp = cells[i].getElementsByTagName("input");
        for (var y = 0; y < inp.length; y++) {
            if (inp[y].type == 'checkbox') {
                if (inp[y].checked == true) {
                    if (ProductFamilies.length > 0) ProductFamilies = ProductFamilies + ",";
                    ProductFamilies = ProductFamilies + inp[y].value;
                }
            }
        }
    };

    $get("txtSearch").focus(); 
    BrassCraft.Query.DocLib(SearchText, ContentTypes, ProductFamilies, SortFld + " " + SortSeq, showInactive, SearchBy, OnSucceededWithContext, OnFailed);
}

// This is the callback function invoked if the Web service succeeded
function OnSucceededWithContext(result, userContext, methodName)
{
    switch (methodName.toLowerCase()) {
        case "DocLib".toLowerCase() :
            PopulateDocLibRows(result);
        	break;
        case "Distributors".toLowerCase() :
        	break;
        case "GetTrackingDetails".toLowerCase() :
            AddTrackDetails(result);
        	break;
	}	
}

// This is the failed callback function.
function OnFailed(error)
{
    var StackTrace = error.get_stackTrace();
    var Message = error.get_message();
    var StatusCode = error.get_statusCode();
    var ExceptionType = error.get_exceptionType();
    var TimedOut = error.get_timedOut();
       
    switch (ExceptionType.toLowerCase()) {
        case "system.applicationexception":
            alert(Message);
            break;
        default:
            // Display the error.    
            //            $get("_ctl0_ContentMain_dvContents").innerHTML = 
            //                "Stack Trace: " +  StackTrace + "<br/>" +
            //                "Service Error: " + Message + "<br/>" +
            //                "Status Code: " + StatusCode + "<br/>" +
            //                "Exception Type: " + ExceptionType + "<br/>" +
            //                "Timedout: " + TimedOut;        
            $get("_ctl0_ContentMain_dvContents").innerHTML = '<div class="Errors" style="margin: 20px"><img src="images/bullet_nav_big.gif" />' + Message + '</div>';
            break;
    }
}

function PopulateDocLibRows(Documents)
{
    var tr;
    var td;
    var anc;
    var img;
    var CssClass;
    var cls;
    var Docs = " Documents";
    if (Documents.length == 1)
        Docs = " Document"
    $get("lblResults").innerHTML = "&nbsp;" + Documents.length + Docs + " found";
    var div = $get("_ctl0_ContentMain_dvContents");
    if(div.childNodes.length > 0) {
        obj = div.childNodes[0];
        div.removeChild(obj);
    }
    var tbl = document.createElement("table");
    tbl.id = "tblResults";
    tbl.className = "Results";
    tbl.cellPadding = "0";
    tbl.cellSpacing = "0";
    tbl.border = "0";
    tbl.align = "center";
    if (Documents.length > 0) {
        AddDocLibHeaderRow(tbl);
    } else {
        tr = tbl.insertRow(-1);
        td = tr.insertCell(-1);
        td.colSpan = 3;
        td.innerHTML = "<img src='images/bullet_nav_big.gif'>Sorry, No documents found with the specified criteria";
        td.className = "Errors";
        tbl.id = "tbl";
        tbl.style.width = "100%";
        tbl.style.paddingTop = "12px";
        tbl.style.paddingLeft = "10px";
        
    }
    CssClass = "eRw";
    for (var i=0;i<Documents.length;i++)
    {
        CssClass = (CssClass=='eRw') ? 'oRw' : 'eRw';
        if(Documents[i].Active == false)
        {
            cls = "ia_pdf";
        } else {
            cls = "pdf";
        }
        tr = tbl.insertRow(-1);
        tr.className = CssClass;
        if (Documents[i].Updated != null)
        {                                    
            AddTableCell(tr, null, null, 428, null, null, CreateAnchor(Documents[i].Description, cls, Documents[i].Link, "_blank", "View/Download")); 
            AddEditLink(tr.firstChild, Documents[i].Id);
            AddTableCell(tr, Documents[i].Size, null, 62, "right");
            AddTableCell(tr, Documents[i].Updated, null, 74, "center");
        } else {
            AddTableCell(tr, Documents[i].Description,  null, null, null, 3); 
            AddEditLink(tr.firstChild, Documents[i].Id);
        }
    }        
    div.appendChild(tbl);
    // Clean up
    div = null;
    CssClass = null;
    tbl = null;
    tr = null; 
    td = null; 
}

function GetDefaults()
{
    if (GetCookie("DocLibSortFld") != null) SortFld = GetCookie("DocLibSortFld");
    if (GetCookie("DocLibSortSeq") != null) SortSeq = GetCookie("DocLibSortSeq");
    if (GetCookie("DocLibSearchBy") != null)
        SetValue_sel("selSearchBy", GetCookie("DocLibSearchBy"));
    else
        SetValue_sel("selSearchBy", "2");
}   
        
function AddDocLibHeaderRow(tbl)
{
    var tr;
    tr = tbl.insertRow(-1);
    AddTableHeaderCell(tr, "Description", 428,  null, "Description", "left");
    AddTableHeaderCell(tr, "Size", 62, null, null, "right");
    AddTableHeaderCell(tr, "Updated", 74, null, "Updated");
    tr = null;
}

function AddTableCell(tr, sHTML, classname, width, align, colspan, obj)
{
    var td = tr.insertCell(-1);
    if (classname != null) 
        td.className = classname;
    if (width != null)
        td.width = width;
    if (colspan != null)
        td.colSpan = colspan;
    if (align != null)
        td.align = align;
    if (sHTML != null)
    td.innerHTML = sHTML;
    if (obj != null)
        td.appendChild(obj)
    td = null;
}

function CreateAnchor(sHTML, classname, link, target, tooltip)
{
    var anc = document.createElement("a");
    anc.href = link;
    if (classname != null)
        anc.className = classname;
    if (tooltip != null)
        anc.title = tooltip;
    if (target != null)
        anc.target = target;
    if (sHTML != null) 
    {
        anc.innerHTML = sHTML;
    } else {
        anc.innerHTML = "&nbsp;";
    }
    return anc
}

function AddEditLink(td, id)
{
    if ($get("_ctl0_ContentMain_lblEdit").innerHTML == "1")
    {        
        td.appendChild(CreateAnchor(null, "edit", "ContentEdit.aspx?Id=" + id, "_parent", "Edit Doc Id: " + id))
    }
}

function AddTableHeaderCell(tr, sHTML, width, colSpan, SortField, align)
{
    var th = document.createElement("th");
    var onclick;
    var cls;
    var sort;
    th.innerHTML = sHTML;
    if (SortField != null)
    {
        onclick = "toggleSort('" + SortField + "')";
        if (SortFld == SortField)
            cls = "btn"
        else
            cls = "hidden"
        if (SortSeq == "ASC")
            sort = "ASC.gif"
        else
            sort = "DESC.gif"
        th.onclick=new Function(onclick);
        th.title = "Click Column to Sort";
        th.style.cursor = "pointer";
        AddImagetoCell(th, null, "images/" + sort, null, cls);
    }            
    if (align != null)
        th.align = align;
    if (width != null)
        th.width = width;
    if (colSpan != null)
        th.colSpan = colSpan;
    tr.appendChild(th)
    th = null;
}

function AddImagetoCell(td, onclick, src, tooltip, classname)
{
    var img = document.createElement("img");
    img.onclick=new Function(onclick);
    if (tooltip != null)
        img.title = tooltip;
    img.src = src;
    if (classname != null) 
        img.className = classname;
    else
        img.className = "btn";
    td.appendChild(img);
    img = null;       
}

function noenter(event, funcName, value) {
    if (event) {
        switch (event.keyCode) 
        {
            case 13: // carrage return (enter)
                event.returnValue = false;
                event.cancel = true;
                if (funcName != null) eval(funcName);
                return false;
                break;
            case 44 : // , (comma)
            case 46 : // . (period)
            case 58 : // : (colon)
            case 59 : // ; (semicolon)
            case 32 : //   (space)
                if (funcName != null) eval(funcName);
                break;
        }
    }
}

function toggleSort(SortField)
{
    SortSeq = (SortSeq == 'ASC') ? 'DESC' : 'ASC';
    SortFld = SortField;
    SetCookie("DocLibSortFld", SortFld, expires_date);
    SetCookie("DocLibSortSeq", SortSeq, expires_date);
    DocLibQuery();
}

function GetValue_sel(sel) {
    sel = $get(sel);
    if (sel.selectedIndex != null)
        return sel[sel.selectedIndex].value;
}

function SetValue_sel(sel, value) {
  sel = $get(sel);
  for (i = 0; i < sel.length; i++) {
      if (sel[i].value == value)
          sel.selectedIndex = i;
  }
}
