// 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;
//

// New variables for navigation query string prefix
var navPrefix = "n";
var navFilterField = navPrefix + "ff";
var navFilterValue = navPrefix + "fv";
var navFilterOperation = navPrefix + "fo";
var navFilterType = navPrefix + "ft";
var navSortField = navPrefix + "sf";
var navSortOperation = navPrefix + "so";
var navPaging = navPrefix + "pg";
var searchFilter = "k";
//


function getPksQueryStringParams() {
    var cbq = new Array();
    otherQueryParams = new Array();
    var qstring = window.location.href.split(/\?/)[1];
    if (qstring == null) return cbq;

    //remove #Podcast from query string (if present)
    if (qstring.match("#Podcast")) {
        qstring = qstring.replace("#Podcasts", "");
    }

    qstring = qstring.split(/\&/);
    for (var i = 0; i < qstring.length; i++) {
        var param;
        if (qstring[i].indexOf("=") < 2)
        { param = "k"; }
        else
        { param = qstring[i].substring(0, 3); }
        var index = (param == navSortField || param == navSortOperation || param == searchFilter) ? 0 : qstring[i].substring(3, 4);
        var value = qstring[i].split(/=/)[1];

        if (cbq[index] == null) cbq[index] = new cbqFilter();

        switch (param.toLowerCase()) {
            // Sort Params    
            case navFilterField:
                cbq[index].Type = "filter";
                cbq[index].Column = value;
                break;
            case navFilterValue:
                cbq[index].Value = value;
                break;
            case searchFilter:
                cbq[index].Type = "filter";
                cbq[index].Value = value;
                break;
            case navFilterOperation:
                cbq[index].Operation = value;
                break;
            case navFilterType:
                cbq[index].ColumnType = value;
                break;
            // Sort Params    
            case navSortField:
                cbq[index].Type = "sort";
                cbq[index].Column = value;
                break;
            case navSortOperation:
                cbq[index].Value = value;
                break;
            case navPaging:
                cbqPage = value;
                break;
            default:
                otherQueryParams[otherQueryParams.length] = qstring[i].split(/=/)[0] + "=" + value;
        }
    }
    return cbq;
}


function addCategoryFilter(filterName, filterValue) {
    // get the current url
    var href = getBaseLocation();
    var params = new Array(); //getPksQueryStringParams(); //apply only one filter at a time
    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;
        }
    }

    buildNewPksQueryString(params);
}


function buildNewPksQueryString(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 += navFilterField + filterIndex + "=" + params[i].Column;
            pstring += "&" + navFilterValue + filterIndex + "=" + escape(params[i].Value);
            pstring += "&" + navFilterOperation + filterIndex + "=" + params[i].Operation;
            pstring += "&" + navFilterType + filterIndex + "=" + params[i].ColumnType;
            filterIndex++;
        }
        else if (params[i].Type == "sort") {
            pstring += navSortField + "1=" + params[i].Column;
            pstring += "&" + navSortOperation + "1=" + escape(params[i].Value);
        }
    }
    if (pstring == "") pstring += "?" + navPaging + "=" + cbqPage;
    else if (pstring == "?") pstring += navPaging + "=" + cbqPage;
    else pstring += "&" + navPaging + "=" + cbqPage;
    for (var i = 0; i < otherQueryParams.length; i++) {
        pstring += "&" + otherQueryParams[i];
    }

    href = "/Pages/SnackFilter.aspx"; //Force filters to navigate to custom grid page
    window.location = href + pstring;
}

function EncodeUrl(string) {
    string = string.replace(/\r\n/g, "\n");
    var utftext = "";

    for (var n = 0; n < string.length; n++) {

        var c = string.charCodeAt(n);

        if (c < 128) {
            utftext += String.fromCharCode(c);
        }
        else if ((c > 127) && (c < 2048)) {
            utftext += String.fromCharCode((c >> 6) | 192);
            utftext += String.fromCharCode((c & 63) | 128);
        }
        else {
            utftext += String.fromCharCode((c >> 12) | 224);
            utftext += String.fromCharCode(((c >> 6) & 63) | 128);
            utftext += String.fromCharCode((c & 63) | 128);
        }

    }

    return escape(utftext);
}



