﻿/// <reference name="MicrosoftAjax.js" />

var togglePostCommentsSubscriptionMessage = "";

function toggleCommentsSubscription(id, messageUpdate) {
    if (togglePostCommentsSubscriptionMessage == "") {
        togglePostCommentsSubscriptionMessage = messageUpdate;
    }
    $get('toggleCommentsSubscription').style.display = "none";
    $get('toggleCommentsSubscription_span').style.display = "";
    executeWebRequest("/global/toggle_comment_subscription.ashx", "POST", "post_id=" + id + "&ref_url=" + escape2(window.document.location.href), toggleCommentsSubscriptionCallback);
}

function toggleCommentsSubscriptionCallback(executor, eventArgs) {
    var result = executor.get_responseData();
    
    if (result != "OK") {
        redirect(result)
    } else {
        var toggleCommentsSubscription = $get('toggleCommentsSubscription');
        
        // change Alt of the button
        var tempMessage = toggleCommentsSubscription.firstChild.alt;
        toggleCommentsSubscription.firstChild.alt = togglePostCommentsSubscriptionMessage;
        toggleCommentsSubscription.firstChild.title = togglePostCommentsSubscriptionMessage;
        togglePostCommentsSubscriptionMessage = tempMessage;
        
        // change image of the button
        if (toggleCommentsSubscription.firstChild.src.indexOf("eCheckedB") != -1) 
        {
           toggleCommentsSubscription.firstChild.src = toggleCommentsSubscription.firstChild.src.replace("eCheckedBtn", "eBtn");
        }
        else
        {
           toggleCommentsSubscription.firstChild.src = toggleCommentsSubscription.firstChild.src.replace("eBtn", "eCheckedBtn");
        }
        
        $get('toggleCommentsSubscription_span').style.display = "none";
        toggleCommentsSubscription.style.display = "";
    }
}

window.onerror = function(message, url, lineNumber) {
    if (message.match(/'_gat' is undefined/) !== null) {
        return true;
    }
    if (message.match(/Error loading script/) !== null && message.indexOf("bloggersbase") == -1) {
        return true;
    }
    executeWebRequest(basePath + "logJSError.aspx", "POST", "message=" + escape2(message) + "&url=" + escape2(url) + "&lnum=" + lineNumber);
    return false;
}

var oldonload = window.onload;
if (typeof window.onload != 'function') {
    window.onload = onPageLoad;
} else {
    window.onload = function() {
        if (oldonload) {
            oldonload();
        }
        onPageLoad();
    }
}
function onPageLoad() {
    if (window.onClientPageLoadCode !== undefined && onClientPageLoadCode) {
        eval(onClientPageLoadCode);
    }
}

function page_init() {
    if (window.onClientPageInitCode !== undefined && onClientPageInitCode) {
        eval(onClientPageInitCode);
    }
}

//function pageLad() {
//    if (window.onClientPageLoadCode !== undefined && onClientPageLoadCode) {
//        eval(onClientPageLoadCode);
//    }
//}

function onStateChanged(sender, e) {
    var val = e.get_state().s;
    if (val) eval(unescape(val));
}

function addMicrosoftHistoryPoint(module, pageNum, link) {
    Sys.Application.addHistoryPoint({ s: escape2(link) });
}

String.prototype.trim = function() {
    return str.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
}

function escape2(str) {
    return escape(str).replace("+", "%2B").replace("/", "%2F").replace("&", "%26").replace("?", "%3F").replace("=", "%3D").replace("'", "%27").replace("\"", "%22");
}

function executeWebRequest(url, method, params, func) {
    var wRequest = new Sys.Net.WebRequest();
    if (method == "GET") wRequest.set_url(url + "?" + params); else wRequest.set_url(url);

    wRequest.set_httpVerb(method);

    if (method == "POST") {
        wRequest.set_body(params);
        wRequest.get_headers()["Content-Length"] = params.length;
    }

    if (func && func !== undefined) wRequest.add_completed(func);
    wRequest.invoke();
}

function redirect(path, objIdToDisable, disabledObjId) {
    if (objIdToDisable != undefined && disabledObjId != undefined) {
        disable(objIdToDisable, disabledObjId);
    }
    if (path !== undefined && path) {
        window.location.href = path;
    }
    else {
        reload();
    }
}

function redirectHome() {
    redirect(basePath);
}

