﻿// Scripts for Podcasting Solution for Microsoft Sharepoint

var categoryDisplayNames = new Array(
    new Array("PodcastPublishDate", "Time"),
    new Array("PodcastLanguage", "Language"),
    new Array("TargetedAudience", "Targeted Audience"),
    new Array("TargetedAudienceLevel", "Level")
);

function cbqFilter() { }
cbqFilter.prototype.Type;
cbqFilter.prototype.Column;
cbqFilter.prototype.Value;
cbqFilter.prototype.Operation;
cbqFilter.prototype.ColumnType;

var cbqPage = 1;

var otherQueryParams = new Array();

//Cybage:-New variable declared

var count = 0;
//


function addCategoryFilter(filterName, filterValue) {
    // get the current url
    var pageName = window.location.pathname;
    pageName = pageName.substring(pageName.lastIndexOf('/') + 1);
    pageName = pageName.toLowerCase();
	// get current params
    var params = (pageName == "pkshomepage.aspx") ? getQueryStringParams() : new Array();
    var foundItem = false;
    for (var i = 1; i < params.length; i++) {
        if (params[i] == null) continue;
        if (params[i].Type == "filter" && params[i].Column.toLowerCase() == filterName.toLowerCase()) {
            foundItem = true;
            if (params[i].ColumnType == "DateTime") {
                params[i].Value = CreateDateFilter(filterValue);
            }
            else {
                params[i].Value = filterValue;
            }
        }
    }
    if (!foundItem) {
        if ("All Today ThisWeek ThisMonth ThisYear".indexOf(filterValue) >= 0) {
            var item = new cbqFilter();
            item.Type = "filter";
            item.Column = filterName;
            item.Value = CreateDateFilter(filterValue);
            item.Operation = "Geq";
            item.ColumnType = "DateTime";
            var index = (params.length == 0) ? 1 : params.length;
            params[index] = item;
        }
        else {
            var item = new cbqFilter();
            item.Type = "filter";
            item.Column = filterName;
            item.Value = filterValue;
            item.Operation = "Eq";
            item.ColumnType = "Text";
            var index = (params.length == 0) ? 1 : params.length;
            params[index] = item;
        }
    }
    buildNewQueryString(params);
}

function getBaseLocation() {
    //return window.location.href.split(/\?/)[0];
	return "/Pages/PKSHomePage.aspx";
}

function getQueryStringParams() {
    var cbq = new Array();
    otherQueryParams = new Array();
    var qstring = window.location.href.split(/\?/)[1];
    if (qstring == null) return cbq;

    qstring = qstring.split(/\&/);
    for (var i = 0; i < qstring.length; i++) {
        var param = qstring[i].substring(0, 2);
        var index = (param == "sf" || param == "so") ? 0 : qstring[i].substring(2, 3);
        var value = qstring[i].split(/=/)[1];

        if (cbq[index] == null) cbq[index] = new cbqFilter();

        switch (param.toLowerCase()) {
            // Sort Params 
            case "ff":
                cbq[index].Type = "filter";
                cbq[index].Column = value;
                break;
            case "fv":
                cbq[index].Value = value;
                break;
            case "fo":
                cbq[index].Operation = value;
                break;
            case "ft":
                cbq[index].ColumnType = value;
                break;
            // Sort Params 
            case "sf":
                cbq[index].Type = "sort";
                cbq[index].Column = value;
                break;
            case "so":
                cbq[index].Value = value;
                break;
            case "pg":
                cbqPage = value;
                break;
            default:
                otherQueryParams[otherQueryParams.length] = qstring[i].split(/=/)[0] + "=" + value;
        }
    }
    return cbq;
}

function buildFilters(divName) {
    var maxWidth = 556;  // the max pixel width the filters can grow before they wrap to a new line
    var totalWidth = 0;

    // get the container
    var div = document.getElementById(divName);
    if (div == null) alert("Cannot create Filter Bar.");
    // build a nasty table
    var table = document.createElement("table");
    var tbody = document.createElement("tbody");
    var tr = document.createElement("tr");
    div.appendChild(table);
    table.appendChild(tbody);
    tbody.appendChild(tr);

    var params = getQueryStringParams()
    // if there aren't any params
    if (params.length == 0) {
        return;
    }
    else {
        //var totalWidth = 0;
        for (var i = 0; i < params.length; i++) {
            if (params[i] == null) continue;
            if (params[i].Type != "filter") continue;
            // check to see if we need to wrap to a new row
            if (totalWidth >= maxWidth) {
                table = document.createElement("table");
                tbody = document.createElement("tbody");
                tr = document.createElement("tr");
                div.appendChild(table);
                table.appendChild(tbody);
                tbody.appendChild(tr);
            }
            // add a cell with the parameter's value
            var td = document.createElement("td");
            tr.appendChild(td);

            var val;
            if (params[i].ColumnType == "DateTime") {
                val = GetFilterNameFromDate(params[i].Value);
            }
            else {
                val = params[i].Value;
            }
            // create the table to hold the filter value
            var type = params[i].Column;
            var displayName = lookupFilterDisplayName(params[i].Column)

            var tbl = document.createElement("table");
            tbl.setAttribute("cellSpacing", "0");
            tbl.setAttribute("cellPadding", "0");
            var tb = document.createElement("tbody");
            var row = document.createElement("tr");
            var col = document.createElement("td");
            var tb2 = document.createElement("table");
            tb2.setAttribute("cellSpacing", "0");
            tb2.setAttribute("cellPadding", "0");
            tb2.setAttribute("width", "100%");
            var tb21 = document.createElement("tbody");
            var row21 = document.createElement("tr");
            var col21 = document.createElement("td");
            var col22 = document.createElement("td");
            col21.appendChild(document.createTextNode(displayName));
            col21.className = "pks-filter-type";
            col22.appendChild(document.createTextNode("x"));
            col22.className = "pks-filter-x";
            row21.appendChild(col21);
            row21.appendChild(col22);
            tb21.appendChild(row21);
            tb2.appendChild(tb21);
            col.appendChild(tb2);

            // use the double function trick to keep the variables
            // scoped properly
            col22.onclick = (function(t, v) { return function() { removeCategoryFilter(t, v); }; })(type, val);
            // old way that will only ever remove the last filter
            // span.onclick = function() { removeCategoryFilter(type, val); };

            // add the top two rounded corners

            var corner = document.createElement("span");
            corner.className = "pks-filter-corner-topleft";
            col21.appendChild(corner);
            corner = document.createElement("span");
            corner.className = "pks-filter-corner-topright";
            col22.appendChild(corner);
            row.appendChild(col);
            tb.appendChild(row);
            // start the bottom row
            row = document.createElement("tr");
            col = document.createElement("td");
            // insert the filter value
            col.appendChild(document.createTextNode(val + " ..."));
            // add the bottom two rounded corners
            col.className = "pks-filter-detail";
            corner = document.createElement("span");
            corner.className = "pks-filter-corner-bottomleft";
            col.appendChild(corner);
            corner = document.createElement("span");
            corner.className = "pks-filter-corner-bottomright";
            col.appendChild(corner);
            row.appendChild(col);
            tb.appendChild(row);
            tbl.appendChild(tb);
            td.appendChild(tbl);
            td.className = "pks-filter-item";
            //add the width of this filter to the total
            //totalWidth += td.offsetWidth;
            totalWidth += 100;

        }
    }
}