function buildNewQueryStringGlobalPass() {
    var href = getBaseLocation();
    var params = globalPassParams;
    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 += navFilterField + filterIndex + "=" + params[i].Column;
            pstring += "&" + navFilterValue + filterIndex + "=" + params[i].Value;
            pstring += "&" + navFilterOperation + filterIndex + "=" + params[i].Operation;
            pstring += "&" + navFilterType + filterIndex + "=" + params[i].ColumnType;
            filterIndex++;
        }
        else if (params[i].Type == "sort") {
            pstring += navSortField + "1=" + params[i].Column;
            pstring += "&" + navSortOperation + "1=" + params[i].Value;
        }
    }
    if (pstring == "") pstring += "?" + navPaging + "=" + cbqPage;
    else if (pstring == "?") pstring += navPaging + "=" + cbqPage;
    else pstring += "&" + navPaging + "=" + cbqPage;
    for (var i = 0; i < otherQueryParams.length; i++) {
        pstring += "&" + otherQueryParams[i];
    }

    window.location = href + pstring;
}


//this finction has been modified to correct the URL on PKSMobileHome.aspx
//URL doesn't work due to Jump to Podcast anchor
function getBaseLocation() {
    var hlink = (window.location.href.split(/\?/)[0]);
    var array = hlink.match("#Podcasts");
    if (array != null) {
        if (array.length > 0) {
            return hlink.substring(0, hlink.lastIndexOf("#Podcasts"));
        }
    }
    else {
        return hlink;
    }
}

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 = getPksQueryStringParams();
    //alert(params);
    // 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 = unescape(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.replace(/%20/g, " ")));
            // 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 CreatePodcasterMailtoLinkToPage(id, name) {

    var userId = id;
    var currentUserId = _spUserId;
    var userName = name;
    if (id == currentUserId) {
        var mailtoSubject = 'View my profiles & podcasts on Academy Mobile';
        var mailtoBody = 'Here is the link to my Academy Mobile podcasts and profiles:';
        mailtoBody += '\n' + window.location;
    }
    else {
        var mailtoSubject = 'View ' + userName + '\'s profiles & podcasts on Academy Mobile';
        var mailtoBody = 'Here is the link to ' + userName + '\'s Academy Mobile podcasts and profiles:';
        mailtoBody += '\n' + window.location;
    }
    var sendToFriend = 'mailto:?subject=' + escape(mailtoSubject) + '&body=' + escape(mailtoBody);
    window.location = sendToFriend;
}


function CreateEditProfileLink(subject) {
    var mailtoSubject = subject;
    var sendToFriend = '/_layouts/useredit.aspx?ID=' + mailtoSubject + "&Source=" + window.location;
    window.location = sendToFriend;
}


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 = getPksQueryStringParams();

    for (var i = 1; i < params.length; i++) {
        if (params[i] == null) continue;
        if (params[i].Column == filterName) params[i] = null;
    }
    buildNewPksQueryString(params);
}


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 = getPksQueryStringParams();
    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 = "true";
            }
        }
    }
    if (!foundItem) {
        var item = new cbqFilter();
        item.Type = "sort";
        item.Column = sortType;
        if (sortType == "Rating") {
            item.Value = "false";
        } else item.Value = "true";
        var index = 0;
        params[index] = item;
    }
    buildNewPksQueryString(params);
}

function CheckPrevPageLink(senderId) {
    var sender = document.getElementById(senderId);
    var params = getPksQueryStringParams();
    if (cbqPage <= 1) {
        sender.style.display = "none";
    }
}

function FirstPage() {
    var params = getPksQueryStringParams();
    cbqPage = 1;
    buildNewPksQueryString(params);
}

function NextPage() {
    var params = getPksQueryStringParams();
    cbqPage++;
    buildNewPksQueryString(params);
}

function PrevPage() {
    var params = getPksQueryStringParams();
    cbqPage--;
    if (cbqPage <= 0) cbqPage = 1;
    buildNewPksQueryString(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 = getPksQueryStringParams();
    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.paddingLeft = "4px";
                img.style.paddingBottom = "2px";
                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.paddingLeft = "4px";
                img.style.paddingBottom = "2px";
                img.style.border = "none";
                link.appendChild(img);
            }
        }
    }

}

