var documentLoadListenerFunctions = new Array();
var documentUnloadListenerFunctions = new Array();

function addCookie(name,value,days) {
    var expires;
    if (days) {
        var date = new Date();
        date.setTime(date.getTime()+(days*24*60*60*1000));
        expires = "; expires="+date.toGMTString();
    }
    else 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 eraseCookie(name) {
    addCookie(name,"",-1);
}

function addDocumentLoadListenerFunction(fn) {
    documentLoadListenerFunctions.push(fn);
}

function documentLoadListener() {
    for (var i = 0; i < documentLoadListenerFunctions.length; i++) {
         eval(documentLoadListenerFunctions[i]);
    }
}

function addDocumentUnloadListenerFunction(fn) {
    documentUnloadListenerFunctions.push(fn);
}

function documentUnloadListener() {
    for (var i = 0; i < documentUnloadListenerFunctions.length; i++) {
        eval(documentUnloadListenerFunctions[i]);
    }
}

function hide(elementId) {
    if (document.getElementById(elementId)!=null)
    {
        document.getElementById(elementId).style.display = "none";
    }
}

function hideElt(element) {
    if (element != null) {
        element.style.display = "none";
    }
}

function showBlock(elementId) {
    if (document.getElementById(elementId)!=null)
    {
        document.getElementById(elementId).style.display = "block";
    }
}

function showInline(elementId) {
    if (document.getElementById(elementId)!=null)
    {
        document.getElementById(elementId).style.display = "inline";
    }
}


function toggleHideShowReturnStatus(elementId) {
   if(document.getElementById(elementId).style.display == "none") {
     document.getElementById(elementId).style.display = "block";
     return true;
   }
   else {
     document.getElementById(elementId).style.display = "none";
     return false;
   }
}

function toggleHideShow(elementId) {
    toggleHideShowReturnStatus(elementId);
}

function toggleHideShowInlineReturnStatus(elementId) {
   if(document.getElementById(elementId).style.display == "none") {
     document.getElementById(elementId).style.display = "inline";
     return true;
   }
   else {
     document.getElementById(elementId).style.display = "none";
     return false;
   }
}

function toggleHideShowInline(elementId) {
    toggleHideShowInlineReturnStatus(elementId);
}

function toggleHideShowWithCtlReturnStatus(elementId, ctlPrefix) {
   var isShown = toggleHideShowReturnStatus(elementId);
   toggleHideShow(ctlPrefix + "-hide");
   toggleHideShow(ctlPrefix + "-show");
   return isShown;
}

function toggleHideShowWithCtl(elementId, ctlPrefix) {
    toggleHideShowWithCtlReturnStatus(elementId, ctlPrefix);
}

function toggleHideShowWithCtlInlineReturnStatus(elementId, ctlPrefix) {
   var isShown = toggleHideShowReturnStatus(elementId);
   toggleHideShowInline(ctlPrefix + "-hide");
   toggleHideShowInline(ctlPrefix + "-show");
   return isShown;
}

function toggleHideShowWithCtlInline(elementId, ctlPrefix) {
    toggleHideShowWithCtlInlineReturnStatus(elementId, ctlPrefix);
}

function nowEnteringText(element) {
    element.innerHTML = "";
    element.setAttribute("value","");
    element.setAttribute("class","enteringText");
}

function setRelatedTagStyle(style) {
    document.getElementById("related_tags").className = style;
}

function isTextAreaBlankById(textAreaId, alertMsg) {
    var result = false;
    var trimmedString = trim(document.getElementById(textAreaId).value);
    if (trimmedString.length < 1) {
        if (alertMsg != undefined) {
            alert(alertMsg);
        }
        result = true;
    }
    return result;
}

function formatDateAshhmma(oDate) {
    var hr = oDate.getHours();
    var hrToShow = '';
    var ampm = '';
    if (hr == 0) {
      hrToShow = 12;
      ampm = 'am';
    }
    else if (hr < 12) {
      hrToShow = hr;
      ampm = 'am';
    }
    else if (hr == 12) {
      hrToShow = hr;
      ampm = 'pm';
    }
    else if (hr > 12) {
      hrToShow = hr - 12;
      ampm = 'pm';
    }
    var mm = oDate.getMinutes();
    var mmToShow = '';
    if (mm < 10) {
      mmToShow = '0' + mm;
    }
    else {
      mmToShow = mm;
    }
    return hrToShow + ":" + mmToShow + ampm;
}

function isUserLoggedIn() {
    return (document.cookie.indexOf('a002_askville') != -1);
}

function updateBackToListCookie(listLocation) {
    addCookie('a012_askville', escape(listLocation), 3);
}

// the curUrl param should have been url-escaped. if that is not the case, the caller should proactively escape it
function signIn(curUrl, avctx, newbieToWelcomePage) {
    if(!document.cookie) {
        alert("Sorry but you don't seem to have cookies enabled for your web browser. Without cookies, you will not be able to sign in to Askville.");
        return;
    }

    var controller = "/SignIn.do";

    if (!avctx) {
        avctx = 'default';
    }
    else if (avctx.match('signup') || avctx.match('signInOptIn1') || avctx.match('signInOptIn-ad1')) {
        controller = "/SignUpStart.do";
    }

    if (curUrl == undefined) {
        curUrl = "";
    }
    else {
        var extraParamInCurUrl = '';

        // %3F is the url-encoded form of question mark, in case the curUrl is url-encoded
        if (curUrl.indexOf('?') > 0 || curUrl.indexOf('%3F') > 0 || curUrl.indexOf('%3f') > 0) {
            extraParamInCurUrl += '&';
        }
        else {
            extraParamInCurUrl += '?';
        }
        extraParamInCurUrl += 'msgcode=sirc.retstat&signin=true' + window.location.hash;
        if (newbieToWelcomePage) {
            extraParamInCurUrl += '&getStarted=true';
        }
        // curUrl should have been url-encoded, so we need to encode the extra param added here
        curUrl = curUrl + escape(extraParamInCurUrl);
    }
    window.location.href = controller + '?avctx=signin.' + avctx + '&action=' + curUrl;
}

function updateBackToListSpan(spanId, linkURL, linkText) {
    var backToList = linkURL ? linkURL : readCookie('a012_askville');
    if (backToList != null && backToList != '') {
        document.getElementById(spanId).innerHTML='<a onmouseover=\"if(document.getElementById(\'backImgId-' + spanId + '\') == null)return false;document.getElementById(\'backImgId-' + spanId + '\').src=\'http://g-ecx.images-amazon.com/images/G/01/askville/icons/arrow-left-hover-v0001.gif\'\" onmouseout=\"if(document.getElementById(\'backImgId-' + spanId + '\') == null)return false;document.getElementById(\'backImgId-' + spanId + '\').src=\'http://g-ecx.images-amazon.com/images/G/01/askville/icons/arrow-left-v0001.gif\'\" href=\"' +
        unescape(backToList) +
        '\"><img id="backImgId-' + spanId +'" src=\"http://g-ecx.images-amazon.com/images/G/01/askville/icons/arrow-left-v0001.gif\" alt=\"back\" style=\"position:relative;top:4px;\" />' + (linkText ? linkText : ' back to question list') + '</a>&nbsp;';
        return true;
    }
    else {
        return false;
    }
}

function setCaretPos(obj, pos) {
    if(obj.createTextRange) {
        /* Create a TextRange, set the internal pointer to
           a specified position and show the cursor at this
           position
        */
        var range = obj.createTextRange();
        range.move("character", pos);
        range.select();
    } else if(obj.selectionStart) {
        /* Gecko is a little bit shorter on that. Simply
           focus the element and set the selection to a
           specified position
        */
        obj.focus();
        obj.setSelectionRange(pos, pos);
    }
}

function isNavigationKey(e) {
    var evt = e || window.event;
    var keynum = evt.keyCode;

    switch (keynum) {
        case 33:
        case 34:
        case 35:
        case 36:
        case 37:
        case 38:
        case 39:
        case 40:
        case 188:

            return true;
        default:
            return false;
    }
}

function trim(str) {
    return str.replace(/^\s+|\s+$/g, '');
}


function showAlphaLabFeedbackWindow() {
    var win = new Window('feedback_win_' + Math.random(), {className: "askv_cube", title: "Alpha Lab Feedback", width:480, height:350, minimizable: false, maximizable: false, resizable: true, url: "/AlphaLabFeedbackPopup.do", hideEffectOptions: {duration:0.5}, showEffectOptions: {duration:0.5}});
    win.setDestroyOnClose();
    win.toFront();
    win.showCenter(true);
}

function getDateStringToMinute(mins) {
    var cd = new Date();
    var minBlock = Math.floor(cd.getMinutes() / mins);
    return cd.getFullYear() + '-' + cd.getMonth() + '-' + cd.getDate() + '-' + cd.getHours() + '-' + minBlock;
}


var cur_user_message_div_id;
function renderCommonMessageForm(div_id, recipientId, subject, submitJs, inputWidth, disableSpellCheck, curUrl, noCancel, toNickname) {
    if (document.getElementById(cur_user_message_div_id)) {
        hide(cur_user_message_div_id);
    }
    cur_user_message_div_id = div_id;

    var url= '/ajax/SubmitUserMessage.do';
    var pars = 'userId='+recipientId;

    if (subject) {
        pars = pars + '&subject=' + subject;
    }

    if (submitJs) {
        pars = pars + '&submitJs=' + submitJs;
    }

    if (inputWidth) {
        pars = pars + '&inputWidth=' + inputWidth;
    }

    if (disableSpellCheck) {
        pars = pars + '&disableSpellCheck=' + disableSpellCheck;
    }

	if (curUrl) {
		pars = pars + '&cururl=' + curUrl;		
	}
	
	if (noCancel) {
		pars = pars + '&noCancel=' + noCancel;		
	}

	if (toNickname) {
		pars = pars + '&toNickname=' + toNickname;
	}

    ajaxUpdateDiv(url, pars, 'get', div_id);
    showBlock(div_id);
}

function userMessageFormSubmit(formId) {
    ajaxFormSubmit(formId, '/ajax/SubmitUserMessage.do', cur_user_message_div_id);
}

function pageXY(el) {
    var XY={x:0, y:0};
    for (var node = el; node; node=node.offsetParent) {
        XY.x += node.offsetLeft;
        XY.y += node.offsetTop;
    }
    return XY;
}

function windowHeight() {
    var myHeight = 0;
    if (typeof(window.innerHeight) == 'number') {
        //Non-IE
        myHeight = window.innerHeight;
    }
    else if (document.documentElement && document.documentElement.clientHeight) {
        //IE 6+ in 'standards compliant mode'
        myHeight = document.documentElement.clientHeight;
    }
    else if (document.body && document.body.clientHeight) {
        //IE 4 compatible
        myHeight = document.body.clientHeight;
    }
    return myHeight;
}

function escapeHtmlBrackets(input) {
    input = input.replace(/</g,"&lt;");
    input = input.replace(/>/g,"&gt;");
    return input;
}

function scrollToDiv(id) {
    var scrollDiv = document.getElementById(id);

    /* cannot set href to named anchor in ajaxed content
       this is the workaround (scrollIntoView is IE and FF2.0 only)
    */
    if (scrollDiv.scrollIntoView) {
        scrollDiv.scrollIntoView(false); // false puts element at bottom of view
    }
    else {
        // my own version of scrollintoview
        var XY = pageXY(scrollDiv);
        var scrollY = XY.y;
        if (scrollY > windowHeight()) {
            scrollY -= windowHeight();
        }
        window.scrollTo(0, scrollY);
    }
}

function watchQuestion(requestId, resultDivId, progressDivId) {
    if (isUserLoggedIn()) {
        var url = "/ajax/QuestionWatchList.do";
        var pars = "action=modify&requestId=" + requestId + "&status=STATUS_WATCHED";
        ajaxLoad(url, pars, 'post', resultDivId, progressDivId);
    }
    else {
        alert('Please sign-in before watching questions');
    }
}

/**
    helpMsgId should be recognized by the controller.
 **/
function showHelpPopupWindow(helpMsgId, w, h) {
    var helpUrl = "/HelpPopup.do?helpMsgId=" + helpMsgId;

    /* Default width and height. */
    if (typeof w == 'undefined') {
        w = 480;
    }
    if (typeof h == 'undefined') {
        h = 350;
    }

    var win = new Window(
        'help_win_' + Math.random(),
        {
            className: "askv_cube",
            title: "Askville Help",
            width:w,
            height:h,
            minimizable: false,
            maximizable: false,
            resizable: true,
            url: helpUrl,
            hideEffectOptions: {
                duration:0.5
            },
            showEffectOptions: {
                duration:0.5
            }
        }
    );
    win.setDestroyOnClose();
    win.toFront();
    win.showCenter(true);
}

var submitcommentonce = false
function checkCommentSubmit() {
    if (!submitcommentonce) {
        submitcommentonce=true;
        return true
    }
    else {
        return false;
    }
}

function addSearchProvider() {
    if (window.external && window.external.AddSearchProvider) {
        window.external.AddSearchProvider('http://askville.amazon.com/opensearch.xml');
    }
    else {
        alert('Sorry, your browser does not support search providers.');
    }
}

function showMainTopicsWindow() {
    var commentUrl = '/MainTopicsWindow.do';
    var win = new Window('main_topic_win_' + Math.random(), {className: "askv_cube", title: 'Popular Topics on Askville', width:300, height:360, minimizable: false, maximizable: false, resizable: true, url: commentUrl, hideEffectOptions: {duration:0.5}, showEffectOptions: {duration:0.5}});
    win.setDestroyOnClose();
    win.showCenter(true);
    win.toFront();
}


function showReportAbuseForm(id, type, curUrl) {
    var pars = 'id=' + id + '&type=' + type + '&curUrl=' + escape(curUrl);
    ajaxLoad('/ajax/ReportAbuseForm.do', pars, 'get', 'report_abuse_div_' + type + '_' + id, 'report_abuse_progress_' + type + '_' + id);
}

function voteForRemoval(requestId) {
    var result = confirm("If enough people vote to remove this question it will not be shown in the bonus box.\n\nAre you sure you want to do this?");
    if (result) {
        var url = "/ajax/NegativeQuestionVote.do";
        var pars = "requestId=" + requestId;
        ajaxLoad(url, pars, 'post', 'bonus_question_link_div_' + requestId, 'vote_for_removal_progress_' + requestId, null, afterRemoval)
    }
}

function afterRemoval() {
    hide('answer_bonus_div');
}


function expandBox(boxName) {
    hide(boxName + "_expand");
    showBlock(boxName + "_collapse");
    showBlock(boxName + "_content");
}

function collapseBox(boxName) {
    hide(boxName + "_content");
    hide(boxName + "_collapse");
    showBlock(boxName + "_expand");
}

function expandBoxPersist(boxName) {
    expandBox(boxName);
    ajaxFireAndForget('/ajax/SetUserPref.do', 'p=' + boxName + '&on=true', 'get')
}

function collapseBoxPersist(boxName) {
    collapseBox(boxName);
    ajaxFireAndForget('/ajax/SetUserPref.do', 'p=' + boxName + '&on=false', 'get')
}

function updateTextAreaHeight(ta, min, offset) {
    if (ta.scrollHeight > (min - offset)) {
        if (navigator.appVersion.match(/MSIE/) != "MSIE") {
            ta.style.height = 0;
        }
        ta.style.height = (ta.scrollHeight + offset) + "px";
    }
}

function handleEnter(field, event) {
    var keyCode = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode;
    return keyCode != 13;
}

function addToFriends(userId, contentIdPrefix) {
    var url= '/ajax/AskToBeFriend.do';
    var pars = 'targetUserId=' + userId + '&uniqueContentId=' + contentIdPrefix;
    ajaxLoad(url, pars, 'get', contentIdPrefix + '_community_action_result', contentIdPrefix + '_community_action_wait');
}

function friendRequestFormSubmit(formId, contentIdPrefix) {
    hide(contentIdPrefix + '_friend_request_form');
    ajaxFormSubmit(formId, '/ajax/AskToBeFriend.do', contentIdPrefix + '_community_action_result', contentIdPrefix + '_community_action_wait');
}

function friendRequestFormCancel(contentIdPrefix) {
    hide(contentIdPrefix + '_community_action_result');
}

function addToFaves(userId, contentIdPrefix) {
    var url= '/ajax/CommunityAction.do';
    var pars = 'targetUserId='+userId + '&action=addAsFave';
    ajaxLoad(url, pars, 'get', contentIdPrefix + '_community_action_result', contentIdPrefix + '_community_action_wait');
}


var showingProfileCard = null;

function showProfileCard(cardId, userId, noCacheAwards) {
    if (showingProfileCard) {
        hide(showingProfileCard);
    }
    showBlock(cardId);

    if (noCacheAwards || document.getElementById(cardId + '_award_result').innerHTML == '') {
        var pars = 'userId=' + userId;
        if (noCacheAwards) {
            pars += '&skipCache=' + noCacheAwards;
        }
        ajaxLoad('/ajax/TopAwards.do', pars, 'get', cardId + '_award_result', cardId + '_award_prog', null, function() { $j('#' + cardId + '_award_result .bubble_tip[title]').qtip({ style: { background: '#F9F6E8', color: 'black', tip: false, border: { color: '#C40', width: 1, radius: 1 } }, position: { corner: { target: 'topMiddle', tooltip: 'bottomLeft'} } } ); } );
    }
    showingProfileCard = cardId;
}

function hideProfileCard(cardId) {
    hide(cardId);
    showingProfileCard = null;
}

function hideProfileCardOnBlur(e) {
    if (showingProfileCard) {
        var card = document.getElementById(showingProfileCard);
        var target = e ? e.target : event.srcElement;
        if (target != card && target.className.indexOf('card_link') == -1 && target.className != 'no_card_blur') {
            hideProfileCard(showingProfileCard);
        }
    }
}

document.onclick=hideProfileCardOnBlur;

function privateMessagePopup(userId, nickname) {
    var helpUrl = "/PrivateMessagePopup.do?userId=" + userId + '&toNickname=' + nickname;

    var w = 480;
    var h = 350;

    var win = new Window(
        'email_win_' + Math.random(),
        {
            className: "askv_cube",
            title: "Private message for " + nickname,
            width:w,
            height:h,
            minimizable: false,
            maximizable: false,
            resizable: true,
            url: helpUrl,
            hideEffectOptions: {
                duration:0.5
            },
            showEffectOptions: {
                duration:0.5
            }
        }
    );
    win.setDestroyOnClose();
    win.toFront();
    win.showCenter(true);
}

function dismissNotification(notificationId, optionalURL) {
    var callback = null;
    if (optionalURL) {
        callback = function() { window.location = optionalURL; };
    }
    $j('#notifySlider').hide("drop", { direction: "up" }, 1000);
    ajaxLoad('/ajax/DismissNotification.do', 'notificationId='+notificationId, 'get', null, null, null, callback);
}

function swalowEvent(e) {
	if (!e) var e = window.event;
	e.cancelBubble = true;
	if (e.stopPropagation) e.stopPropagation();
}