function doRedirect(event, path) {   
    event.cancelBubble = true;
    window.location.href = path;
}

function reload() {
    window.location.reload(location.href);
}

function disable(objIdToDisable, disabledObjId) {
    if (objIdToDisable) {
        var obj = $get(objIdToDisable);
        if (obj) {
            obj.disabled = true;
            obj.style.display = "none";
        }
    }
    
    if (disabledObjId)
    {
        var obj = $get(disabledObjId);
        if (obj)
        {
            obj.style.display = "";
        }
    }
}

function enable(objIdToEnable, objIdToHide) {
    if (objIdToEnable) {
        var obj = $get(objIdToEnable);
        if (obj) {
            obj.disabled = false;
            obj.style.display = "";
        }
    }
    
    if (objIdToHide) {
        var obj = $get(objIdToHide);
        if (obj) {
            obj.style.display = "none";
        }
    }
}

function enterKeyCheck(e, btnId) {
    var characterCode;
    if(e && e.which != undefined)
    {
        characterCode = e.which; //character code is contained in NN4's which property
    }
    else
    {
        e = event;
        characterCode = e.keyCode; //character code is contained in IE's keyCode property
    }
    
    if (characterCode == 13)
    {
        $("#" + btnId).click();
        return false;
    }
    return true;
}

function openSearchWindow(preloader_path) {
    // this is not a search page, do http redirection
    window.location = bbPath + escape2(removeInvalidSearchCharacters($("#text_input_search").val())) + "/";
}

function removeInvalidSearchCharacters(str)
{
    return str.replace("/", " ").replace("&", " ");
}

// -----------------------------------------
// http://www.quirksmode.org/js/cookies.html
function createCookie(name, value, days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        var expires = "; expires=" + date.toGMTString();
    }
    else {
        var expires = ""; 
    }
	
	document.cookie = name + "=" + value + expires + "; path=/";
}

function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') c = c.substring(1, c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
    }
    return null;
}

function deleteCookie(cookie_name) {
    document.cookie = cookie_name + "=;path=/;expires=Thu, 01-Jan-1970 00:00:01 GMT";
}

// -----------------------------------------

// http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=1843487&SiteID=1
if (typeof (window.external) != 'undefined') {
    document.getElementsByName = function(name, tag) {
        if (!tag) {
            tag = '*';
        }
        var elems = document.getElementsByTagName(tag);
        var res = []
        for (var i = 0; i < elems.length; i++) {
            att = elems[i].getAttribute('name');
            if (att == name) {
                res.push(elems[i]);
            }
        }
        return res;
    }
}

function isDefined(variable) {
    return (typeof(window[variable]) != "undefined");
}

function htmlToDocumentFragment(htmlString) {
    var tempDiv = document.createElement('div');
    tempDiv.innerHTML = htmlString;
    if (tempDiv.childNodes.length == 1) {
        return tempDiv.firstChild;
    } else {
        var fragment = document.createDocumentFragment();
        while (tempDiv.firstChild) {
            fragment.appendChild(tempDiv.firstChild);
        }
        return fragment;
    }
}

function gotoTop() {
    document.documentElement.scrollTop = 0;
}

function showErrorMessage(html) {
    var div = htmlToDocumentFragment(html);
    var oldDiv = $get(div.id);
    if (oldDiv == null) {
        $get("ContentDiv").appendChild(div);
    }
    else {
        $get("ContentDiv").replaceChild(div, oldDiv);
    }
    div.style.display = "";
    div.style.position = 'absolute';
    div.style.left = ((document.documentElement.clientWidth - div.clientWidth) / 2) + 'px';
    div.style.top = ((document.documentElement.clientHeight - div.clientHeight) / 2 + document.documentElement.scrollTop) + 'px';
    div.style.opacity = 1;
    div.style.filter = "alpha(opacity = 100)";
    setTimeout('fadeAway(\'' + div.id + '\')', 3000);
}

function ShowInCenter(element) {
    /// <summary>Move an element directly to the middle of currently displayed screen</summary>
    element1 = $get(element);
    element1.style.display = "";
    element1.style.position = 'absolute';
    element1.style.left = ((document.documentElement.clientWidth - element1.clientWidth) / 2) + 'px';
    element1.style.top = ((document.documentElement.clientHeight - element1.clientHeight) / 2 + document.documentElement.scrollTop) + 'px';
    element1.style.opacity = 1;
    element1.style.filter = "alpha(opacity = 100)";
    setTimeout('fadeAway(\'' + element + '\')', 5000);
}