function CreatePodcastMailtoLinkToPage(subject, body) {
    var mailtoSubject = subject;
    var mailtoBody = 'Hello, check out this Learning Snack from Microsoft Learning\'s SnackBox site called: ' + mailtoSubject;
    mailtoBody += '\n' + window.location;
    mailtoBody += '\n\n' + RichTextToPlainText(body, true);
    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 BuildUrlLinkToPage(elementId) {
    var windowlocationLink = document.getElementById(elementId);
    var url1 = document.URL;
    var newUrl = url1.replace('&', '&amp;').replace('<', '&lt;').replace('>', '&gt;').replace('\'', '&apos;').replace('"', '&quot;');


    windowlocationLink.value = document.URL;
}

function BuildEmbedLinkToPage(elementId, imageUrl, author, title, mediaUrl) {
    var windowlocationLink = document.getElementById(elementId);
    if (imageUrl.indexOf('http://') < 0) {
        var newUrl = document.URL;
        var pages = '/Pages/';
        var count = newUrl.indexOf(pages, 0);
        if (count > 0) {
            newUrl = newUrl.substring(0, count);
        }
        imageUrl = newUrl.concat(imageUrl);
    }
    var imageUrlClean = imageUrl.replace('&', '&amp;').replace('<', '&lt;').replace('>', '&gt;').replace('\'', '&apos;').replace('"', '&quot;');
    var mediaUrlClean = mediaUrl.replace('&', '&amp;').replace('<', '&lt;').replace('>', '&gt;').replace('\'', '&apos;').replace('"', '&quot;');
    var returnValue = '<div style="background-color:black; color:white; border-style:solid; border-' + 'color:#98bf21; width:145px; font-family: Tahoma; font-size:8pt; padding-right:10px;' +
'padding-left:10px;padding-top:10px;padding-bottom:10px; border-width:4px;">' +
'<a href="{0}" target="_blank"><img id="descImg9" ' + 'src="{1}" width="125px" height="100px" alt="{4}"></a><br/>{2}<br/>by<br/> {3}</div>';
    returnValue = returnValue.replace('{0}', mediaUrlClean).replace('{1}', imageUrlClean).replace('{2}', title).replace('{3}', author).replace('{4}', title);

    windowlocationLink.value = returnValue;
}

function BuildEmbedLinkToPageNew(elementId, imageUrl, author, title, mediaUrl) {
    var windowlocationLink = document.getElementById(elementId);
    var newUrl = document.URL;
    var pages = '/Pages/';
    var count = newUrl.indexOf(pages, 0);
    if (count > 0) {
        newUrl = newUrl.substring(0, count);
    }
    if (imageUrl.indexOf('http://') < 0) {
   
        imageUrl = newUrl.concat(imageUrl);
    }
    var mediapage=mediaUrl;
    if (mediaUrl.indexOf(".wmv", 0) > 0) {
        mediapage = "{0}/_layouts/MediaPlayer.aspx?source={1}".replace("{0}", newUrl).replace("{1}", mediaUrl);
    }
    var onClickItem = "SnackPlayer=window.open('{0}', 'SnackPlayer', 'width=880,height=660'); return false;".replace('{0}',mediapage);
    var imageUrlClean = imageUrl.replace('&', '&amp;').replace('<', '&lt;').replace('>', '&gt;').replace('\'', '&apos;').replace('"', '&quot;');
    var mediaUrlClean = mediaUrl.replace('&', '&amp;').replace('<', '&lt;').replace('>', '&gt;').replace('\'', '&apos;').replace('"', '&quot;');
    var returnValue = '<div style="background-color:black; color:white; border-style:solid; border-' + 'color:#98bf21; width:145px; font-family: Tahoma; font-size:8pt; padding-right:10px;' +
'padding-left:10px;padding-top:10px;padding-bottom:10px; border-width:4px;">' +
'<a href="#" target="_blank" onClick="{0}"><img id="descImg9" ' + 'src="{1}" width="125px" height="100px" alt="{4}"></a><br/>{2}<br/>by<br/> {3}</div>';
    returnValue = returnValue.replace('{0}', onClickItem).replace('{1}', imageUrlClean).replace('{2}', title).replace('{3}', author).replace('{4}', title);

    windowlocationLink.value = returnValue;
}


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 += getPksFileTypeImage(fileName);
            o += " <a href='" + link + "'>";
            o += dispName;
            o += "</a><p />";
            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 getPksFileTypeImage(fileName) {
    var fileExtIdx = fileName.lastIndexOf('.');
    var fileTypeImage = "icgen.gif";
    var fileTypeExt = "Item";

    if (fileExtIdx > -1) {
        fileTypeExt = fileName.substring(fileExtIdx + 1).toLowerCase();
        switch (fileTypeExt) {
            case "accdb":
                fileTypeImage = "icaccdb.gif";
                break;
            case "accdt":
                fileTypeImage = "icaccdb.gif";
                break;
            case "accdc":
                fileTypeImage = "icaccdb.gif";
                break;
            case "accde":
                fileTypeImage = "icaccde.gif";
                break;
            case "accdr":
                fileTypeImage = "icaccde.gif";
                break;
            case "asax":
                fileTypeImage = "icasax.gif";
                break;
            case "ascx":
                fileTypeImage = "icascx.gif";
                break;
            case "asmx":
                fileTypeImage = "icasmx.gif";
                break;
            case "asp":
                fileTypeImage = "ichtm.gif";
                break;
            case "aspx":
                fileTypeImage = "ichtm.gif";
                break;
            case "bmp":
                fileTypeImage = "icbmp.gif";
                break;
            case "cat":
                fileTypeImage = "iccat.gif";
                break;
            case "chm":
                fileTypeImage = "icchm.gif";
                break;
            case "config":
                fileTypeImage = "icconfig.gif";
                break;
            case "css":
                fileTypeImage = "iccss.gif";
                break;
            case "db":
                fileTypeImage = "icdb.gif";
                break;
            case "dib":
                fileTypeImage = "icdib.gif";
                break;
            case "disc":
                fileTypeImage = "icdisc.gif";
                break;
            case "doc":
                fileTypeImage = "icdoc.gif";
                break;
            case "docm":
                fileTypeImage = "icdocx.gif";
                break;
            case "docx":
                fileTypeImage = "icdocx.gif";
                break;
            case "dot":
                fileTypeImage = "icdot.gif";
                break;
            case "dotm":
                fileTypeImage = "icdotx.gif";
                break;
            case "dotx":
                fileTypeImage = "icdotx.gif";
                break;
            case "dvd":
                fileTypeImage = "icdvd.gif";
                break;
            case "dwp":
                fileTypeImage = "icdwp.gif";
                break;
            case "dwt":
                fileTypeImage = "icdwt.gif";
                break;
            case "eml":
                fileTypeImage = "iceml.gif";
                break;
            case "est":
                fileTypeImage = "icest.gif";
                break;
            case "fwp":
                fileTypeImage = "icfwp.gif";
                break;
            case "gif":
                fileTypeImage = "icgif.gif";
                break;
            case "hlp":
                fileTypeImage = "ichlp.gif";
                break;
            case "hta":
                fileTypeImage = "ichta.gif";
                break;
            case "htm":
                fileTypeImage = "ichtm.gif";
                break;
            case "html":
                fileTypeImage = "ichtm.gif";
                break;
            case "htt":
                fileTypeImage = "ichtt.gif";
                break;
            case "inf":
                fileTypeImage = "icinf.gif";
                break;
            case "ini":
                fileTypeImage = "icini.gif";
                break;
            case "jfif":
                fileTypeImage = "icjfif.gif";
                break;
            case "jpe":
                fileTypeImage = "icjpe.gif";
                break;
            case "jpeg":
                fileTypeImage = "icjpeg.gif";
                break;
            case "jpg":
                fileTypeImage = "icjpg.gif";
                break;
            case "js":
                fileTypeImage = "icjs.gif";
                break;
            case "jse":
                fileTypeImage = "icjse.gif";
                break;
            case "log":
                fileTypeImage = "iclog.gif";
                break;
            case "master":
                fileTypeImage = "icmaster.gif";
                break;
            case "mht":
                fileTypeImage = "icmht.gif";
                break;
            case "mhtml":
                fileTypeImage = "icmht.gif";
                break;
            case "mpd":
                fileTypeImage = "icmpd.gif";
                break;
            case "mpp":
                fileTypeImage = "icmpp.gif";
                break;
            case "mps":
                fileTypeImage = "icmps.gif";
                break;
            case "mpt":
                fileTypeImage = "icmpt.gif";
                break;
            case "mpw":
                fileTypeImage = "icmpw.gif";
                break;
            case "mpx":
                fileTypeImage = "icmpx.gif";
                break;
            case "msg":
                fileTypeImage = "icmsg.gif";
                break;
            case "msi":
                fileTypeImage = "icmsi.gif";
                break;
            case "msp":
                fileTypeImage = "icmsp.gif";
                break;
            case "ocx":
                fileTypeImage = "icocx.gif";
                break;
            case "odc":
                fileTypeImage = "icodc.gif";
                break;
            case "one":
                fileTypeImage = "icone.gif";
                break;
            case "onepkg":
                fileTypeImage = "iconp.gif";
                break;
            case "onetoc2":
                fileTypeImage = "icont.gif";
                break;
            case "png":
                fileTypeImage = "icpng.gif";
                break;
            case "pot":
                fileTypeImage = "icpot.gif";
                break;
            case "potm":
                fileTypeImage = "icpotx.gif";
                break;
            case "potx":
                fileTypeImage = "icpotx.gif";
                break;
            case "ppt":
                fileTypeImage = "icppt.gif";
                break;
            case "pptm":
                fileTypeImage = "icpptx.gif";
                break;
            case "pptx":
                fileTypeImage = "icpptx.gif";
                break;
            case "pps":
                fileTypeImage = "icpps.gif";
                break;
            case "psp":
                fileTypeImage = "icpsp.gif";
                break;
            case "psd":
                fileTypeImage = "icbmp.gif";
                break;
            case "ptm":
                fileTypeImage = "icptm.gif";
                break;
            case "ptt":
                fileTypeImage = "icptt.gif";
                break;
            case "pub":
                fileTypeImage = "icpub.gif";
                break;
            case "rtf":
                fileTypeImage = "icrtf.gif";
                break;
            case "stp":
                fileTypeImage = "icstp.gif";
                break;
            case "stt":
                fileTypeImage = "icstt.gif";
                break;
            case "tif":
                fileTypeImage = "ictif.gif";
                break;
            case "tiff":
                fileTypeImage = "ictiff.gif";
                break;
            case "txt":
                fileTypeImage = "ictxt.gif";
                break;
            case "vbe":
                fileTypeImage = "icvbe.gif";
                break;
            case "vbs":
                fileTypeImage = "icvbs.gif";
                break;
            case "vdx":
                fileTypeImage = "icvdx.gif";
                break;
            case "vsd":
                fileTypeImage = "icvsd.gif";
                break;
            case "vsl":
                fileTypeImage = "icvsl.gif";
                break;
            case "vss":
                fileTypeImage = "icvss.gif";
                break;
            case "vst":
                fileTypeImage = "icvst.gif";
                break;
            case "vsu":
                fileTypeImage = "icvsu.gif";
                break;
            case "vsw":
                fileTypeImage = "icvsw.gif";
                break;
            case "vsx":
                fileTypeImage = "icvsx.gif";
                break;
            case "vtx":
                fileTypeImage = "icvtx.gif";
                break;
            case "webpart":
                fileTypeImage = "icdwp.gif";
                break;
            case "wm":
                fileTypeImage = "icwm.gif";
                break;
            case "wma":
                fileTypeImage = "icwma.gif";
                break;
            case "wmd":
                fileTypeImage = "icwmd.gif";
                break;
            case "wmp":
                fileTypeImage = "icwmp.gif";
                break;
            case "wms":
                fileTypeImage = "icwms.gif";
                break;
            case "wmv":
                fileTypeImage = "icwmv.gif";
                break;
            case "wmx":
                fileTypeImage = "icwmx.gif";
                break;
            case "wmz":
                fileTypeImage = "icwmz.gif";
                break;
            case "wsf":
                fileTypeImage = "icwsf.gif";
                break;
            case "xls":
                fileTypeImage = "icxls.gif";
                break;
            case "xlsb":
                fileTypeImage = "icxlsx.gif";
                break;
            case "xlsm":
                fileTypeImage = "icxlsx.gif";
                break;
            case "xlsx":
                fileTypeImage = "icxlsx.gif";
                break;
            case "xlt":
                fileTypeImage = "icxlt.gif";
                break;
            case "xltb":
                fileTypeImage = "icxltx.gif";
                break;
            case "xltm":
                fileTypeImage = "icxltx.gif";
                break;
            case "xltx":
                fileTypeImage = "icxltx.gif";
                break;
            case "xml":
                fileTypeImage = "icxml.gif";
                break;
            case "xps":
                fileTypeImage = "icxps.gif";
                break;
            case "xsd":
                fileTypeImage = "icxsd.gif";
                break;
            case "xsl":
                fileTypeImage = "icxsl.gif";
                break;
            case "xsn":
                fileTypeImage = "icxsn.gif";
                break;
            case "xslt":
                fileTypeImage = "icxslt.gif";
                break;
            case "zip":
                fileTypeImage = "iczip.gif";
                break;
        }
    }

    return "<img src='/_layouts/images/" + fileTypeImage + "' alt='" + fileTypeExt + "' />";
}


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 '';
}

