
$(document).ready(function() {
    mainmenu();

    MM_preloadImages('/Images/green_star.png', '/Images/full_star.png', '/Images/empty_star.png');
    if (typeof (pARTICLERATE) != "undefined")
        SetRatings(pARTICLERATE, '0');

    if ($('#WA_LATEST') != null) {
        GetWidgetArticles(2);
    }
    if (typeof (pSEARCHCRITERIA) != "undefined")
    //if ($('#SearchResultArticles') != null)
    {
        if (pSEARCHCRITERIA != "") {
            //pSEARCHCRITERIA = $("[id$='txt_Search']").val() ;
            if (pSEARCHCRITERIA.substr(0, 1) == "o") {
                $("[id$='TXT_OBITUARYSEARCH']").val(pSEARCHCRITERIA.substr(1));
            } else if (pSEARCHCRITERIA.substr(0, 1) == "g") {
                $("[id$='txt_Search']").val(pSEARCHCRITERIA.substr(1));
            }
            SearchArticle(1);
        }
    }
    PrepareCommentsActions();
    PrepareRatingsTitle();
});
function GetWidgetArticles(param1) {

    try {
        if (typeof (pCATEGORYCODE) != "undefined") {

//            if (pCATEGORYCODE == 'CAT0') {
//                param1 = 1//cheating a little, the default request is for latest news, but at home page we need to get most read since latest news is not supposed to be shown there.
//            }

            $.ajax(
            {
                url: "/Services/ServiceMSDigitalDaily.svc/GetWidgetArticles",
                data: '{ "iWidgetType" : ' + param1 + ',"sCategoryCode" : "' + pCATEGORYCODE + '","iCategoryId" : ' + pCATEGORYID + '}',
                type: "POST",
                contentType: "application/json; charset=utf-8",
                timeout: 10000,
                dataType: "json",
                async: false,
                success: function(msg) { AjaxSucceeded(msg); },
                error: AjaxFailed
            }
          );
        }
    } catch (e) { }
    return false;
}

function AjaxSucceeded(result) {
    var objReturn = JSON.parse(result.d);
    $('#WidgetArticles').setTemplate($("#WidgetArticlesTemplate").html());
    $('#WidgetArticles').setParam("param1", pCATEGORYCODE);
    $('#WidgetArticles').processTemplate(objReturn);
}
function AjaxFailed(result) {

    var message = result.responseText.substring(result.responseText.indexOf(">") + 1);
    message = message.substring(0, message.indexOf("<"));
    alert(message);

    //alert(result.status + ' ' + result.statusText);
}

function convertAsciiToChars(myString) {
    var replaceChars = "'#&\"%"; // Characters that should be replaced
    for (var no = 0; no < replaceChars.length; no++) {
        myString = myString.replace("&#" + replaceChars.charCodeAt(no) + ";", replaceChars.charAt(no));
    }

    return myString;
}

function alphaOnly(title) {
    //alert(title);
    title = title.replace(/[^a-zA-Z0-9]+/g, ' ').trim();
    return title;
}
function SeoNavigateUrl(pCatLevel, pCatName, pCatCode, pTitle, pId) {
    if (pCatCode != "CAT8") {
        pCatName = unescape(pCatName);
        //var sLink = "/" + pCatLevel + "/" + pCatName.replace(/\$|\//gi, " ") + "/" + pCatCode;
        var sLink = "/" + pCatLevel + "/" + pCatName.replace(/[^a-zA-Z0-9]+/g, ' ').trim() + "/" + pCatCode;
        if (pTitle != null) {
            sLink += "/" + unescape(pTitle).replace(/[^a-zA-Z0-9]+/g, ' ').trim() + "/" + pId;
            //sLink = sLink + "/" + unescape(pTitle.replace(/\$|\//gi, " ").replace(/\$|\./gi, "")).trim() + "/" + pId;
        }
        sLink += "/default.aspx";
        window.location.href = unescape(sLink);
    } else {
    //alert('asd');
        OpenPopup("/AudioForm.aspx", 590, 652);
    }
    return false;
}
function SeoSearchUrl(e) {
    var sSearchFilter = "";
    if (window.event)
        e = window.event;
    var srcEl = e.srcElement ? e.srcElement : e.target;
    if (srcEl.id.indexOf("btn_Search") > -1)
        sSearchFilter = "g" + $("[id$='txt_Search']").val();
    else if (srcEl.id.indexOf("BTN_OBITUARYSEARCH") > -1)
        sSearchFilter = "o" + $("[id$='TXT_OBITUARYSEARCH']").val();
    if (pCATEGORYID != null && (pCATEGORYID * 1) > 0)
        SeoNavigateUrl(6, "SearchArticle", pCATEGORYCODE, escape(sSearchFilter.trim()), pCATEGORYID);
    else
        SeoNavigateUrl(6, escape(sSearchFilter.trim()), pCATEGORYCODE);
    return false;
}
function NavigateForm(pCatLevel, pArticleId, pCatCode) {
    window.location.href = "../Categories.aspx?CATEGORYLEVEL=" + pCatLevel + "&ID=" + pArticleId + "&CATEGORYCODE=" + pCatCode;
}