function lookupFilterDisplayName(title) {
    var value = title;
    for (var i = 0; i < categoryDisplayNames.length; i++) {
        var namePair = categoryDisplayNames[i];
        if (namePair[0] == title) {
            value = namePair[1];
            break;
        }
    }
    return value;
}
function lookupFilterTitle(displayName) {
    var value = displayName;
    for (var i = 0; i < categoryDisplayNames.length; i++) {
        var namePair = categoryDisplayNames[i];
        if (namePair[1] == displayName) {
            value = namePair[0];
            break;
        }
    }
    return value;
}

function openFilterPopup(item) {
    var div = document.createElement("div");
    var div2 = document.createElement("div");
    div2.appendChild(document.createTextNode("Remove"));
    div2.className = "am-filterPopup-text";

    div.className = "am-filterPopup";
    div.style.top = item.offsetHeight;
    div.style.left = 0;
    div.style.width = item.offsetWidth - 2;

    var text = item.innerText;
    text = text.replace(/\//, "");   // this is the regex for "/"
    text = text.split(/[ >> ]/);
    var filterName = lookupFilterTitle(text[0]);
    var filterValue = text[1];
    div.onclick = function() { removeCategoryFilter(filterName, filterValue); };

    div.appendChild(div2);
    item.appendChild(div);
    //Cybage:Removed bgcoclor
    //item.style.backgroundColor = "#666";
    //

}

function closeFilterPopup(item) {
    var divs = item.getElementsByTagName("div");
    for (var i = 0; i < divs.length; i++) item.removeChild(divs[i]);
    //Cybage:Removed bgcoclor
    //item.style.backgroundColor = "black";
    //

}

function removeCategoryFilter(filterName, filterValue) {
    var href = getBaseLocation();
    var params = getQueryStringParams();

    for (var i = 1; i < params.length; i++) {
        if (params[i] == null) continue;
        if (params[i].Column == filterName) params[i] = null;
    }
    buildNewQueryString(params);
}

function buildNewQueryString(params) {
    var href = getBaseLocation();
    var pstring = "";
    var filterIndex = 1;
    for (var i = 0; i < params.length; i++) {
        if (params[i] == null) continue;
        if (pstring.length == 0) pstring += "?";
        else pstring += "&";

        if (params[i].Type == "filter") {
            pstring += "ff" + filterIndex + "=" + params[i].Column;
            pstring += "&fv" + filterIndex + "=" + params[i].Value;
            pstring += "&fo" + filterIndex + "=" + params[i].Operation;
            pstring += "&ft" + filterIndex + "=" + params[i].ColumnType;
            filterIndex++;
        }
        else if (params[i].Type == "sort") {
            pstring += "sf1=" + params[i].Column;
            pstring += "&so1=" + params[i].Value;
        }
    }
    if (pstring == "") pstring += "?pg=" + cbqPage;
    else if (pstring == "?") pstring += "pg=" + cbqPage;
    else pstring += "&pg=" + cbqPage;
    for (var i = 0; i < otherQueryParams.length; i++) {
        pstring += "&" + otherQueryParams[i];
    }

    window.location = href + pstring;
}

function openSortDropdown(item) {
    var divs = item.getElementsByTagName("div");
    var div;
    for (var i = 0; i < divs.length; i++) if (divs[i].className == "am-grid-sortdropdown") div = divs[i];
    if (div == null) return;

    div.style.top = 24;
    div.style.left = 24;
    div.style.display = "block";
}

function closeSortDropdown(item) {
    var divs = item.getElementsByTagName("div");
    var div;
    for (var i = 0; i < divs.length; i++) if (divs[i].className == "am-grid-sortdropdown") div = divs[i];
    if (div == null) return;
    div.style.display = "none";
}

function sortGrid(sortType) {
    // get the current url
    var href = getBaseLocation();
    var params = getQueryStringParams();
    var foundItem = false;
    for (var i = 0; i < params.length; i++) {
        if (params[i] == null) continue;
        if (params[i].Type == "sort") {
            foundItem = true;
            if (params[i].Column == sortType) {
                params[i].Value = (params[i].Value == "true") ? "false" : "true";
            }
            else {
                params[i].Column = sortType;
                params[i].Value = (sortType == "Rating" || sortType == "Downloads") ? "false" : "true";
            }
        }
    }
    if (!foundItem) {
        var item = new cbqFilter();
        item.Type = "sort";
        item.Column = sortType;
        item.Value = (sortType == "Rating" || sortType == "Downloads") ? "false" : "true";
        var index = 0;
        params[index] = item;
    }
    buildNewQueryString(params);
}

function CheckPrevPageLink(senderId) {
    var sender = document.getElementById(senderId);
    var params = getQueryStringParams();
    if (cbqPage <= 1) {
        sender.style.display = "none";
    }
}

function FirstPage() {
    var params = getQueryStringParams();
    cbqPage = 1;
    buildNewQueryString(params);
}

function NextPage() {
    var params = getQueryStringParams();
    cbqPage++;
    buildNewQueryString(params);
}

function PrevPage() {
    var params = getQueryStringParams();
    cbqPage--;
    if (cbqPage <= 0) cbqPage = 1;
    buildNewQueryString(params);
}

function CreateDateFilter(value) {
    var date = new Date();
    switch (value) {
        case "All": date.setFullYear(1900, 0, 1); break;
        case "Today": /* Already set to Today */break;
        case "ThisWeek": date.setDate(date.getDate() - date.getDay()); break;
        case "ThisMonth": date.setFullYear(date.getFullYear(), date.getMonth(), 1); break;
        case "ThisYear": date.setFullYear(date.getFullYear(), 0, 1); break;
    }
    return (date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate() /*+ "T00:00:00Z"*/)
}

function GetFilterNameFromDate(value) {
    var date = new Date();
    var dateStr;
    if (value.indexOf('T') > 0) dateStr = value.substring(0, value.indexOf('T'));
    else dateStr = value;
    dateStr = dateStr.split('-');
    date.setFullYear(dateStr[0]);
    date.setMonth(dateStr[1] - 1);
    date.setDate(dateStr[2]);

    if (date.getFullYear() == 1900) return "All";
    var today = new Date();
    if (date.toDateString() == today.toDateString()) return "Today";
    var week = new Date();
    week.setDate(today.getDate() - today.getDay())
    if (date.toDateString() == week.toDateString()) return "This Week";
    var month = new Date();
    month.setFullYear(today.getFullYear(), today.getMonth(), 1);
    if (date.toDateString() == month.toDateString()) return "This Month";
    var year = new Date();
    year.setFullYear(today.getFullYear(), 1, 1);
    if (date.toDateString() == year.toDateString()) return "This Year";

    return value;
}

function CreateSortMarker(listId) {
    var params = getQueryStringParams();
    var sortItem;
    var sortDir;
    for (var i = 0; i < params.length; i++) {
        if (params[i] == null) continue;
        if (params[i].Type == "sort") {
            sortItem = params[i].Column;
            sortDir = params[i].Value;
            break;
        }
    }
    if (sortItem == null) return;

    var list = document.getElementById(listId);
    if (list == null) return;
    var li = list.getElementsByTagName("li");
    if (li == null || li.length == 0) return;
    for (var i = 0; i < li.length; i++) {
        var links = li[i].getElementsByTagName("a");
        if (links == null || links.length == 0) continue;
        var link = links[0];
        var field = link.attributes["field"];
        if (field == null) continue;
        if (sortItem == field.value) {
            if (sortDir == "true") {
                var img = document.createElement("img");
                img.src = "/Style Library/PodcastingKit/Images/down_arrow.gif";
                img.alt = "ascending";
				img.style.height = "7px";
                img.style.paddingLeft = "8px";
                img.style.paddingBottom = "";
                img.style.border = "none";
                link.appendChild(img);
            }
            else {
                var img = document.createElement("img");
                img.src = "/Style Library/PodcastingKit/Images/up_arrow.gif";
                img.alt = "descending";
				img.style.height = "7px";
                img.style.paddingLeft = "8px";
                img.style.paddingBottom = "";
                img.style.border = "none";
                link.appendChild(img);
            }
        }
    }

}

function CreatePodcastMailtoLinkToPage(subject, body) {
    var mailtoSubject = subject;
    var mailtoBody = 'Hello, check out this Podcast called: ' + mailtoSubject;
    mailtoBody += '\n' + window.location;
    mailtoBody += '\n\nDecription:\n' + RichTextToPlainText(body, false);
    if (mailtoSubject.length > 50) mailtoSubject = mailtoSubject.substring(0, 47) + '...';
    var sendToFriend = 'mailto:?subject=' + escape(mailtoSubject) + '&body=' + escape(mailtoBody);
    window.location = sendToFriend;
}

function RichTextToPlainText(html, addLineBreaks) {
    html = unescape(html);
    var lineBreak = (addLineBreaks) ? "\r" : " ";

    // Text Block Tags
    html = html.replace(/<div.*?>|<p.*?>|<font.*?>|<span.*?>|<\/font>|<\/span>/gi, "");
    html = html.replace(/<\/div>|<\/p>|<br.*?>/gi, lineBreak);
    // List Tags
    html = html.replace(/<ol.*?>|<ul.*?>|<\/ol>|<\/ul>|<\/li>/gi, lineBreak);
    html = html.replace(/<li.*?>/gi, " * ");
    // Style Tags
    html = html.replace(/<b>|<\/b>|<strong>|<\/strong>|<i>|<\/i>|<em>|<\/em>|<u>|<\/u>/gi, "");
    // Table Tags
    html = html.replace(/<table.*?>|<\/table>/gi, lineBreak);
    if (addLineBreaks) html = html.replace(/<\/tr>/gi, lineBreak);
    else {
        html = html.replace(/<\/tr>(?:.*?<tr.*?>)/gi, ", ");
        html = html.replace(/<\/tr>/gi, "; ");
    }
    html = html.replace(/<\/td>.*<td>|<\/td>.*[\n|\r].*<td>/gi, ", ");
    html = html.replace(/<tr.*?>|<td.*?>|<\/td>|<tbody>|<\/tbody>/gi, "");
    // Links
    html = html.replace(/<img.*?src=(\x22|\x27)(.*?)\1.*?alt=(\x22|\x27)(.*?)\3.*?>/gi, "$4 ($2)");
    html = html.replace(/<img.*?alt=(\x22|\x27)(.*?)\1.*?src=(\x22|\x27)(.*?)\3.*?>/gi, "$2 ($4)");
    html = html.replace(/<\/img>/gi, "");
    html = html.replace(/<a.*?href=(\x22|\x27)(.*?)\1.*?>(.*?)<\/a>/gi, "$3 ($2)");
    // Erroneous Line Breaks
    html = html.replace(/\n+/g, lineBreak);
    html = html.replace(/\r+/g, lineBreak);
    // No Breaking Spaces
    html = html.replace(/\&nbsp;/gi, " ");
    if (!addLineBreaks) {
        html = html.replace(/\x20+/g, " "); // fix multiple spaces
    }

    return html;
}


///////////////////////////////
//  PODCAST DETAILS SCRIPTS  //
///////////////////////////////

var fileUrl = '/_layouts/MSIT.CustomPages/Download.aspx';
var useDownloadTracking = true;

function SetFileUrl(value) {
    try {
        if (value.indexOf('?') < 0) {
            useDownloadTracking = false;
            fileUrl = value;
        }
        else {
            useDownloadTracking = true;
            fileUrl = value.split('?')[0];
        }
    }
    catch (ex)
	{ }
}

function GetWebId(csId) {
    csId = unescape(csId);
    return csId.split('@')[0];
}

function GetListId(csId) {
    csId = unescape(csId);
    return csId.split('@')[1];
}

function RenderRatings(csId, id, rating, title) {
    var webId = GetWebId(csId);
    var listId = GetListId(csId);
    var url = '';
    var template = '@DefaultSettings$';

    renderListRatingControl(listId, rating, id, title, url, template, webId);
}

function BuildFlagAsInappropriateLink(elementId, csId) {
    var flagAsInappropriateLink = document.getElementById(elementId);

    var addOnChar = '?';
    if (flagAsInappropriateLink.href.indexOf('?', 0) > 0)
    { addOnChar = '&'; }

    flagAsInappropriateLink.href += addOnChar;
    flagAsInappropriateLink.href += 'List=';
    flagAsInappropriateLink.href += GetListId(csId);


    addOnChar = '&';

    flagAsInappropriateLink.href += addOnChar;
    flagAsInappropriateLink.href += 'source=';
    flagAsInappropriateLink.href += escape(document.URL);
}

function KillLead(x) {
    if (!x) { return ''; }
    if (x == '') { return ''; }
    if (x.length == 1) { return x; }

    if (x.substr(0, 1) != '<') {
        x = x.substr(1);
    }

    return x;
}

function Replace(x, y, z) {
    while (x.indexOf(y) >= 0) {
        x = x.replace(y, z);
    }

    return x;
}

function UnHTMLEscape(x) {

    //unescape doesn't do this:
    x = Replace(x, '&lt;', '<');
    x = Replace(x, '&gt;', '>');
    x = Replace(x, '&apos;', "'");
    x = Replace(x, '&quot', '"');
    x = Replace(x, '&amp;', '&');

    x = unescape(x);

    return x;
}

function LoadXml(x) {
    try {
        xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
        xmlDoc.async = "false";
        xmlDoc.loadXML(x);
        return xmlDoc;
    }
    catch (e) {
        try {
            parser = new DOMParser();
            return parser.parseFromString(x, "text/xml");
        }
        catch (e)
		{ }
    }

    return null;
}

function RenderSupportMaterial(sourceId, targetId, supportFilesId, csId, itemId) {
    var xml = document.getElementById(sourceId).innerHTML;
    xml = UnHTMLEscape(xml);
    xml = KillLead(xml);
    xml = LoadXml(xml);

    var o = '<div align="center"><div style="font-size: medium; width: 85%;" align="left">';
    var files = xml.getElementsByTagName("ExternalFileInfo");
    var count = 0;

    for (var i = 0; i < files.length; i++) {
        var fileName = files[i].getElementsByTagName("FileName")[0].childNodes[0].nodeValue;
        var isPrimary = files[i].attributes.getNamedItem("IsPrimary").nodeValue.toUpperCase();
        var clientLink = files[i].getElementsByTagName("ClientLink")[0].childNodes[0].nodeValue;
        var dispName = files[i].getElementsByTagName("OriginalFileName");

        try {
            if ((dispName == null) || (dispName.length < 1)) {
                dispName = fileName;
            }
            else {
                dispName = dispName[0].childNodes[0].nodeValue
            }
        }
        catch (ex) {
            dispName = fileName;
        }


        if (isPrimary != "TRUE") {
            var link = '';
            if (useDownloadTracking) {
                link = fileUrl + "?csid=" + csId + "&id=" + itemId + "&file=" + fileName;
            }
            else {
                link = clientLink;
            }

            //if (count > 0){o += ", ";}
            o += "<a href='" + link + "'>";
            o += dispName;
            o += "</a><br />";
            count++;
        }
        else {
            if (useDownloadTracking) {
                var downloadLink = document.getElementById('aDownloadLink');
                downloadLink.href = fileUrl + "?csid=" + csId + "&id=" + itemId;
            }
        }
    }
    o += "</div></div>";

    var strFiles = "(" + count + " Files)";
    if (count == 0) { strFiles = "(No Files)"; }
    if (count == 1) { strFiles = "(1 File)"; }

    if ((supportFilesId != null) && (supportFilesId != "")) {
        document.getElementById(supportFilesId).innerHTML = "Support Material " + strFiles;
    }

    if ((targetId != null) && (targetId != "")) {
        document.getElementById(targetId).innerHTML = o;
    }
}

function GetQueryValue(param) {
    try {
        var u = document.URL;

        if (u.indexOf('?') < 0) { return ''; }
        u = u.substr(u.indexOf('?') + 1);
        u = u.replace('?', '&');
        var pairs = u.split('&');

        if ((pairs == null) || (pairs.length < 1)) { return ''; }

        for (var i = 0; i < pairs.length; i++) {
            var parts = pairs[i].split('=');
            if (parts[0].toLowerCase() == param.toLowerCase())
            { return parts[1]; }
        }
    }
    catch (ex)
	{ }
    return '';
}

function GenerateEditLink() {
    var listName = EditPodcastGetListName();

    if (unescape(listNameForEditPodcast) == 'PKS Podcasts') {
        return "<a href='/" + listNameForEditPodcast + "/EditForm.aspx?ID=" + GetQueryValue("ItemId") + "&Source=" + escape(document.URL) + "'>Edit Podcast</a>";
    }
    else {
        return "<a href='/Lists/" + listNameForEditPodcast + "/EditForm.aspx?ID=" + GetQueryValue("ItemId") + "&Source=" + escape(document.URL) + "'>Edit Podcast</a>";
    }
}

// -----------------scripts for Edit link starts ------

var xmlDocForEditPodcast = new ActiveXObject("Microsoft.XMLDOM");
var listNameForEditPodcast;

function loadXML(xmlFile) {
    xmlDocForEditPodcast.async = "false";
    xmlDocForEditPodcast.onreadystatechange = verify;
    xmlDocForEditPodcast.load(xmlFile);
}

function verify() {
    if (xmlDocForEditPodcast.readyState != 4)
        return false;
}

function traverse(tree) {
    var listId = GetListIdForEditLink();
    listId = listId.toLowerCase();
    var listName;

    if (tree.hasChildNodes()) {

        for (var i = 0; i < tree.childNodes.length; i++) {
            if (tree.tagName.match('InternalName')) {
                var str1 = tree.text.toLowerCase();
                if (tree.text.toLowerCase() == listId) {
                    listName = tree.nextSibling.text;
                    listName = escape(listName);
                    listNameForEditPodcast = listName;
                    return listName;
                }
            }
            traverse(tree.childNodes(i));
        }
    }

}

//script for getting all lists of site using web services
//get the xml and traverse it to find the specific list name

function EditPodcastGetListName() {
    //var a = new ActiveXObject("Microsoft.XMLHTTP");   
    var a = new ActiveXObject("Msxml2.XMLHTTP");

    if (a == null) return null;


    var getListRequest = "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
    + "<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">"
    + "<soap:Body>"
    + "<GetListCollection xmlns=\"http://schemas.microsoft.com/sharepoint/soap/\">"
    + "</GetListCollection>"
    + "</soap:Body>"
    + "</soap:Envelope>";


    a.Open("Post", EncoderGetRootUrl() + "/_vti_bin/sitedata.asmx?op=GetListCollection", false);
    a.setRequestHeader("Content-Type:", "text/xml; charset=utf-8");
    a.setRequestHeader("SOAPAction:", "http://schemas.microsoft.com/sharepoint/soap/GetListCollection");
    a.Send(getListRequest);

    loadXML(a.responseXML);
    var doc = xmlDocForEditPodcast.documentElement;
    var listName = traverse(doc);
    return listName;
}

function GetListIdForEditLink() {
    var csId = GetQueryValue("csId");
    csId = unescape(csId);
    var listId = GetListId(csId);
    return listId;
}
// -----------------scripts for Edit link ends ------


function EndsWith(input, value) {
    var idx = input.indexOf(value);
    if (idx < 0) { return false; }

    if (idx == input.length - 1) { return true; }

    input = input.substring(idx + 1);
    return EndsWith(input, value);
}



//Cybage change

//The function RenderSupportMaterialForIE is used because 
//in IE, apostrophe characters are taken out in the output string and 
//the tag name is converted to uppercase. Firefox though, retains the same case and characters 
//as how it was written in the HTML file. You would have to do cross browser checks in your Javascript
//We are checking it on Podcastdetail page

function RenderSupportMaterialForIE(sourceId, targetId, supportFilesId, csId, itemId) {
    var xml = document.getElementById(sourceId).innerHTML;

    xml = UnHTMLEscape(xml);
    xml = KillLead(xml);
    xml = LoadXml(xml);


    var o = '<div style="PADDING-LEFT: 12px! important" align="left"><div style="FONT-WEIGHT: bold! important; WIDTH: 85%" align="left">';
    var files = xml.getElementsByTagName("EXTERNALFILEINFO");
    var count = 0;


    for (var i = 0; i < files.length; i++) {
        var fileName = files[i].getElementsByTagName("FILENAME")[0].childNodes[0].nodeValue;
        var isPrimary = files[i].attributes.getNamedItem("IsPrimary").nodeValue.toUpperCase();
        var clientLink = files[i].getElementsByTagName("CLIENTLINK")[0].childNodes[0].nodeValue;
        var dispName = files[i].getElementsByTagName("ORIGINALNAME");

        try {
            if ((dispName == null) || (dispName.length < 1)) {
                dispName = fileName;
            }
            else {
                dispName = dispName[0].childNodes[0].nodeValue
            }
        }
        catch (ex) {
            dispName = fileName;
        }


        if (isPrimary != "TRUE") {
            var link = '';
            if (useDownloadTracking) {
                link = fileUrl + "?csid=" + csId + "&id=" + itemId + "&file=" + fileName;
            }
            else {
                link = clientLink;
            }

            //if (count > 0){o += ", ";}
            o += "<a href='" + link + "'>";
            o += dispName;
            o += "</a><br />";
            count++;
        }
        else {
            if (useDownloadTracking) {
                var downloadLink = document.getElementById('aDownloadLink');
                downloadLink.href = fileUrl + "?csid=" + csId + "&id=" + itemId;
            }
        }
    }
    o += "</div></div>";

    var strFiles = "(" + count + " Files)";
    if (count == 0) { strFiles = "(No Files)"; }
    if (count == 1) { strFiles = "(1 File)"; }

    if ((supportFilesId != null) && (supportFilesId != "")) {
        document.getElementById(supportFilesId).innerHTML = "Support Material " + strFiles;
    }

    if ((targetId != null) && (targetId != "")) {
        document.getElementById(targetId).innerHTML = o;
    }
}

function RenderSupportMaterialForOtherBrowsers(sourceId, targetId, supportFilesId, csId, itemId) {
    var xml = document.getElementById(sourceId).innerHTML;
    xml = UnHTMLEscape(xml);
    xml = KillLead(xml);
    xml = LoadXml(xml);

    var o = '<div style="PADDING-LEFT: 12px! important" align="left"><div style="FONT-WEIGHT: bold! important; WIDTH: 85%" align="left">';
    var files = xml.getElementsByTagName("ExternalFileInfo");
    var count = 0;

    for (var i = 0; i < files.length; i++) {
        var fileName = files[i].getElementsByTagName("FileName")[0].childNodes[0].nodeValue;
        var isPrimary = files[i].attributes.getNamedItem("IsPrimary").nodeValue.toUpperCase();
        var clientLink = files[i].getElementsByTagName("ClientLink")[0].childNodes[0].nodeValue;
        var dispName = files[i].getElementsByTagName("OriginalFileName");

        try {
            if ((dispName == null) || (dispName.length < 1)) {
                dispName = fileName;
            }
            else {
                dispName = dispName[0].childNodes[0].nodeValue
            }
        }
        catch (ex) {
            dispName = fileName;
        }


        if (isPrimary != "TRUE") {
            var link = '';
            if (useDownloadTracking) {
                link = fileUrl + "?csid=" + csId + "&id=" + itemId + "&file=" + fileName;
            }
            else {
                link = clientLink;
            }

            //if (count > 0){o += ", ";}
            o += "<a href='" + link + "'>";
            o += dispName;
            o += "</a><br />";
            count++;
        }
        else {
            if (useDownloadTracking) {
                var downloadLink = document.getElementById('aDownloadLink');
                downloadLink.href = fileUrl + "?csid=" + csId + "&id=" + itemId;
            }
        }
    }
    o += "</div></div>";

    var strFiles = "(" + count + " Files)";
    if (count == 0) { strFiles = "(No Files)"; }
    if (count == 1) { strFiles = "(1 File)"; }

    if ((supportFilesId != null) && (supportFilesId != "")) {
        document.getElementById(supportFilesId).innerHTML = "Support Material " + strFiles;
    }

    if ((targetId != null) && (targetId != "")) {
        document.getElementById(targetId).innerHTML = o;
    }
}

function RenderSupportMaterialModified(sourceId, targetId, supportFilesId, csId, itemId) {
    var xml = document.getElementById(sourceId).innerHTML;
    xml = UnHTMLEscape(xml);
    xml = KillLead(xml);
    xml = LoadXml(xml);

    var o = '<div style="PADDING-LEFT: 12px! important" align="left"><div style="FONT-WEIGHT: bold! important; WIDTH: 85%" align="left">';
    var files = xml.getElementsByTagName("ExternalFileInfo");
    var count = 0;

    for (var i = 0; i < files.length; i++) {
        var fileName = files[i].getElementsByTagName("FileName")[0].childNodes[0].nodeValue;
        var isPrimary = files[i].attributes.getNamedItem("IsPrimary").nodeValue.toUpperCase();
        var clientLink = files[i].getElementsByTagName("ClientLink")[0].childNodes[0].nodeValue;
        var dispName = files[i].getElementsByTagName("OriginalFileName");

        try {
            if ((dispName == null) || (dispName.length < 1)) {
                dispName = fileName;
            }
            else {
                dispName = dispName[0].childNodes[0].nodeValue
            }
        }
        catch (ex) {
            dispName = fileName;
        }


        if (isPrimary != "TRUE") {
            var link = '';
            if (useDownloadTracking) {
                link = fileUrl + "?csid=" + csId + "&id=" + itemId + "&file=" + fileName;
            }
            else {
                link = clientLink;
            }

            //if (count > 0){o += ", ";}
            o += "<a href='" + link + "'>";
            o += dispName;
            o += "</a><br />";
            count++;
        }
        else {
            if (useDownloadTracking) {
                var downloadLink = document.getElementById('aDownloadLink');
                downloadLink.href = fileUrl + "?csid=" + csId + "&id=" + itemId;
            }
        }
    }
    o += "</div></div>";

    var strFiles = "(" + count + " Files)";
    if (count == 0) { strFiles = "(No Files)"; }
    if (count == 1) { strFiles = "(1 File)"; }

    if ((supportFilesId != null) && (supportFilesId != "")) {
        document.getElementById(supportFilesId).innerHTML = "Support Material " + strFiles;
    }

    if ((targetId != null) && (targetId != "")) {
        document.getElementById(targetId).innerHTML = o;
    }
}

//Media Encoder java script functions

function EncoderGetRootUrl() {
    var urlParts = document.location.href.split('/');
    var serverurl = urlParts[0] + '//' + urlParts[2];
    return serverurl;
}

function EncoderGetFilePath() {
    var filepath;
    var html;
    var divs = document.getElementsByTagName("div");
    for (var i = 0; i < divs.length; i++) {
        if (divs[i].id == 'divPodcastFilesXml') {
            var serverpath = 'ServerPath&gt;';
            var slashChar = "\\";
            html = divs[i].innerHTML;
            var fileurl = html.substring(html.indexOf('ServerPath&gt;') + serverpath.length, html.indexOf('\&lt;/ServerPath&gt'));
            var filename = html.substring(html.indexOf('FileName&gt;') + 12, html.indexOf('&lt;/FileName'));
            var filepathParts = fileurl.split('\\');
            filepath = slashChar + filepathParts[2] + slashChar + filepathParts[3] + slashChar + filepathParts[4] + slashChar + filename;

            return filepath;
        }
    }
}

// This function was written becuase of tags were converted into capital case.
function EncoderGetFilePath_Changed() {
    var filepath;
    var html;
    var divs = document.getElementsByTagName("div");
    for (var i = 0; i < divs.length; i++) {
        if (divs[i].id == 'divPodcastFilesXml') {
            var serverpath = '<SERVERPATH>';
            var slashChar = "\\";
            html = divs[i].innerHTML;
            var fileurl = html.substring(html.indexOf('SERVERPATH>') + serverpath.length, html.indexOf('\</SERVERPATH>'));
            var filename = html.substring(html.indexOf('<FILENAME>') + 10, html.indexOf('</FILENAME>'));
            var filepathParts = fileurl.split('\\');
            filepath = slashChar + filepathParts[2] + slashChar + filepathParts[3] + slashChar + filepathParts[4] + slashChar + filename;

            return filepath;
        }
    }
}


function EncoderAddToQueue() {
    var a = new ActiveXObject("Microsoft.XMLHTTP");

    var listName;
    listName = "Media Encoder Queue"; // The list name where entry of fileurl will be made

    var filePath = EncoderGetFilePath();

    var filePathParts = filePath.split('\\');
    var itemId = filePathParts[3];

    var isItemPresentInListEncoderQueue = EncoderIsItemExists(itemId, listName, filePath); // calling function to check duplicate entry for itemid

    if (!isItemPresentInListEncoderQueue) {

        var sBatch;
        sBatch = "<Method ID=\"1\" Cmd=\"New\">"
	        + "<Field Name=\"Title\">" + itemId + "</Field>"
	        + "<Field Name=\"FileUrl\">" + filePath + "</Field>"
	        + "<Field Name=\"Status\">" + "Submitted" + "</Field>"
	        + "</Method>";


        var updateList;

        updateList = "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
	           + "<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">"
	           + "<soap:Body>"
	           + "<UpdateListItems xmlns=\"http://schemas.microsoft.com/sharepoint/soap/\">"
	           + "<listName>" + listName + "</listName>"
	           + "<updates>"
	           + "<Batch>"
	           + sBatch
	           + "</Batch>"
	           + "</updates>"
	           + "</UpdateListItems>"
	           + "</soap:Body>"
	           + "</soap:Envelope>";

        a.Open("POST", EncoderGetRootUrl() + "/_vti_bin/Lists.asmx?op=UpdateListItems", false);
        a.setRequestHeader("Content-Type:", "text/xml; charset=utf-8");
        a.setRequestHeader("SOAPAction:", "http://schemas.microsoft.com/sharepoint/soap/UpdateListItems");

        a.Send(updateList);

        var message = 'Thank you. Your request has been logged. The video processing will take a couple of hours, please check back later.';

        if (a.statusText == 'OK') {
            alert(message);
            EncoderChangeImg();
        }
        else {
            alert(a.statusText);
        }
    }
    else {
        var itemAlreadyInQueue = " Thank you. A request has already been logged. The video is in processing stage, please check back later."
        alert(itemAlreadyInQueue);
    }
}


function EncoderIsItemExists(itemId, listName, filePath) {
    var listGuid = EncoderGetListGuid(listName);
    var fields = "<field Name='ID'></field><field Name='Title'></field><field Name='Status'></field>";
    var where = "<Eq>FieldRef Name='Title'/><Value Type='Number'>" + itemId + "</Value></Eq>";
    var orderBy = "<OrderField Name='Title' Type='xsd:string' Direction='ASC'/>";
    var rowLimit = 1;
    var extractRows = false;

    var a = new ActiveXObject("Microsoft.XMLHTTP");

    if (a == null) return null;

    a.Open("POST", EncoderGetRootUrl() + "/_vti_bin/DspSts.asmx", false);
    a.setRequestHeader("Content-Type:", "text/xml; charset=utf-8");
    a.setRequestHeader("SOAPAction:", "http://schemas.microsoft.com/sharepoint/dsp/queryRequest");

    var getListItemsRequest = '<?xml version=\"1.0\" encoding=\"utf-8\"?>'
    + "<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" "
    + "xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" "
    + "xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope\/\">"
    + " <soap:Header xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope\/\">"
    + " <dsp:versions xmlns:dsp=\"http://schemas.microsoft.com/sharepoint/dsp\">"
    + " <dsp:version>1.0</dsp:version>"
    + " </dsp:versions>"
    + " <dsp:request xmlns:dsp=\"http://schemas.microsoft.com/sharepoint/dsp\""
    + " service=\"DspSts\" document=\"content\" method=\"query\">"
    + " </dsp:request>"
    + " </soap:Header>"
    + "<soap:Body>"
    + "<queryRequest "
    + " xmlns=\"http://schemas.microsoft.com/sharepoint/dsp\">"
    + " <dsQuery select=\"/list[@id='" + listGuid + "']\""
    + " resultContent=\"dataOnly\""
    + " columnMapping=\"attribute\" resultRoot=\"Rows\" resultRow=\"Row\">"
    + " <query RowLimit=\"" + rowLimit + "\">"
    + " <fields>" + fields + "</fields>"
    + " <where>" + where + "</where>"
    + " <orderBy>" + orderBy + "</orderBy>"
    + " </query>"
    + " </dsQuery>"
    + " </queryRequest>"
    + "</soap:Body>"
    + "</soap:Envelope>";

    a.Send(getListItemsRequest);

    if (a.responseText.match(itemId))
        return true;
    else
        return false;
}


function EncoderGetListGuid(fullName) {
    var listXml = EncoderGetList(fullName);
    if (listXml != null)
        return listXml.selectSingleNode("//List").getAttribute("ID");
    else
        return null;
}

function EncoderGetList(listName) {
    var a = new ActiveXObject("Microsoft.XMLHTTP");

    if (a == null) return null;


    var getListRequest = "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
    + "<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">"
    + "<soap:Body>"
    + "<GetList xmlns=\"http://schemas.microsoft.com/sharepoint/soap/\">"
    + "<listName>" + listName + "</listName>"
    + "</GetList>"
    + "</soap:Body>"
    + "</soap:Envelope>";

    a.Open("Post", EncoderGetRootUrl() + "/_vti_bin/Lists.asmx?op=GetList", false);
    a.setRequestHeader("Content-Type:", "text/xml; charset=utf-8");
    a.setRequestHeader("SOAPAction:", "http://schemas.microsoft.com/sharepoint/soap/GetList");
    a.Send(getListRequest);


    if (a.status != 200)
        return null;
    else
        return a.responseXML;

}

function EncoderChangeImg() {
    var imgs, i;
    imgs = document.getElementsByTagName('img');
    for (i in imgs) {
        if (/encode.gif/.test(imgs[i].src)) {
            imgs[i].src = "../Style Library/PodcastingKit/Images/Encoding_InProgress.gif"
        }
    }
}


function EncoderCheckItem() {
    var listName;
    listName = "Media Encoder Queue"; // The list name where entry of fileurl will be made

    var filePath = EncoderGetFilePath();

    var filePathParts = filePath.split('\\');
    var itemId = filePathParts[3];

    var isItemPresentInListEncoderQueue = EncoderIsItemExists(itemId, listName, filePath); // calling function to check duplicate entry for itemid

    if (isItemPresentInListEncoderQueue) {
        EncoderChangeImg();
    }
}

function SetSelectedTab() {
    // get the page name
    var pageName = window.location.pathname;
    pageName = pageName.substring(pageName.lastIndexOf('/') + 1);
    pageName = pageName.toLowerCase();
    // get all the top nav links
    var links = document.getElementsByTagName('a');
    var navItems = new Array();
    var numLink = 0;
    for (var i = 0; i < links.length; i++) {
        if (links[i].className.indexOf('topNavItem') >= 0) {
            navItems[numLink] = links[i];
            numLink++;
        }
    }
    // set every link to unselected
    for (var i = 0; i < navItems.length; i++) {
        var cls = navItems[i].className;
        if (cls.indexOf('topNavSelected') < 0) continue;
        // create new class name for item
        var newClass = cls.substring(0, cls.indexOf('topNavSelected'));
        newClass = newClass + cls.substring(cls.indexOf('topNavSelected') + 14);
        navItems[i].className = newClass;
        // create new class name for parent
		var parent = navItems[i].parentNode.parentNode.parentNode.parentNode; 
        cls = parent.className;
        newClass = cls.substring(0, cls.indexOf('topNavSelected'));
		newClass = newClass + cls.substring(cls.indexOf('topNavSelected') + 14);
		parent.className = newClass;        
    }
    // set new selected link
    for (var i = 0; i < navItems.length; i++) {
        var linkPage = navItems[i].href;
        linkPage = linkPage.substring(linkPage.lastIndexOf('/')+1);
        linkPage = linkPage.toLowerCase();

        if (pageName == 'pkshomepage.aspx' || pageName == 'podcastdetail.aspx' || pageName == "podcastsearchresults.aspx") {
            if (linkPage == 'pkshomepage.aspx') {
            	navItems[i].className += ' topNavSelected';
            	navItems[i].parentNode.parentNode.parentNode.parentNode.className += ' topNavSelected';
            }
        }
        if (pageName == 'podcasters.aspx' || pageName == 'podcasterdetail.aspx') {
            if (linkPage == 'podcasters.aspx') {
            	navItems[i].className += ' topNavSelected';
            	navItems[i].parentNode.parentNode.parentNode.parentNode.className += ' topNavSelected';
            }
        }
    }
}