var subsite;

function GenerateEditLink() {
    var listName = EditPodcastGetListName();

    if (subsite.toLowerCase() == 'pages') {
        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>";
        }
    }
    else {
        if (unescape(listNameForEditPodcast) == 'PKS Podcasts') {
            return "<a href='/" + subsite + '/' + listNameForEditPodcast + "/EditForm.aspx?ID=" + GetQueryValue("ItemId") + "&Source=" + escape(document.URL) + "'>Edit Podcast</a>";
        }
        else {
            return "<a href='/" + subsite + "/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", EncoderGetRootUrlForEditPodcast() + "/_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 EncoderGetRootUrlForEditPodcast() {
    var urlParts = document.location.href.split('/');
    subsite = urlParts[3];
    var serverurl;
    if (subsite.toLowerCase() == 'pages') {
        serverurl = urlParts[0] + '//' + urlParts[2];
    }
    else {
        serverurl = urlParts[0] + '//' + urlParts[2] + '//' + urlParts[3];
    }

    return serverurl;
}

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 += getPksFileTypeImage(fileName);
            o += " <a href='" + link + "'>";
            o += dispName;
            o += "</a><p />";
            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 += getPksFileTypeImage(fileName);
            o += " <a href='" + link + "'>";
            o += dispName;
            o += "</a><p />";
            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 NFSfiles = xml.getElementsByTagName("FileXml");
    var layOutPath;
    var itemId;
    var downLoadUrl;
    var count = 0;

    for (var i = 0; i < NFSfiles.length; i++) {
        layOutPath = NFSfiles[i].getElementsByTagName("ItemRelativeFolderUrl")[0].childNodes[0].nodeValue;
        itemId = NFSfiles[i].getElementsByTagName("UploadLocationPrefix")[0].childNodes[0].nodeValue;
    }

    var files = xml.getElementsByTagName("File");

    for (var i = 0; i < files.length; i++) {

        var fileName = files[i].childNodes[0].nodeValue;
        var isPrimary = files[i].attributes.getNamedItem("IsPrimary").nodeValue.toUpperCase();
        var fileType = files[i].attributes.getNamedItem("FileType").nodeValue.toUpperCase();

        if (isPrimary != "TRUE") {

            count++;

            if (fileType != "REFERENCE") {
                downLoadUrl = layOutPath + fileName + '?=&mode=Play%E2%80%93Download';
            }
            else {
                if (fileName.match('http://') || fileName.match('https://')) {
                    downLoadUrl = fileName;
                }
                else {
                    downLoadUrl = "http://" + fileName;
                }
            }
            o += getPksFileTypeImage(fileName);
            o += " <a href='" + downLoadUrl + "'>";
            o += fileName;
            o += "</a><p />";

        }

    }
    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 = 'ItemRelativeFolderUrl&gt;';
            var slashChar = "\\";
            html = divs[i].innerHTML;

            //Here some code changes are done 1/29/2009

            var fileurl = html.substring(html.indexOf('ItemRelativeFolderUrl&gt;') + 25, html.indexOf('\&lt;/ItemRelativeFolderUrl&gt'));

            var tempname = html.substring(html.indexOf('IsPrimary="true"'), html.length);
            var name = tempname.substring(tempname.indexOf('IsPrimary="true"'), tempname.indexOf('&lt;/File&gt;'));
            var filename = name.substring(name.indexOf('"&gt;') + 5, name.length);

            var filepathParts = fileurl.split('/');

            filepath = slashChar + filepathParts[4] + slashChar + filepathParts[5] + slashChar + filepathParts[6] + 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 percent = "%25";

    var listName;
    listName = "Media Encoder Queue"; // The list name where entry of fileurl will be made
    var filePath = EncoderGetFilePath();
    var action = "Encode";
    var itemId = GetQueryValue('itemId');

    var csid = GetQueryValue('csid');
    if (csid.match(percent)) {
        csid = csid.substring(csid.lastIndexOf('%257B') + 5, csid.length - 5);
    }
    else {
        csid = csid.substring(csid.lastIndexOf('{') + 1, csid.length - 1);
    }

    var isItemPresentInListEncoderQueue = EncoderIsItemExists(itemId, listName, filePath, action, csid); // 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>"
	        + "<Field Name=\"Action\">" + "Encode" + "</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, action, pksListGuid) {
    var listGuid = EncoderGetListGuid(listName);
    var fields = "<Field Name='FileUrl'></Field>";
    var where = "<And><And><Eq><FieldRef Name='Title' /><Value Type='Text'>" + itemId + "</Value></Eq><Eq><FieldRef Name='Action' /><Value Type='Text'>" + action + "</Value></Eq></And><Or><Or><Eq><FieldRef Name='Status' /><Value Type='Text'>Submitted</Value></Eq><Eq><FieldRef Name='Status' /><Value Type='Text'>Complete</Value></Eq></Or><Eq><FieldRef Name='Status' /><Value Type='Text'>In Progress</Value></Eq></Or></And>";
    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);
    var matchItem = pksListGuid.toLowerCase() + "\\" + itemId + "\\";

    //This part of the code has been changed - Date 1/29/2009
    var q = a.responseText;
    var s = q.indexOf(matchItem);
    if (s != -1)
        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 itemId = GetQueryValue('itemId');

    var isItemPresentInListEncoderQueue = EncoderIsItemExists(itemId, listName, filePath); // calling function to check duplicate entry for itemid

    if (isItemPresentInListEncoderQueue) {
        EncoderChangeImg();
    }
}

