﻿/// <reference path="jquery-vsdoc.js" />
/*single category`s navigators moving*/
// need for block adding animation while current animation is not finished
var naviReloaded = false;
function replaceSideNavi(cntrl) {
    if(!replaceSideNavi.d)
        replaceSideNavi.d = $(document);
    if(!replaceSideNavi.w)
        replaceSideNavi.w = $(window);
    if(!replaceSideNavi.b)
        replaceSideNavi.b = $(document.body);
    var d = replaceSideNavi.d;
    var w = replaceSideNavi.w;
    var b = replaceSideNavi.b;
    
    var newPos = w.scrollTop() + (b.height() / 2);
    newPos = newPos < 200 ? 200 : newPos;
    newPos = newPos > (d.height() - 400) ? d.height() - 400 : newPos;
    cntrl.stop().animate({ "top": newPos }, 100);
}

// find navigators, configure them and replace in appropriate position
function getSideNavi() {
    var naviParents = $('.w2px');
    // if there are more than one category
    if (naviParents.size() > 2)
        return null;
    var cntrl = naviParents.find('.btnNextSmall, .btnPrevSmall');
    cntrl.css("position", "absolute");
    replaceSideNavi(cntrl)
    return cntrl;
}
function fitSideNavi() {
    var cntrl = getSideNavi();
    if (!cntrl)
        return;
    // subscribe on scroll
    $(window).scroll(function() {
        if (naviReloaded) {
            cntrl = getSideNavi();
            naviReloaded = false;
        }
        else
            replaceSideNavi(cntrl);
    });

    // subscribe on resize
    $(window).resize(function() {
        if (naviReloaded) {
            cntrl = getSideNavi();
            naviReloaded = false;
        }
        else
            replaceSideNavi(cntrl);
    });
}
/*END single category`s navigators moving*/
/*Message box*/
var msgBoxIndex = 0;
function showMessageBox(message, top, left) {
    if (!message || message == "")
        return;
    var mbId = "jsMsgBox" + (msgBoxIndex++);
    var msgBox = $("#" + mbId + "");
    if (msgBox.size() == 0) {
        var contatinerDiv = document.createElement("div");
        contatinerDiv.innerHTML = "\
        <div id=\"" + mbId + "\" style=\"position:absolute;z-index:1358022759\">\
        <div class=\"ppWindowDark\" style=\"width:210px;height:45px;\" >\
            <!--topline-->\
            <div class=\"ppCornerTLDark\"></div>\
            <div class=\"ppCornerTRDark\"></div>\
            <div class=\"ppTLineDark\"></div>\
            <!--left line-->\
            <div class=\"ppLLineDark\"></div>\
            <!--right line-->\
            <div class=\"ppRLineDark\"></div>\
            <!--background for content-->\
            <div class=\"ppBGContentDark\">\
                <div style=\"padding-right: 10px; padding-left: 10px\">\
                    <span ID=\"" + mbId + "text\" style=\"font-size:8pt; color:#fff; font-family:Arial;\"></span>\
                </div>\
            </div>\
            <!--bottomline-->\
            <div class=\"ppCornerBLDark\"></div>\
            <div class=\"ppCornerBRDark\"></div>\
            <div class=\"ppBLineDark\"></div>\
        </div></div>";
        document.body.appendChild(contatinerDiv);
        msgBox = $("#" + mbId + "");
    }
    $("#" + mbId + "text").text(message);
    if (!top && !left) {
        left = ($(window).width() - 220) / 2;
        top = $(window).scrollTop() + ($(document.body).height() / 2);
    }
    else
        left = ($(window).width() - 220) > left ? left : ($(window).width() - 220);
    msgBox.css({ "top": top, "left": left });
    setTimeout(function() { closeMessageBox(msgBox); }, 2000);
}

function closeMessageBox(msgBox) {
    msgBox.remove();
}
/*END Message Box*/
/*COMMENTS*/
// show popup comments
function showCommentsWindow(url) {
    var commentsWnd = document.getElementById('commentsWrapper');
    if (commentsWnd != null) commentsWnd.style.display = 'block';
    $(commentsWnd).data("curUrl", url);
    storeCommentedUrl(url);
    var cmntPanel = document.getElementById('commentsContainer');
    cmntPanel.innerHTML = "";
    HtmlContent.GetUrlComments(url, onGetCommentsSuccess);
}

function closeCommentsWnd() {
    var commentWnd = $("#commentsWrapper");
    commentWnd.hide();
    commentWnd.find(".captchaText").val("");
    commentWnd.find(".xCmntText").val("");
}