function fadeAway(target) {
    var div = $get(target);
    div.style.opacity -= 0.1;
    div.style.filter = "alpha(opacity = " + (div.style.opacity * 100) + ")";

    if (div.style.opacity > 0) {
        setTimeout('fadeAway(\'' + target + '\')', 100);
    }
    else {
        div.style.display = "none"
    }
}

function replaceDiv(html) {
    var newNode = htmlToDocumentFragment(html);
    var oldNode = $get(newNode.id);
    oldNode.parentNode.replaceChild(newNode, oldNode);
}

function continueWriting(id) {
    executeWebRequest("/global/set_draft_post_id.ashx", "POST", "post_id=" + id, continueWritingCallback);
}

function continueWritingCallback(executor, eventArgs) {
    var result = executor.get_responseData();
    redirect(result);
}

function rememberUrlAndRedirect() {
    executeWebRequest("/global/remember_url.ashx", "POST", "url_to_remember=" + escape2(location.href), rememberUrlAndRedirectCallback);
}

function rememberUrlAndRedirectCallback(executor, eventArgs) {
    var result = executor.get_responseData();
    redirect(result);
}

function set_text_color(div_id, color) {
    $get(div_id).style.color = color;
}

function logout() {
    executeWebRequest("/global/logout.ashx", "POST", "", OnLogoutRequestHandler);
}

function OnLogoutRequestHandler() {
    reload();
}

function sendNotificationCallback(response) {
}

function submitAbuseReport(type, contentId) {
    if ($get("reportReasonTxt").value.length == 0) return;

    disable("submitReportArticleBtn", "submitReportArticleBtnD");
    disable("cancelReportArticleBtn", "cancelReportArticleBtnD");
    executeWebRequest("/global/submit_abuse_report.ashx", "POST", "content_id=" + contentId + "&reason=" + escape2($get("reportReasonTxt").value) + "&report_type=" + $get("reportType").options[$get("reportType").selectedIndex].value + "&abuse_content_type=" + type, submitReportArticleCallback);
}

function submitDynamicAbuseReport(type, contentIdVar) {
    if ($get("reportReasonTxt").value.length == 0) return;

    disable("submitReportArticleBtn", "submitReportArticleBtnD");
    disable("cancelReportArticleBtn", "cancelReportArticleBtnD");
    executeWebRequest("/global/submit_abuse_report.ashx", "POST", "content_id=" + eval(contentIdVar) + "&reason=" + escape2($get("reportReasonTxt").value) + "&report_type=" + $get("reportType").options[$get("reportType").selectedIndex].value + "&abuse_content_type=" + type, submitReportArticleCallback);
}

function submitReportArticleCallback(executor, eventArgs) {
    var result = executor.get_responseData();
    $.modal.close();
    if (result) showErrorMessage(result);
}

function openWindow(path, name) {
    window.open(path, name);
}

// this function is used to determine a number of current page
// page that calls this function should contain pages element
// due to the flawed design this function usage of this function
// is not recommended
function getCurrentPage() {
    var divs = document.getElementsByTagName('span');

    for (index in divs) {
        if (typeof (divs[index]) == 'object') {
            if (divs[index].getAttribute('class') == 'Selected') {
                return divs[index].innerHTML;
            }
        }
    }

    // if no pages element were found then we are on 1st page
    return 1;
}

function toggleDivVisibility(divId)
{
    var div = $get(divId);
    if (div.style.display == "") {
        div.style.display = "none";
    } else {
        div.style.display = "";
    }
}

function closeHomeStrip() {
    $get("HomeStripDiv").style.display = "none";
    createCookie("hide_upper", 1, 28);
    $get("FeaturedBlogWidget").style.display = "none";
}