function EncoderAddThumbnailToQueue() {
    var userName = "," + _spUserId + ",";
    var userExists = CheckUserInGroup(userName);
    var authors = ',' + GetQueryValue('userId') + ',' + GetQueryValue('caid');
    var itemId = GetQueryValue('itemId');

    var csid = GetQueryValue('csid');
    if (csid.match('%25')) {
        csid = csid.substring(csid.lastIndexOf('%257B') + 5, csid.length - 5);
    }
    else {
        csid = csid.substring(csid.lastIndexOf('{') + 1, csid.length - 1);
    }

    var userFullName = GetItemFromList('User Information List', _spUserId);

    var checkOwner = CheckOwner(userFullName, csid);

    if (authors.match(userName) || userExists || checkOwner) {

        var a = new ActiveXObject("Microsoft.XMLHTTP");

        var listName;
        listName = "Media Encoder Queue"; // The list name where entry of fileurl will be made
        var action = "Thumbnail";
        var filePath = EncoderGetFilePath();

        var isItemPresentInListEncoderQueue = EncoderIsItemExists(itemId, listName, filePath, action, csid); // 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>"
		        + "<Field Name=\"Action\">" + "Thumbnail" + "</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);
            }
            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);
        }
    }
    else {
        alert("Only Admins, Owners and Co-Owners can regenerate thumbnail");
    }
}


