var userState = new Cookie(document, "userState", 8760);
userState.load();
// Called at window onload, checks the default settings of the userState cookie
var watchListId = "listDropDown";
var HeadlineSummaryType = "";
var SelectedCount = "0";
String.prototype.trim = function() { return this.replace(/^\s+|\s+$/, ''); };
// event listeners

document.observe("HomePage:WatchListItemEvent", function(event) { if(event.memo!=null)processWatchListItem(event.memo.Params) });

function checkState() {
   //Resize New Portlet Iframe 
    var iframeName = window.top.window.iframeTreeid;
    if(window.frames[iframeName])
    {
        window.frames[iframeName].reSize();
    }
    
    var left = $("left_nav");
    var center = $("center");
    var right = $("right_nav");
    var alerts = $("alertsalt");

    var leftBtn = $("left_col_btn");
    var centerBtn = $("center_col_btn");
    var rightBtn = $("right_col_btn");

    try {
        if (MediaButton.Left) {
            left.show();
            alerts.style.display = "none";
        }
        else {
            left.hide();
            alerts.style.display = "none";
        }
        if (MediaButton.Right) {
            right.show();
            alerts.style.display = "none";
        }
        else {
           right.hide();
            alerts.style.display = "block";
        }

    }
    catch (e) { }
    

    /* this controls the font-size of the "center" column based on the cookie */
    try {
        if (MediaButton.Font) {
            $("center").style.fontSize = MediaButton.Font + "px";
            document.getElementById("WelcomeFrame").contentWindow.document.getElementById("dvWelcomeMsg").style.fontSize = MediaButton.Font + "px";
            resizeIframe('WelcomeFrame');
        }
    }
    catch (e) { }

    if (IsVisible('photos'))
        FixPhotos();
    if (IsVisible('graphics'))
        FixGraphics();
}
//Controls the panel layout buttons