function arrange_bubbles()
{
    window.onresize = function() { arrange_bubbles() };

    if (bubbleList != undefined)
    {
        var counter = 0;
        while (bubbleList['bubble_' + counter] != undefined)
        {
            $get('bubble_' + counter).style.display = '';
            $get('bubble_' + counter).style.top = (getY($get('LargeImage')) + 1 * bubbleList['bubble_' + counter]['top']) + "px";
            $get('bubble_' + counter).style.left = (getX($get('LargeImage')) + 1 * bubbleList['bubble_' + counter]['left']) + "px";

            $get('text_bubble_' + counter).style.display = '';
            $get('text_bubble_' + counter).style.top = (getY($get('LargeImage')) + 1 * bubbleList['bubble_' + counter]['shift_y'] + 1 * bubbleList['bubble_' + counter]['top'] + 0.1 * bubbleList['bubble_' + counter]['height']) + "px";
            $get('text_bubble_' + counter).style.left = (getX($get('LargeImage')) + 1 * bubbleList['bubble_' + counter]['left'] + 0.1 * bubbleList['bubble_' + counter]['width']) + "px";

            counter++;
        }
    }
}

function getY(oElement)
{
    var iReturnValue = 0;
    while (oElement != null)
    {
        iReturnValue += oElement.offsetTop;
        oElement = oElement.offsetParent;
    }
    return iReturnValue;
}

function getX(oElement)
{
    var iReturnValue = 0;
    while (oElement != null)
    {
        iReturnValue += oElement.offsetLeft;
        oElement = oElement.offsetParent;
    }
    return iReturnValue;
}

function submitNickname() {
    $get("submitNickBtn").style.display = "none";
    $get("submitNickBtnDisabled").style.display = "";

    executeWebRequest("/global/submit_nick.ashx", "POST", "nick=" + escape2($get("nicknameTxt").value), submitNicknameSuccess);
}

function submitNicknameSuccess(executor, eventArgs) {
    var result = executor.get_responseData();
    
    $get("submitNickBtn").style.display = "";
    $get("submitNickBtnDisabled").style.display = "none";

    if (result == '200') {
        $find('initUserNamePopup').hide();
    } else {
        $get("nickErrorDiv").style.display = "";
        $get("nickErrorDiv").innerHTML = result;
    }
}

function requestNameChange() {
   // $('#initUserNamePanel').modal({ containerCss: { height: '300px', width: '170px'} });
}

// the function that is called from the facebook connect
function facebookCallback(callbackPath, facebookApiKey)
{
    if (!isDefined("updateMyFacebookLiveFeed"))
    {
        // this is not a virality page
        $('' + unescape(FacebookPopup) + '').modal({ containerCss: { height: '300px', width: '750px'} });
        $get("FacebookLoginIFrame").src = "http://www.facebook.com/authorize.php?api_key=" + facebookApiKey + "&v=1.0&ext_perm=offline_access&next=" + encodeURI(callbackPath) + "&next_cancel=" + encodeURI(callbackPath);
    }
    else
    {
        updateMyFacebookLiveFeed();
    }
}

function logOffFacebook(apiKey, sessionKey) {
    FB.Connect.logout(function() {});
    executeWebRequest("/global/remove_fb_session.ashx", "POST", "", facebookLogoutCallback);
}

function facebookLogoutCallback() {
    reload();
}

function facebookLogin(callbackPath, facebookApiKey) {
    if (FB.Connect.get_loggedInUser() != null) {
        userContext = { 'path': callbackPath, 'apikey': facebookApiKey };
        executeWebRequest("/global/fb_login.ashx", "POST", "with_association=0", facebookLoginCallback);
    }
}

function facebookLoginCallback(executor, eventArgs) {
    var result = executor.get_responseData();

    var resultParams = eval("(" + unescape(result) + ")");
    if (resultParams["status"] == 1) {
        // in order to avoid reload - need to change buttons events on post page
        //$get("LoginDivContainer").innerHTML = resultParams["body"];
        $('' + unescape(FacebookPopup) + '').modal({ containerCss: { height: '300px', width: '750px'} });
        $get("FacebookLoginIFrame").src = "http://www.facebook.com/authorize.php?api_key=" + userContext['apikey'] + "&v=1.0&ext_perm=offline_access&next=" + encodeURI(userContext['path']) + "&next_cancel=" + encodeURI(userContext['path']);
        //reload();
    } else {
        showErrorMessage(resultParams["body"]);
    }
}

function performTwitterLogin(path, elementId)
{
    if ($get(elementId).checked) openWindow(path, "twitterLogin");
}

function performFacebookLogin(path, elementId) {
    if (elementId == null || $get(elementId).checked) {
        executeWebRequest("/global/set_fb_association_flag.ashx", "POST", "");
        FB.Connect.requireSession(facebookLoggedIn); 
        return false;
    }
}