function SetDefaultThumbnail() {
    var listName;

    var fileUrl = EncoderGetFilePath();
    var fileName = fileUrl.substring(fileUrl.lastIndexOf('/'), fileUrl.length);

    /*Verify the logged user*/
    var userId = "," + _spUserId + ",";
    var userFullName = GetItemFromList('User Information List', _spUserId);
    var userExists = CheckUserInGroup(userId);

    var csid = GetQueryValue('csid');
    if (csid.match('%25')) {
        csid = csid.substring(csid.lastIndexOf('%257B') + 5, csid.length - 5);
    }
    else {
        csid = csid.substring(csid.lastIndexOf('{') + 1, csid.length - 1);
    }

    listName = GetListCollection(csid);

    var checkOwner = CheckOwner(userFullName, csid);

    if (checkOwner || userExists) {
        var fileExt = fileName.substring(fileName.lastIndexOf('.') + 1, fileName.length);
        var defaultThumbnailUrl;

        var retval = ExtensionExist(fileExt);
        if (retval) {
            defaultThumbnailUrl = EncoderGetRootUrl() + "/Style Library/PodcastingKit/Images/pks_thumbnail_" + fileExt + ".jpg";
        }
        else {
            defaultThumbnailUrl = EncoderGetRootUrl() + "/Style Library/PodcastingKit/Images/pks_thumbnail.jpg";
        }

        var a = new ActiveXObject("Microsoft.XMLHTTP");

        if (a == null) return null;

        var sBatch;
        sBatch = "<Method ID=\"1\" Cmd=\"Update\">"
		        + "<Field Name=\"ID\">" + GetQueryValue('itemId') + "</Field>"
		        + "<Field Name=\"PodcastThumbnail\">" + defaultThumbnailUrl + "</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", EncoderGetRootUrlForEditPodcast() + "/_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);
        alert("Thumbnail Updated. Please refresh the page.");
    }
    else {
        alert("Only Admins and Owners can set default thumbnail");
    }
}