function layout(tLayer) {
    var td = $("left_nav");
    var center = $("center");
    var tdright=$("right_nav");
    var alerts = $("alertsalt");
    var leftBtn = $("left_col_btn");
    var centerBtn = $("center_col_btn");
    var rightBtn = $("right_col_btn");
    var style;
    switch (tLayer) {
        case leftBtn:
            alerts.style.display = "none";
            leftBtn.removeClassName();
            
            leftBtn.removeClassName("left-on");
            leftBtn.removeClassName("left-off");
            if(td.visible())
            {
                MediaButton.SetParams("Left=false");
                td.hide();
                leftBtn.addClassName("left-on");
                
            }
            else
            {
                MediaButton.SetParams("Left=true");
                td.show();
                leftBtn.addClassName("left-off");
            }
            
            if(!tdright.visible())
            {
                alerts.style.display = "block";
            }
            break;
        case centerBtn:
             
             centerBtn.removeClassName("middle-off");
             centerBtn.removeClassName("middle-on");
             leftBtn.removeClassName("left-on");
             leftBtn.removeClassName("left-off");
             rightBtn.removeClassName("right-off");
             rightBtn.removeClassName("right-on");
            if (td.visible() && tdright.visible())
            {
                alerts.style.display = "block";
                MediaButton.SetParams("Right=false");
                MediaButton.SetParams("Left=false");
                centerBtn.addClassName("middle-on");
                leftBtn.addClassName("left-on");
                rightBtn.addClassName("right-on");  
                td.hide();
                tdright.hide();
            }
            else 
            {
                alerts.style.display = "none";
                MediaButton.SetParams("Right=true");
                MediaButton.SetParams("Left=true");
                centerBtn.addClassName("middle-off");
                leftBtn.addClassName("left-off");
                rightBtn.addClassName("right-off");  
                td.show();
                tdright.show();
               
            }
            
            break;
        case rightBtn:
            rightBtn.removeClassName("right-off");
            rightBtn.removeClassName("right-on");
            if (tdright.visible()) 
            {
                alerts.style.display = "block";
                MediaButton.SetParams("Right=false");
                tdright.hide();
                rightBtn.addClassName("right-on");  
            }
            else 
            {
                alerts.style.display = "none";
                MediaButton.SetParams("Right=true");
                tdright.show();
                rightBtn.addClassName("right-off");   
              
            }
            break;
    }
   
    var iframeName = window.top.window.iframeTreeid;
    if(window.frames[iframeName])
    {
        window.frames[iframeName].reSize();
    }
    //alert("holyGrail" + holyGrail.className);
}
function textControl(element) {
    var fontSize = MediaButton.Font;
    if (element.getAttribute("id") == "text-larger") {
        if (fontSize < 15) {
            fontSize += 1;
            //fontSize = 15;
            document.which("center").style.fontSize = fontSize + "px";
            document.getElementById("WelcomeFrame").contentWindow.document.getElementById("dvWelcomeMsg").style.fontSize = fontSize + "px";
            resizeIframe('WelcomeFrame');
            //document.which("left").style.fontSize = fontSize + "px";
            //document.which("right").style.fontSize = fontSize + "px";
        }
    }
    else if (element.getAttribute("id") == "text-medium") {
        if (fontSize < 13) {
            fontSize += 1;
            //fontSize = 13;
            document.which("center").style.fontSize = fontSize + "px";
            document.getElementById("WelcomeFrame").contentWindow.document.getElementById("dvWelcomeMsg").style.fontSize = fontSize + "px";
            resizeIframe('WelcomeFrame');
        }
    }
    else if (element.getAttribute("id") == "text-icon_plus") {
        if (fontSize == 15)
            return false
        else
            fontSize = fontSize + 1;
        document.which("center").style.fontSize = fontSize + "px";
        document.getElementById("WelcomeFrame").contentWindow.document.getElementById("dvWelcomeMsg").style.fontSize = fontSize + "px";
        resizeIframe('WelcomeFrame');
    }
    else if (element.getAttribute("id") == "text-icon_minus") {
        if (fontSize == 10)
            return false
        else
            fontSize = fontSize - 1;
        document.which("center").style.fontSize = fontSize + "px";
        document.getElementById("WelcomeFrame").contentWindow.document.getElementById("dvWelcomeMsg").style.fontSize = fontSize + "px";
        resizeIframe('WelcomeFrame');
    }
    else {
        if (fontSize > 10) {
            fontSize -= 1;
            //fontSize = 12;
            document.which("center").style.fontSize = fontSize + "px";
            document.getElementById("WelcomeFrame").contentWindow.document.getElementById("dvWelcomeMsg").style.fontSize = fontSize + "px";
            resizeIframe('WelcomeFrame');
            //document.which("left").style.fontSize = fontSize + "px";            
            //document.which("right").style.fontSize = fontSize + "px";			
        }
        else {
            return false;
        }
    }
    // userState.font = fontSize;
    // userState.store();
    MediaButton.Font = fontSize;
    MediaButton.SetParams("Font=" + fontSize);
    //location.reload();
}
// Controls the ability of the li containers to resize
function liHeight(what) {
    var height = 0;
    for (var i = 0; i < what.length; i++) {
        if (parseInt(what[i].offsetHeight) > height) height = parseInt(what[i].offsetHeight);
    }
    //height += 20;
    for (var i = 0; i < what.length; i++) {
        what[i].style.height = height + "px";
    }
}
function getRef(obj) {
    return (typeof obj == "string") ?
        document.which(obj) : obj;
}
function setClassName(obj, className) {
    getRef(obj).className = className;
}
function toggleClassName(obj, class1, class2) {
    obj = getRef(obj);
    // obj.isClass1 will be false the first time.
    if (!obj.isClass1) {
        obj.className = class1;
        obj.isClass1 = true;
    }
    else {
        obj.className = class2;
        obj.isClass1 = false;
    }
}
function WatchList_Add(contentId, format, itemID, recordID, mediaType, name, ItemStartDate, ItemExpireDate) {
    var watchListObj = null;
    var iframeObj = null;
    var watchListID = "-1";

    iframeObj = window.parent.frames["watchListIFrame"];

    if (iframeObj != null) {
        watchListObj = iframeObj.document.getElementsByName(watchListId)[0];
    }

    if (watchListObj != null && watchListObj.selectedIndex != -1) {
        watchListID = watchListObj.options[watchListObj.selectedIndex].value;
    }

    PublishWatchListItemAddEvent(watchListID, contentId, format, itemID, recordID, mediaType, name, ItemStartDate, ItemExpireDate);
    return true;
}
function PublishWatchListItemAddEvent(watchListID, contentId, format, itemID, recordID, mediaType, name, itemStartDate, itemExpireDate) {
    var params = { "WatchListID": watchListID, "ContentId": contentId, "Format": format, "ItemID": itemID, "RecordID": recordID, "MediaType": mediaType, "Name": name, "ItemStartDate": itemStartDate, "ItemExpireDate": itemExpireDate };
    document.fire("HomePage:WatchListItemEvent", { Params: params });
    return true;
}
function PublishGetMediaCountsEvent(lastCommand) {
    document.fire("HomePage:GetMediaCountsEvent", { LastCommand: lastCommand });
    return true;
}
var GetMediaCountsExecute = new function() {
    this.init = function() {
        document.observe("HomePage:GetMediaCountsEvent", function(event) { if (event.memo != null) processGetMediaCounts(event.memo.LastCommand); });
    }
    function processGetMediaCounts(obj) {
        try {
            var options = {
                method: "POST",
                postBody: Object.toQueryString({ Action: "GetMediaCounts", LastCommand: obj }),
                onSuccess: function(transport) { GetMediaCountsCallback(transport.status, transport.responseText) }
            };
            new Ajax.Request('UtilHandler.ashx', options)
        }
        catch (e) {
        }
    }
    function GetMediaCountsCallback(type, data, evt) {
        if (data != "")
            MediaButton.SetCounts(data);
    }
}
GetMediaCountsExecute.init();
function watchListItemAutoRefresh(obj) {
    var options = {
        method: "get",
        parameters: Object.toQueryString({ WLC: 1, Action: "autorefresh" }),
        onSuccess: function(transport, json) { WatchListItemCallback(transport.status, transport.responseText, transport); }
    };
    new Ajax.Request('WatchList.ashx', options)
}
function processWatchListItem(obj) {
    try {
        var options = {
            method: "get",
            parameters: Object.toQueryString({ WLC: 2, Action: "add", WatchListID: obj.WatchListID, ContentId: obj.ContentId, Format: obj.Format, ItemID: obj.ItemID, RecordID: obj.RecordID, MediaType: obj.MediaType, ItemName: obj.Name, ItemStartDate: obj.ItemStartDate, ItemExpireDate: obj.ItemExpireDate }),
            onSuccess: function(transport) { WatchListItemCallback(transport.status, transport.responseText, transport) }
        };
        new Ajax.Request('WatchList.ashx', options);
    }
    catch (e) { }
    return true;
}
function WatchListItemCallback(type, data, evt) {
    WatchListRefresh();
    return true;
}
function WatchListRefresh() {
    if (window.parent.frames.length > 0)//bug fix - frame not found on search prview page ,check length
    {
        var iframeObj = window.parent.frames["watchListIFrame"].document.getElementById(watchListId);
        var watchListID = "-1";
        var WatchListFrame = null;
        WatchListFrame = window.parent.frames["watchListIFrame"];
        if (iframeObj != null && iframeObj.selectedIndex != -1) {
            watchListID = iframeObj.options[iframeObj.selectedIndex].value;
        }
        WatchListFrame.location.href = 'WatchList.aspx?lbxid=' + watchListID;
    }
}
function trim(inputString) {
    if (typeof inputString != "string") return inputString;
    var retValue = inputString;
    var ch = retValue.substring(0, 1);
    while (ch == " ") { // Check for spaces at the beginning of the string
        retValue = retValue.substring(1, retValue.length);
        ch = retValue.substring(0, 1);
    }
    ch = retValue.substring(retValue.length - 1, retValue.length);
    while (ch == " ") { // Check for spaces at the end of the string
        retValue = retValue.substring(0, retValue.length - 1);
        ch = retValue.substring(retValue.length - 1, retValue.length);
    }
    // Note that there are two spaces in the string - look for multiple spaces within the string
    while (retValue.indexOf("  ") != -1) {
        // Again, there are two spaces in each of the strings
        retValue = retValue.substring(0, retValue.indexOf("  ")) + retValue.substring(retValue.indexOf("  ") + 1, retValue.length);
    }
    return retValue; // Return the trimmed string back to the user
}
function oneUp(URL) {
    day = new Date();
    id = day.getTime();
    eval("page" + id + " = window.open(URL, '" + id + "', 'toolbar=0,scrollbars=1,location=0,statusbar=0,menubar=0,resizable=1,width=945,height=665,left=0,top=0');");
}
function oneUpReport(URL) {
    var h = 665;
    var w = 945;
    var lp = (screen.width) ? (screen.width - w) / 2 : 0;
    var tp = (screen.height) ? (screen.height - h) / 2 : 0;
    window.open(URL, null, 'toolbar=0,scrollbars=1,location=0,statusbar=0,menubar=0,resizable=1,width=' + w + ',height=' + h + ',left=' + lp + ',top=' + tp);
}
function showHide(elem) {
    (elem.style.display == '' || elem.style.display == 'block') ? elem.style.display = "none" : elem.style.display = "";
}
var clicks = 0;
function swapText(obj, oText, cText) {
    if (clicks == 0) {
        obj.innerHTML = cText;
        clicks = 1;
    }
    else {
        obj.innerHTML = oText;
        clicks = 0;
    }
    return;
}
// Removes annoying rectangle in Firefox 1.5
var removeRectangle = function() {
    if (navigator.userAgent.indexOf('Firefox') != -1) {
        var lnks = document.links;
        if (lnks) {
            for (var i = 0; i < lnks.length; i++) {
                lnks[i].onmousedown = function() {
                    this.blur();
                    return false;
                }
            }
        }
    }
}
document.which = function(elem) {
    var value = document.getElementById(elem);
    return value;
}
if (!Array.prototype.push) {
    Array.prototype.push = function() {
        var startLength = this.length;
        for (var i = 0; i < arguments.length; i++)
            this[startLength + i] = arguments[i];
        return this.length;
    }
};
Array.prototype.contains = function(element) {
    for (var i = 0; i < this.length; i++) {
        if (this[i] === element) {
            return true;
        }
    }
    return false;
};
Array.prototype.clear = function() {
    this.length = 0;
};
Array.prototype.remove = function(element) {
    var result = false;
    var array = [];
    for (var i = 0; i < this.length; i++) {
        if (this[i] === element) {
            result = true;
        } else {
            array.push(this[i]);
        }
    }
    this.clear();
    for (var i = 0; i < array.length; i++) {
        this.push(array[i]);
    }
    array = null;
    return result;
};
// Determine whether a node's text content is entirely whitespace.
function is_all_ws(nod) {
    // Use ECMA-262 Edition 3 String and RegExp features
    return !(/[^\t\n\r ]/.test(nod.data));
}
//Determine if a node should be ignored by the iterator functions.
function is_ignorable(nod) {
    return (nod.nodeType == 8) || // A comment node
         ((nod.nodeType == 3) && is_all_ws(nod)); // a text node, all ws
}
// Version of |previousSibling| that skips nodes that are entirely whitespace or comments.
function node_before(sib) {
    while ((sib = sib.previousSibling)) {
        if (!is_ignorable(sib)) return sib;
    }
    return null;
}
// Version of |nextSibling| that skips nodes that are entirely whitespace or comments.
function node_after(sib) {
    while ((sib = sib.nextSibling)) {
        if (!is_ignorable(sib)) return sib;
    }
    return null;
}
var leftMenu = new Array();
if (userState.leftMenu) {
    var hidden = userState.leftMenu.split(',');
    for (var x in hidden) {
        leftMenu[x] = hidden[x];
    }
}
document.getElementsByClassName = function(className) {
    if (document.all) {
        var children = document.all;
    } else {
        var children = document.getElementsByTagName('*');
    }
    var elements = new Array();
    for (var i = 0; i < children.length; i++) {
        var child = children[i];
        var classNames = child.className.split(' ');
        for (var j = 0; j < classNames.length; j++) {
            if (classNames[j] == className) {
                elements.push(child);
                break;
            }
        }
    }
    return elements;
}
function FixPhotos() {
    var photos = document.which('photos');
    if (photos) {
        var oldstyle = photos.style.display;
        if (oldstyle == 'none')
            photos.style.display = "block";
        var photoli = photos.getElementsByTagName('li');
        liHeight(photoli);
        photos.style.display = oldstyle;
    }
}
function FixGraphics() {
    var graphics = document.which('graphic');
    if (graphics) {
        var oldstyle = graphics.style.display;
        if (oldstyle == 'none')
            graphics.style.display = "block";
        graphicsli = graphics.getElementsByTagName('li');
        liHeight(graphicsli);
        graphics.style.display = oldstyle;
    }
}
var windowDoPop
function go(whichURL) {
    var go_url = 'http://www.ap.org/pages/contact/' + whichURL[whichURL.selectedIndex].value;
    windowDoPop = window.open(go_url, 'doPop', 'toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=no,top=40,width=450,height=450');
    windowDoPop.focus();
}
function HomePageDownload(download_item) {
    try {
        var item = eval(download_item);
        if (item.isALaCarte == 'true') {
            GetDownloadStatus(download_item);
        } else {
            alert("download coming soon..");
        }
    }
    catch (e) { alert(e.name + " : " + e.message); }
}
function DoDownload(d_url) {
    var uri = d_url.trim(); //since Safari acts up                                           
    frames['dwnloadIFrame'].location.href = uri;
}
var CCINewsGateObject = Class.create();
CCINewsGateObject.prototype = {
    initialize: function() {
        //this.onSuccess = onSuccess || Prototype.emptyFunction;
        //alert('initialized CCINewsGateObject');
    },
    generate: function() {
        var options = {
            method: "POST",
            postBody: Object.toQueryString({ a: "generate" }),
            onSuccess: function(transport) { UpdateCCINewsgate(transport.status, transport.responseText) }
        };
        new Ajax.Request('CCINewsGate.ashx', options)
        return false;
    },
    remove: function(mediatype_recordid) {
        var options = {
            method: "POST",
            postBody: Object.toQueryString({ a: "remove", guids: mediatype_recordid }),
            onSuccess: function(transport) { UpdateCCINewsgate(transport.status, transport.responseText) }
        };
        new Ajax.Request('CCINewsGate.ashx', options)
        return false;
    }
};