function addUserComment() {
    var commentWnd = $("#commentsWrapper");
    var url = window.globalCmntUrl ? window.globalCmntUrl : commentWnd.data("curUrl");
    var captchaText = commentWnd.find(".captchaText").val();
    var textarea = commentWnd.find(".xCmntText");
    var text = textarea.val();
    // set loader
    commentWnd.find(".xPLH").append(loaderHTML);
    HtmlContent.AddUrlComment(url, captchaText, setTextBreaks(text, textarea.get(0)), onAddComment);
}

function onAddComment(results) {
    var commentWnd = $("#commentsWrapper");
    // remove loader
    commentWnd.find(".pwLoader").remove();
    var captcha = commentWnd.find(".captchaText").val("");
    // is there error
    if (!results[0]) {
        var cmntText = commentWnd.find(".xCmntText").val(" ");
        $(commentWnd.find(".captchaCmnt img").get(0)).attr("src", results[1]);
        onGetCommentsSuccess(results[2]);
        cmntText.focus();
    }
    else {
        // if there is new url for cpatcha - set it
        if (results[1])
            $(commentWnd.find(".captchaCmnt img").get(0)).attr("src", results[1]);
        captcha.focus();
    }
}

function updateCaptcha() {
    HtmlContent.GetUpdatedCaptcha(onCaptchaUpdated);
}
function onCaptchaUpdated(result) {
    $($("#commentsWrapper").find(".captchaCmnt img").get(0)).attr("src", result);
}
/*END COMMENTS*/

/*RATING*/
function rateUrl(sender, url, qType, isIncrease, pwWndSender) {
    if (sender.disabled || sender.className == "rateUpBtnF" || sender.className == "rateDownBtnF")
        return false;
    HtmlContent.RateUrl(url, qType, isIncrease, function(result) { onRateUrl(result, sender, pwWndSender); });
}
// set results of rating for rate burrons( if there is preview Window sender - set result fot it too)
function onRateUrl(result, sender, pwWndSender) {
    var left = $(pwWndSender ? pwWndSender : sender).offset().left;
    var top = $(pwWndSender ? pwWndSender : sender).offset().top;

    // error occured
    if (result[0]) {
    }
    // no error
    else {
        var rateWrp = $(sender).parents(".ratingWrapper");
        findBtnsAndSetRate(rateWrp, result);
        if (pwWndSender) {
            rateWrp = $(pwWndSender).parents(".ratingWrapper");
            findBtnsAndSetRate(rateWrp, result);
        }
    }
    showMessageBox(result[1], top, left)
}

function findBtnsAndSetRate(rateWrp, result) {
    var rateUp = rateWrp.find(".rateUp a").get(0);
    var rateDown = rateWrp.find(".rateDown a").get(0);
    // set rate buttons enabling
    if (result[2] == 0)
        setRateBtnsAvailability(rateUp, rateDown, true, true)
    else if (result[2] == 1)
        setRateBtnsAvailability(rateUp, rateDown, false, true)
    else if (result[2] == -1)
        setRateBtnsAvailability(rateUp, rateDown, true, false)
}

function setRateBtnsAvailability(rateUp, rateDown, isUpEnabled, isDownEnabled) {
    rateUp.className = isUpEnabled ? "rateUpBtn" : "rateUpBtnF";
    rateUp.disabled = isUpEnabled ? false : "disabled";
    rateDown.className = isDownEnabled ? "rateDownBtn" : "rateDownBtnF";
    rateDown.disabled = isDownEnabled ? false : "disabled";
}
/*END RATING*/

function showPreviewVideoWindowHandler(sender, embed, url) {
    if (embed == "")
        embed = '<div style="width:200px;height:40px;font-size:14px;text-align:center;">Source is not found</div>';
    showPreviewVideoWindow(sender, embed, url);
}

function showPreviewImageWindowHandler(sender, url, realUrl, qType) {
    showPreviewImageWindow(sender, url, realUrl, qType);
}
function showRightPreviewVideo(embed) {
    if (embed == "")
        embed = '<div style="width:200px;height:40px;font-size:14px;text-align:center;">Source is not found</div>';
    $(".divRightPreview").html(embed);
}

var indexPreview = 0;

// generate id is depended on parent previewWindow`s id
function getRateUpId(pwId) { return pwId + "ru"; }
function getRateDownId(pwId) { return pwId + "rd"; }