function ExtensionExist(fileExt) {
    var listName = "PKS Configuration Settings";
    var listGuid = EncoderGetListGuid(listName);
    var fields = "<Field Name='Value'></Field>";
    var where = "<Eq><FieldRef Name='Title' /><Value Type='Text'>MediaEncoder.FileTypeThumbnail</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(fileExt))
        return true;
    else
        return false;
}


function CheckUserInGroup(userName) {
    var groupName = "PKS Administrators";

    var a = new ActiveXObject("Microsoft.XMLHTTP");
    if (a == null) return null;

    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>"
	           + "<GetUserCollectionFromGroup xmlns=\"http://schemas.microsoft.com/sharepoint/soap/directory/\">"
	           + "<groupName>" + groupName + "</groupName>"
	           + "</GetUserCollectionFromGroup>"
	           + "</soap:Body>"
	           + "</soap:Envelope>";

    a.Open("POST", EncoderGetRootUrl() + "/_vti_bin/usergroup.asmx?op=GetUserCollectionFromGroup", false);
    a.setRequestHeader("Content-Type:", "text/xml; charset=utf-8");
    a.setRequestHeader("SOAPAction:", "http://schemas.microsoft.com/sharepoint/soap/directory/GetUserCollectionFromGroup");

    a.Send(updateList);

    var user = userName.substring(1, userName.length - 1);
    if (a.responseText.match('ID="' + user + '"'))
        return true;
    else
        return false;
}