function switchNavBarTab(tabsContainerId, currentTabCssId, originalTab, menuContainerId) {
    var currTab = null;
    var ul = $get(tabsContainerId);
    for (var i = 0; i < ul.childNodes.length; ++i) {
        ul.childNodes[i].id = "";
        var tabString = ul.childNodes[i].attributes["name"].value;
        //var stringLength = tabString.length;

        //$get(tabString).style.display = "none";

        if (tabString == originalTab) {
            currTab = ul.childNodes[i];
        }
    }
    currTab.id = currentTabCssId;

    var menuContainer = $get(menuContainerId);
    for (var i = 0; i < ul.childNodes.length/*not menuContainer.childNodes.length !!!*/; ++i) {
        if (menuContainer.childNodes[i].attributes["name"].value == originalTab) {
            menuContainer.childNodes[i].className  = "navClass " + menuContainer.childNodes[i].className;
            menuContainer.childNodes[i].style.display = "";
        } else {
            menuContainer.childNodes[i].className  = menuContainer.childNodes[i].className.replace("navClass ", "");
            menuContainer.childNodes[i].style.display = "none";
        }
    }
}

function closeModal() {
    $.modal.close();
}

function notifyFriendsAndReaders(postId, path) {
    disable("BtnNotifyMyFriends", "BtnNotifyMyFriendsDisabled");
    $('' + unescape(processingAlert) + '').modal({ containerCss: { height: '152px', width: '320px', backgroundColor: '#fff' } });
    executeWebRequest("notify_friends_readers.aspx", "POST", "path=" + escape2(path) + "&post_id=" + postId + "&subj=" + articleSubject + "&nick=" + currentUserNickname, notifyFriendsAndReadersCallback);
}

function notifyFriendsAndReadersCallback(executor, eventArgs) {
    $.modal.close();
    $('' + unescape(executor.get_responseData()) + '').modal({ containerCss: { height: '152px', width: '320px', backgroundColor: '#fff'} });
}

function joinNow() {
    $('' + unescape(processingAlert) + '').modal({ containerCss: { height: '152px', width: '320px', backgroundColor: '#fff'} });
    executeWebRequest("/global/join_now.ashx", "POST", "email=" + escape2($get("joinEmailTxt").value), joinNowCallback);
}

function joinNowCallback(executor, eventArgs) {
    $.modal.close();
   // showErrorMessage(executor.get_responseData());
   $(unescape(executor.get_responseData())).modal({ containerCss: { height: '202px', width: '327px', backgroundColor: '#fff' } });
}

function populateNavBar(bar_type, blog_id, grouping_id, is_nugget, url_prefix)
{
    executeWebRequest("/global/build_nav_bar.ashx", "POST", "bar_type=" + bar_type + "&blog_id=" + blog_id +"&grouping_id=" + grouping_id + "&url_prefix=" + url_prefix + "&is_nugget=" + is_nugget, populateNavBarCallback);
}

function closeAnnouncement()
{
    $get("announcement_box").style.display = "none";
    executeWebRequest("/global/close_announcement.ashx", "POST", "");
}

function populateNavBarCallback(executor, eventArgs)
{
    $get("NavBarContainer").innerHTML = executor.get_responseData();
}

function initializeCarousel(imgLeft, imgRight, leftX, leftY, rightX, rightY)
{
    stepcarousel.setup({
	    galleryid: 'mygallery', //id of carousel DIV
	    beltclass: 'belt', //class of inner "belt" DIV containing all the panel DIVs
	    panelclass: 'panel', //class of panel DIVs each holding content
	    autostep: {enable:true, moveby:0, pause:2000000},
	    panelbehavior: {speed:500, wraparound:false, persist:true},
	    defaultbuttons: {enable: true, moveby: 1, leftnav: [imgLeft, leftX, leftY], rightnav: [imgRight, rightX, rightY]},
          tatusvars: ['statusA', 'statusB', 'statusC'], //register 3 variables that contain current panel (start), current panel (last), and total panels
	    contenttype: ['inline'] //content setting ['inline'] or ['external', 'path_to_external_file']
    })
}

function loadBlogsPage(pageNumber) {
    executeWebRequest("/global/get_top_blogs.ashx", "POST", "page_num=" + pageNumber, loadBlogsPageCallback);
}

function loadBlogsPageCallback(executor, eventArgs) {
    replaceDiv(executor.get_responseData());
}