function NavigateLinks(e, pCatLevel, pCatId, pCatCode) {
    if (pCatCode != "CAT8") {
        var navQueryString = "CATEGORYCODE=" + pCatCode;
        navQueryString += (pCatLevel != null ? "&CATEGORYLEVEL=" + pCatLevel : "");
        navQueryString += (pCatId != null ? "&CATEGORYID=" + pCatId : "");
        //navQueryString += ((pCatLevel != null && pCatLevel == 6) ? "&SEARCHCRITERIA=" + $("[id$='txt_Search']").val() : "");
        var sSearchFilter = "";
        if (window.event)
            e = window.event;
        var srcEl = e.srcElement ? e.srcElement : e.target;
        if (srcEl.id.indexOf("btn_Search") > -1)
            sSearchFilter = "g" + $("[id$='txt_Search']").val();
        else if (srcEl.id.indexOf("BTN_OBITUARYSEARCH") > -1)
            sSearchFilter = "o" + $("[id$='TXT_OBITUARYSEARCH']").val();
        navQueryString += ((pCatLevel != null && pCatLevel == 6 && sSearchFilter != "") ? "&SEARCHCRITERIA=" + sSearchFilter : "");
        window.location.href = "/Categories.aspx?" + navQueryString;
    }
    else {
        OpenPopup("/AudioForm.aspx", 598, 652);
    }
    return false;
}


function SearchArticle(iPageIndex) {
    if ($('#SearchResultArticles').length > 0) {
        try {
            //$("[id$='txt_Search']").val = pSEARCHCRITERIA;
            var tmpCategoryCode = pCATEGORYCODE;
            //if (pCATEGORYCODE == "CAT7" && pSEARCHCRITERIA.substr(0, 1) == "g")
            if (pSEARCHCRITERIA.substr(0, 1) == "g")
                tmpCategoryCode = "CAT0"
            if (typeof (pCATEGORYCODE) != "undefined") {
                $.ajax(
            {
                url: "/Services/ServiceMSDigitalDaily.svc/GetSearchedResultArticles",
                data: '{ "sCategoryCode" : "' + tmpCategoryCode + '","iCategoryId" : ' + pCATEGORYID + ',"iCurrentPageIndex" : ' + iPageIndex + ',"sSearchCriteria" : "' + pSEARCHCRITERIA.substr(1) + '"}',
                type: "POST",
                contentType: "application/json; charset=utf-8",
                timeout: 10000,
                dataType: "json",
                async: false,
                success: function(msg) { SearchSucceeded(msg); },
                error: AjaxFailed
            }
          );
            }
        } catch (e) { }
    }
    return false;
}

function SaveRate(strSection, strId, strRate) {
    if (pUSERID == "" || pUSERID == null)
        return;
    m_ratecontrol = true;
    try {
        $.ajax(
            {
                url: "/Services/ServiceMSDigitalDaily.svc/SaveRatings",
                data: '{ "strSection" : "' + strSection + '","strId" : "' + strId + '","strRate" : "' + strRate + '"}',
                type: "POST",
                contentType: "application/json; charset=utf-8",
                timeout: 10000,
                dataType: "json",
                async: false,
                success: function(msg) { SaveRateSucceeded(msg); },
                error: function(msg) { SaveRateFailed(msg); }
            }
          );
    } catch (e) { }
    return false;
}

function SaveRateSucceeded(result) {
    var objReturn = JSON.parse(result.d);

    if (parseInt(objReturn) > 0) {
        SetRatings(parseInt(objReturn), 1);
    }
}