// functions for locking-unlocking functionality of child links of previewWindow  during a dragging
var locksDuringDrag = {};
function lockPwDuringDrag(id) {
    locksDuringDrag[id] = true;
}
function unlockPwDuringDrag(id) {
    locksDuringDrag[id] = false;
}
function isPwLocked(el) {
    return locksDuringDrag[$(el).parents('.ppNFixedWrapper').attr('id')];
}
// set limits of dragging and locking previewWindow
function pwDrag(pwWindow) {
    // lock
    lockPwDuringDrag(pwWindow.attr("id"));
}
function setPwBorder(pwWindow) {
    pwWindow = $(pwWindow);
    var offset = pwWindow.offset();
    var h = pwWindow.height();
    var w = pwWindow.width();
    var leftLimit = document.documentElement.clientWidth ? document.documentElement.clientWidth : window.innerWidth;
    var bottomLimit = (document.documentElement.scrollHeight ? document.documentElement.scrollHeight : window.innerHeight) - 70;
    // if has gone out of left limits then set left position
    if (leftLimit <= (offset.left + w + 10))
        pwWindow.css({ left: (leftLimit - w - 10) });

    if (bottomLimit <= (offset.top + h + 10))
        pwWindow.css({ top: (bottomLimit - h - 10) });

    pwWindow.setBorder({ left: 10, right: leftLimit - 10, top: 0, bottom: bottomLimit });
}
function totalCheckPwPositions() {
    var pwWindows = $('.ppNFixedWrapper');
    pwWindows.each(function(f, e) { setPwBorder(e); });
}

// link opening handlers
//
var openedLinks = {};
function setLinkOpenStatus(link, flag) {
    openedLinks[link] = flag;
}
function isOpenedLink(link) {
    return openedLinks[link] ? true : false;
}

// close preview window
function closePw(el) {
    // if window dragged at this moment - dont close
    if (isPwLocked(el))
        return false;
    var pwWnd = $(el).parents('.ppNFixedWrapper')
    // set link as unopened
    setLinkOpenStatus(pwWnd.data('sourceUrl'), false);
    pwWnd.remove();
    return true;
}

// close all preview windows
function closeAllPw(el) {
    // if window dragged at this moment - dont close
    if (isPwLocked(el))
        return false;
    // set all links as unopened
    $('.ppNFixedWrapper')
    // filter all windows is not yet oppened
        .filter(function() { return $(this).offset().left > 0; })
    // set links as unoppened
        .each(function() { setLinkOpenStatus($(this).data("sourceUrl"), false); })
    // remove all windows
        .remove();
    return true;
}
function stopBubbling(event) {
    if (event.stopPropagation)
        event.stopPropagation();
    else
        window.event.cancelBubble = true;
    return false;
}
// returns id of created preview window
function createPreviewWindow(url, isVideo) {
    var pwId = "x_pw_" + indexPreview++;
    var preview = '<div id="' + pwId + '" class="ppNFixedWrapper" style="width: 545px; height: 420px;" onclick="unlockPwDuringDrag(this.id)" onmousedown="unlockPwDuringDrag(this.id)">\
					<div class="ppWindow">\
                        <div class="ppCornerTL"></div>\
						<div class="ppCornerTR"></div>\
						<div class="ppTLine"></div>\
						<div class="ppLLine"></div>\
						<div class="ppRLine"></div>\
						<div class="ppBGContent"></div>\
						<div class="ppCornerBL"></div>\
						<div class="ppCornerBR"></div>\
						<div class="ppBLine"></div>\
					</div>\
					<div class="ppContent">\
						<div style="position: absolute; height: 20px; margin-right: 10px; margine-bottom: 0px;text-align: right; width: 100%">\
							<table align="right" cellpadding="0" cellspacing="0" border="0"><tr><td>\
									<img src="http://img.lavva.com/closeallbtn.gif" style="float: right;border: none; visibility: visible; font-size: 14px; margin: 4px; padding: 0 0px; cursor:pointer;text-decoration: none;" value="close" class="ppClose" \
										onclick="return closeAllPw(this)" onmousedown="stopBubbling(event)" /></td>\
								<td>\
									<img src="http://img.lavva.com/closebtn.gif" alt="close" class="ppClose" \
										onclick="return closePw(this)" onmousedown="stopBubbling(event)" />\
								</td></tr>\
							</table>\
						</div>\
						<div class="previewWrapper">' +
							((isVideo) ? '<div class="previewVideo" onmousedown="event.stopPropagation ? event.stopPropagation() : (event.cancelBubble = true)">\
										   </div>' :
							'<a class="x_pwLnk" href="#" onclick="if(!isPwLocked(this)) window.open(this.href); return false;">\
								<img alt="&nbsp;" style="display: none;"\
									class="previewImage" tag="previewImage" />\
							</a>') +
						'</div>\
						<div style="position: absolute; height: 20px; bottom: 5px; _bottom:0px; margin-right: 10px; margine-bottom: 0px;text-align: right; width: 100%">\
							<table align="right" cellpadding="0" cellspacing="0" border="0" width="100%"><tr>\
								<td align="right" class="ratingWrapper"><span class="rateUp"><a id="' + getRateUpId(pwId) + '" runat="server" class="rateUpBtn" title="Rate Up"></a></span>\
								<span class="rateLabel"></span>\
								<span class="rateDown"><a id="' + getRateDownId(pwId) + '" runat="server" class="rateDownBtn" title="Rate Down"></a></span>\
							</td></tr>\
							</table>\
						</div>\
					</div>\
				</div>';
    var contatinerDiv = document.createElement("div");
    contatinerDiv.innerHTML = preview;
    document.body.insertBefore(contatinerDiv, document.body.firstChild);
    var pw = $("#" + pwId);
    pw.data("sourceUrl", url);
    // subscribe on dragging
    pw.easydrag();
    pw.ondrag(function() { pwDrag($("#" + pwId)) });
    setPwBorder(pw);
    setLinkOpenStatus(url, true);
    return pwId;
}