function GetListCollection(Guid) {
    var listname;
    var a = new ActiveXObject("Microsoft.XMLHTTP");
    if (a == null) return null;

    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>"
	           + "<GetListCollection xmlns=\"http://schemas.microsoft.com/sharepoint/soap/\" />"
	           + "</soap:Body>"
	           + "</soap:Envelope>";

    a.Open("POST", EncoderGetRootUrlForEditPodcast() + "/_vti_bin/Lists.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(updateList);
    var response = a.responseText;
    if (a.responseText.match(Guid)) {
        var Title = response.split(Guid);
        var getTitle = Title[1].substring(Title[1].lastIndexOf('Title'), Title[1].lastIndexOf('Description'));
        var splitTitle = getTitle.split('"');
        listName = splitTitle[1];
        return listName;
    }
}

function GetItemFromList(listName, itemId) {
    var a = new ActiveXObject("Microsoft.XMLHTTP");

    if (a == null) return null;

    var query = "<Query><Where><Eq><FieldRef Name='ID'/><Value Type='Number'>" + itemId + "</Value></Eq></Where></Query>";


    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>"
	+ "<GetListItems xmlns=\"http://schemas.microsoft.com/sharepoint/soap/\">"
	+ "<listName>" + listName + "</listName>"
	+ "<query>" + query + "</query>"
	+ "<rowLimit>" + 1 + "</rowLimit>"
	+ "</GetListItems>"
	+ "</soap:Body>"
	+ "</soap:Envelope>";

    a.Open("Post", EncoderGetRootUrl() + "/_vti_bin/Lists.asmx?op=GetListItems", false);
    a.setRequestHeader("Content-Type:", "text/xml; charset=utf-8");
    a.setRequestHeader("SOAPAction:", "http://schemas.microsoft.com/sharepoint/soap/GetListItems");
    a.Send(getListRequest);

    var xmlDoc = a.responseXML;
    var responseElement = xmlDoc.getElementsByTagName("z:row");

    var id = responseElement[0].getAttribute('ows_ID');
    var title = responseElement[0].getAttribute('ows_Title');

    if (id == null) {
        return null;
    }
    else {
        return title;
    }
}


function CheckOwner(accountName, listGuid) {
    var itemId = GetQueryValue('itemId');
    var fields = "<Field Name='Author'></Field>";
    var where = "<Eq><FieldRef Name='ID' /><Value Type='Counter'>" + 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", EncoderGetRootUrlForEditPodcast() + "/_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);

    var response = a.responseXML.getElementsByTagName('Row');
    var listUserName = response[0].getAttribute('Author');

    accountName = accountName.replace("\\", "");
    listUserName = listUserName.replace("\\", "");


    if (accountName.toLowerCase() == listUserName.toLowerCase())
        return true;
    else
        return false;
}