function SaveRateFailed(result) {
    alert('Dont Save, ' + result);
    m_ratecontrol = false;
    LostFocusRating();
}
function SearchSucceeded(result) {
    var objReturn = JSON.parse(result.d);
    $("#SearchResultArticles").setTemplate($("#SearchResultArticlesTemplate").html());
    var iBeginPagination = Math.floor((objReturn.PAGEDEFINITIONS[0]["CURRENTPAGEINDEX"] - 1) / objReturn.PAGEDEFINITIONS[0]["PAGINATIONCOUNT"]) * objReturn.PAGEDEFINITIONS[0]["PAGINATIONCOUNT"] + 1;
    var iEndPagination = iBeginPagination + objReturn.PAGEDEFINITIONS[0]["PAGINATIONCOUNT"] - 1;
    var iPageCount = Math.ceil(objReturn.PAGEDEFINITIONS[0]["RECORDCOUNT"] / objReturn.PAGEDEFINITIONS[0]["PAGERECORDCOUNT"]);
    iEndPagination = iEndPagination > iPageCount ? iPageCount : iEndPagination;
    $("#SearchResultArticles").setParam("BEGINPAGINATION", iBeginPagination);
    $("#SearchResultArticles").setParam("ENDPAGINATION", iEndPagination);
    $("#SearchResultArticles").setParam("PAGECOUNT", iPageCount);
    $("#SearchResultArticles").setParam("param1", pCATEGORYCODE);
    $("#SearchResultArticles").processTemplate(objReturn);
}

function StripHtml(val) {
    var regexp = /<("[^"]*"|'[^']*'|[^'">])*>/gi;
    return val.replace(regexp, "");
}
function StripLineBreaks(val) {
    return val.replace(new RegExp("\\n", "g"), "");
}

function SaveComment() {
    try {
        if (typeof (pCATEGORYCODE) != "undefined") {
            $.ajax(
                    {
                        url: "/Services/ServiceMSDigitalDaily.svc/SetArticleComment",
                        data: '{ "sUserID" : "' + pUSERID + '","iArticleID" : ' + pID + ',"iContentType" : ' + pCONTENTTYPE + ',"sComment" : "' + StripLineBreaks(StripHtml($("#FV_GENERALARTICLEDETAIL_TXT_COMMENT").val())) + '"}',
                        type: "POST",
                        contentType: "application/json; charset=utf-8",
                        timeout: 10000,
                        dataType: "json",
                        async: false,
                        success: function(msg) { if (msg.toString() == "SUCCESS") { CommentSucceeded(msg); } else { alert(msg.toString()); } },
                        error: function(result) { if (result.status == '200' && result.responseText.indexOf("SUCCESS") >= 0) { CommentSucceeded(result); } else {  AjaxFailed(result); } }
                    }
                 )
        }
    } catch (e) { }
    return false;
    //error: function(result) { if (result.status == '200') { CommentSucceeded(result); } else { AjaxFailed(result); } }
}
function CommentSucceeded(result) {
    alert("Your comment has been added");
    location.reload();
}
function ShowHideComments() {
    if ($("[id$='LBL_HIDECOMMENTS']").text() == "Hide Comments") {
        $("[id$='DL_COMMENTS']").attr("style", "display:none");
        $("[id$='TR_CommentsIntro']").attr("style", "display:none");
        $("[id$='TR_CommentsInput']").attr("style", "display:none");
        $("[id$='TR_CommentsFooter']").attr("style", "display:none");
        $("[id$='IMG_HIDECOMMENTS']").attr("src", "/images/down-triangle.gif");
        $("[id$='LBL_HIDECOMMENTS']").text("Show Comments");
    }
    else if ($("[id$='LBL_HIDECOMMENTS']").text() == "Show Comments") {
        $("[id$='DL_COMMENTS']").attr("style", "display:'';width:100%;");
        $("[id$='TR_CommentsIntro']").attr("style", "display:'';width:100%;");
        $("[id$='TR_CommentsInput']").attr("style", "display:'';width:100%;");
        $("[id$='TR_CommentsFooter']").attr("style", "display:'';width:100%;");
        $("[id$='LBL_HIDECOMMENTS']").text("Hide Comments");
        $("[id$='IMG_HIDECOMMENTS']").attr("src", "/images/up-triangle.gif");
    }

}
function PrepareCommentsActions() {
    if (typeof (pUSERID) != "undefined") {
        if (pUSERID == "") {
            $("[id$='TXT_COMMENT']").attr("style", "display:none");
            $("[id$='TBL_COMMENTACTIONS']").attr("style", "display:none");
            $("[id$='TD_COMMENTSLOGIN']").attr({ style: "display:'';padding:5px 20px 5px 20px;font-weight:bold;" });
        }
        if (pUSERID != "") {
            $("[id$='TXT_COMMENT']").attr({ style: "display:'';width:100%" });
            $("[id$='TBL_COMMENTACTIONS']").attr({ style: "display:'';width:100%" });
            $("[id$='TD_COMMENTSLOGIN']").attr({ style: "display:none;" });
        }
    }
}