function showPreviewImageWindow(sender, url, realUrl, qType) {
    if (isOpenedLink(url))
        return false;

    var pwId = createPreviewWindow(url);
    var previewWnd = $("#" + pwId);
    if (!previewWnd && !previewWnd.size())
        return;

    var img = previewWnd.find(".previewImage");

    if (img != null) {
        img.attr("src", "");
        img.css({ display: 'inline' });

        var link2 = previewWnd.find(".x_pwLnk");
        link2.attr("href", realUrl);

        var rateUp = document.getElementById(getRateUpId(pwId));
        var rateDown = document.getElementById(getRateDownId(pwId));
        // set buttons availibility
        //
        var rateWrpSender = $(sender).parents(".xRes");
        var rateUpSource = rateWrpSender.find(".ratingWrapper .rateUp a").get(0);
        var rateDownSource = rateWrpSender.find(".ratingWrapper .rateDown a").get(0);
        setRateBtnsAvailability(rateUp, rateDown, rateUpSource.className == "rateUpBtn", rateDownSource.className == "rateDownBtn");
        // setup rating button handler on preview
        //
        rateUp.onclick = function() { voteUpUrl(rateUpSource, rateUp, realUrl, qType); };
        rateDown.onclick = function() { voteDownUrl(rateDownSource, rateDown, realUrl, qType); };

        animatePreview(sender, previewWnd, false);
        img.attr("src", url);
    }
}
function showPreviewVideoWindow(sender, embed, url) {
    if (isOpenedLink(url))
        return false;

    var pwId = createPreviewWindow(url, true);
    var previewWnd = $("#" + pwId);
    if (!previewWnd && !previewWnd.size())
        return;

    var divVideo = previewWnd.find(".previewVideo");
    divVideo.append(embed);
    animatePreview(sender, previewWnd, true);

    var rateUp = document.getElementById(getRateUpId(pwId));
    var rateDown = document.getElementById(getRateDownId(pwId));
    // set buttons availibility
    //
    var rateWrpSender = $(sender).parents(".xRes");
    var rateUpSource = rateWrpSender.find(".ratingWrapper .rateUp a").get(0);
    var rateDownSource = rateWrpSender.find(".ratingWrapper .rateDown a").get(0);
    if (rateUpSource != undefined) {
    	setRateBtnsAvailability(rateUp, rateDown, rateUpSource.className == "rateUpBtn", rateDownSource.className == "rateDownBtn");
    	// setup rating button handler on preview
    	//
    	rateUp.onclick = function() { voteUpUrl(rateUpSource, rateUp, url, 'videos'); };
    	rateDown.onclick = function() { voteDownUrl(rateDownSource, rateDown, url, 'videos'); };
    }
}

function voteUpUrl(sourceSender, pwWindowSender, url, qType) {
    rateUrl(sourceSender, url, qType, true, pwWindowSender);
}
function voteDownUrl(sourceSender, pwWindowSender, url, qType) {
    rateUrl(sourceSender, url, qType, false, pwWindowSender);
}

function createXMLHttp() {
    if (typeof XMLHttpRequest != "undefined") { // для браузеров аля Mozilla
        return new XMLHttpRequest();
    } else if (window.ActiveXObject) { // для Internet Explorer (all versions)
        var aVersions = ["MSXML2.XMLHttp.5.0", "MSXML2.XMLHttp.4.0",
                   "MSXML2.XMLHttp.3.0", "MSXML2.XMLHttp",
                   "Microsoft.XMLHttp"
                   ];
        for (var i = 0; i < aVersions.length; i++) {
            try { //
                var oXmlHttp = new ActiveXObject(aVersions[i]);
                return oXmlHttp;
            } catch (oError) {
            }
        }
        //throw new Error("Невозможно создать объект XMLHttp.");
    }
}