function check_OnChange(mediatype_recordid, download_item) {
    //debugger
    var action;
    var id = mediatype_recordid.split("_");
    var cbox = this;
    var itembox = $("item_box_" + id[1]);
    if (this.checked) {
        if (download_item.isALaCarte == 'true') {
            this.checked = false;
            DownloadManager.DoDownload(download_item, function() {
                cbox.checked = true;
                Element.addClassName(itembox, "selected");
                action = "add";
                try {
                    var options = {
                        method: "POST",
                        postBody: Object.toQueryString({ a: action, guids: mediatype_recordid, Selectedashx: 2 }),
                        onSuccess: function(transport) { SelectedCountCallback(transport.status, transport.responseText) }
                    };
                    new Ajax.Request('Selected.ashx', options)
                }
                catch (e) { }
            });
        } else {
            Element.addClassName(itembox, "selected");
            action = "add";
        }
    }
    else {
        Element.removeClassName(itembox, "selected");
        action = "rem";
    }
    try {
        var options = {
            method: "POST",
            postBody: Object.toQueryString({ a: action, guids: mediatype_recordid, Selectedashx: 3 }),
            onSuccess: function(transport) { SelectedCountCallback(transport.status, transport.responseText) }
        };
        new Ajax.Request('Selected.ashx', options)
    }
    catch (e) { }
}
function SelectedCountCallback(type, data, evt) {
    //debugger
    if ($("lblSelected")) {
        $("lblSelected").innerHTML = "Bulk Downloads (" + data + ")";
    }
    SelectedCount = data;
    cciNGObj = new CCINewsGateObject();
    cciNGObj.generate();
}

function ConfirmCCISelected() {
    if (SelectedCount != "0") {
        var cciURL = $("cciDLLink").href;
        window.open(cciURL);
        return true;
    }
    else {
        alert("No items have been selected.");
        return false;
    }
}
function UpdateCCINewsgate(type, data) {
    //debugger
    if ($("cciDLLink")) {
        $("cciDLLink").href = data;
    }
}
function GetSelectedCount() {
    var action = "get";
    var record_id = "0";
    try {
        var options = {
            method: "POST",
            postBody: Object.toQueryString({ a: action, guids: record_id, Selectedashx: 4 }),
            onSuccess: function(transport) { SelectedCountCallback(transport.status, transport.responseText) }
        };
        new Ajax.Request('Selected.ashx', options)
    }
    catch (e) { }
}