function PrepareRatingsTitle() {
    if (typeof (pUSERID) != "undefined") {
        if (pUSERID == "") {
            $("[id$='imgRate_1']").attr("alt", "You must be logged in to provide a rating");
            $("[id$='imgRate_1']").attr("title", "You must be logged in to provide a rating");
            $("[id$='imgRate_2']").attr("alt", "You must be logged in to provide a rating");
            $("[id$='imgRate_2']").attr("title", "You must be logged in to provide a rating");
            $("[id$='imgRate_3']").attr("alt", "You must be logged in to provide a rating");
            $("[id$='imgRate_3']").attr("title", "You must be logged in to provide a rating");
            $("[id$='imgRate_4']").attr("alt", "You must be logged in to provide a rating");
            $("[id$='imgRate_4']").attr("title", "You must be logged in to provide a rating");
            $("[id$='imgRate_5']").attr("alt", "You must be logged in to provide a rating");
            $("[id$='imgRate_5']").attr("title", "You must be logged in to provide a rating");
        }
        if (pUSERID != "") {
            $("[id$='imgRate_1']").attr("alt", "Lowest");
            $("[id$='imgRate_1']").attr("title", "Lowest");
            $("[id$='imgRate_2']").attr("alt", "Lower");
            $("[id$='imgRate_2']").attr("title", "Lower");
            $("[id$='imgRate_3']").attr("alt", "Normal");
            $("[id$='imgRate_3']").attr("title", "Normal");
            $("[id$='imgRate_4']").attr("alt", "Higher");
            $("[id$='imgRate_4']").attr("title", "Higher");
            $("[id$='imgRate_5']").attr("alt", "Highest");
            $("[id$='imgRate_5']").attr("title", "Highest");
        }
    }
}

function AddRightWidgets() {
    //if (pCATEGORYCODE == "CAT0") 
    //{
    var WidgetWeather = $("<div id='WidgetWeather'></div>");
    WidgetWeather.setTemplateURL("/UserControls/jtmp.tau");
    WidgetWeather.setParam("param1", pCATEGORYCODE);
    WidgetWeather.processTemplate($("#TemplateWeather"));
    $("[id$='CPH_RIGHTSECTION']").append(WidgetWeather.html().replace(/\$|\REPSCRIPT/gi, 'SCRIPT'));
    $("DIV[scriptsrc]").each(function() {
        var newScript = document.createElement('script');
        newScript.type = 'text/javascript';
        newScript.charset = 'utf-8';
        newScript.src = $(this).attr("scriptsrc");
        document.all($(this).attr("id")).appendChild(newScript);
        $(this).removeAttr("scriptsrc");
    }
        );
    //}
}
function OpenInAppropriateDialog(iCommentId) {
    if ($("#TestInappropriate").length == 0) {
        var test = $("<div id='TestInappropriate'></div>");
        test.setTemplateURL("/UserControls/jtmp.tau");
        test.setParam("param1", iCommentId);
        test.processTemplate($("#TemplateInappropriate").html());
        $(document.body).append(test)
    }
    $("#DLG_INAPPROPRIATE").dialog({
        closeOnEscape: true,
        draggable: false,
        modal: true,
        resizable: false,
        autoOpen: false,
        bgiframe: true,
        title: 'Why is this inappropriate?',
        width: 360,
        height: 160,
        zIndex: 100
    });
    $("#DLG_INAPPROPRIATE").dialog('open');
}
function SubmitInAppropriate(iCommentId) {
    try {
        $.ajax(
            {
                url: "/Services/ServiceMSDigitalDaily.svc/SetInApprotiate",
                data: '{ "iArticleID" : ' + pID + ',"iContentType" : ' + pCONTENTTYPE + ',"iCommentId" : ' + iCommentId + ',"sComment" : "' + $("#TXT_INAPPROPRIATE").val() + '"}',
                type: "POST",
                contentType: "application/json; charset=utf-8",
                timeout: 10000,
                dataType: "json",
                async: false,
                success: function(msg) { if (msg.toString() == "") { alert("Your feedback has been submitted."); $('#DLG_INAPPROPRIATE').dialog('close'); } else { alert(msg.toString()); } },
                error: function(result) { if (result.status == '200') { alert("Your feedback has been submitted."); $('#DLG_INAPPROPRIATE').dialog('close'); } else { AjaxFailed(result); } }
            }
          );
    } catch (e) { }
    return false;
}




