﻿var changeAdMainUrl = null;

$(function()
{
    //    if ($(".main .all").length > 0) {

    //    //        firstElementSelect();

    //        document.onclick = function(e) {
    //            if (timerId > 0) {
    //                window.clearTimeout(timerId);
    //                timerId = -1;
    //                document.onclick = null;
    //            }
    //        }
    //    }
    if (document.location.hash && document.location.hash.length > 2)
    {
        var id = document.location.hash.substring(2);
        var playerId = document.getElementById(id);
        if (playerId)
            expose('', id);
    }
});

function expose(prefix, id)
{
    var searchId = prefix + id;
    var x = document.getElementById(searchId);

    var player = document.getElementById("player");

    if (player != null)
    {
        var parent = player.parentNode;
        var parentId = parent.attributes.getNamedItem("id").nodeValue;
        if (searchId != parentId)
        {

            // заглушка для IE8
            window.setTimeout("$('#" + parentId + " + .row').css('top', 0);", 0);
            parent.removeChild(player);
        }
        else
            return;
    }

    var y = document.createElement("div");
    y.setAttribute("id", "player");
    //y.style['display'] = 'block';
    y.innerHTML = "<span class='video'>" + getPlayerCodeInline(id) + "</span><span id='Ad280x280' class='ad'></span>";

    x.appendChild(y);
    var frame = document.getElementById("frameAd");
    if (frame != null)
        frame.src = "/ad280x280_3.aspx";

    // заглушка для IE8
    $("#" + searchId + " + .row").css('top', 1);
}

function expose2(prefix, id, sessionHash)
{
    var searchId = prefix + id;
    var x = document.getElementById(searchId);

    var player = document.getElementById("player");

    if (player != null)
    {
        var parent = player.parentNode;
        var parentId = parent.attributes.getNamedItem("id").nodeValue;
        if (searchId != parentId)
        {

            // заглушка для IE8
            window.setTimeout("$('#" + parentId + " + .row').css('top', 0);", 0);
            parent.removeChild(player);
        }
        else
            return;
    }

    var y = document.createElement("div");
    y.setAttribute("id", "player");
    //y.style['display'] = 'block';
    y.innerHTML = "<span class='video'>" + getPlayerCodeInline2(id, sessionHash) + "</span><span id='Ad280x280' class='ad'></span>";

    x.appendChild(y);
    var frame = document.getElementById("frameAd");
    if (frame != null)
        frame.src = "/ad280x280_3.aspx";

    // заглушка для IE8
    $("#" + searchId + " + .row").css('top', 1);
}


function getPlayerCodeInline(guid)
{
    return getPlayerCode("player" + guid, guid, "&amp;autoPlay=true&amp;placement=inline", 400);
}

function getPlayerCode(id, guid, adFlashVars, width)
{
    var code = "/FreshPlayer2.swf"
    var flashvars = "guid=" + guid + "&amp;location=n2" + adFlashVars;
    var url = code + "?" + flashvars;
    var height = width * 3 / 4;

    return "<object id='" + id + "' width='" + width + "' height='" + height + "' type='application/x-shockwave-flash' data='" + url + "'>\
    <param name='movie' value='" + url + "' />\
    <param name='allowfullscreen' value='true' />\
    <param name='wmode' value='opaque' />\
    </object>";
}

function getPlayerCodeInline2(guid, sessionHash)
{
    return getPlayerCode2("player" + guid, guid, sessionHash, "&amp;autoPlay=true&amp;placement=inline", 400);
}

function getPlayerCode2(id, guid, sessionHash, adFlashVars, width)
{
    var code = "/FreshPlayer2.swf"
    var flashvars = "guid=" + guid + "&amp;sessionHash=" + sessionHash + "&amp;location=n2" + adFlashVars;
    var url = code + "?" + flashvars;
    var height = width * 3 / 4;

    return "<object id='" + id + "' width='" + width + "' height='" + height + "' type='application/x-shockwave-flash' data='" + url + "'>\
    <param name='movie' value='" + url + "' />\
    <param name='allowfullscreen' value='true' />\
    <param name='wmode' value='opaque' />\
    </object>";
}



function cal()
{
    var y = document.flashCalendar.get();
    var month = (y.month + 1);
    var date = (y.date + 1);

    window.location = "/chronicle/" + month + "/" + date;
}

function login_show()
{
    __doPostBack('ctl00$UserLogin$BLogin', '');
    //    $('#auth').css("display", "block");
    //    $('#authdiv').css("display", "block");
    //    $('#authdialog').css("display", "block");

    //    document.getElementById('loginInputF').firstChild.focus();

}


function show_auth_form()
{
    login_show();
}

function close_auth()
{
    //    __doPostBack('ctl00$UserLogin', '');
    __doPostBack('Cancel', '');
}

function switchDataRange()
{
    $('#datePick').toggle();
}

function date_switch()
{
    $('#datePick').toggle();
}

function addFavorite(mediaId, onsuccess, onfail)
{
    return NewsTube2.WS.Users.FavoriteAdd(mediaId, onsuccess, onfail);
}


function uploadGetMediaId()
{
    return $("#edit").attr("mediaId");
}

function uploadGetImportState()
{
    return $("#edit").attr("importState");
}


function uploadGetTempKeyFrameId()
{
    var o = $("#ctl00_Content_preview .active");

    //var v = $("#ctl00_Content_preview .active").attr("id");
    return o.length > 0 ? Number(o.attr("id").substring(1)) : 0;
}



function progress()
{
    //alert("progress");

    $(".uploadercancel").css("display", "block");

    $('#useragreement').css("display", "none");
    $('#edit').css("display", "block");
}

function ready(mediaId)
{
    $("#edit").attr("mediaId", mediaId);
    $(".uploadercancel").css("display", "none");

    if (mediaId != '' && mediaId != '00000000-0000-0000-0000-000000000000')
    {
        swfobject.getObjectById("uploader").customize('загружен');

        NewsTube2.WS.Users.MediaNew(mediaId, function()
        {
            waitTranscode();
        });
    } else
    {
        $("#edit").attr("importState", 8);
    }
}

function follow()
{
    var importState = uploadGetImportState();

    switch (importState)
    {
        default:
            if (Page_ClientValidate("Edit"))
            {
                var mediaId = uploadGetMediaId();
                var inputs = $('#edit input:text');
                var name = inputs[0].value;
                var description = $('#edit textarea')[0].value;
                var tags = inputs[1].value;
                var tempKeyFrameId = uploadGetTempKeyFrameId();

                NewsTube2.WS.Users.MediaUpdate(mediaId, name, description, tags, tempKeyFrameId, function()
                {
                    window.location.href = '/myvideo.aspx';
                }
                );
            }
            break;
        case 8:
        case '8':
            uploaderCancel();
            break;
    }
}

function uploaderCancel()
{
    swfobject.getObjectById("uploader").cancel();

    $(".uploadercancel").css("display", "none");

    $('#useragreement').css("display", "block");
    $('#edit').css("display", "none");

    __doPostBack("ctl00_Content_UPPreview", "");
}

function waitTranscode()
{
    var mediaId = uploadGetMediaId();

    NewsTube2.WS.Users.GetImportState(mediaId, checkImportState);
}

function checkImportState(importState)
{
    $("#edit").attr("importState", importState);
    //alert(importState);
    var uploader = swfobject.getObjectById("uploader");
    switch (importState)
    {
        case 1:
            uploader.customize('сохранить ролик');
            waitTranscode()
            break;
        case 10:
            uploader.customize('сохранить ролик');
            waitTranscode()
            break;
        case 3:
        case 5:
            uploader.customize('сохранить ролик');
            showKeyFrames();
            break;
        case 8:
            uploader.customize('ошибка в обработке ролика');
            break;
        case 0:
            uploader.customize('ошибка загрузки файла');
            break;
        default:
            uploader.customize(importState);
            break;
    }

}

function showKeyFrames()
{
    var mediaId = uploadGetMediaId();
    __doPostBack("ctl00_Content_UPPreview", mediaId);

}

function uploadSetKeyFrame(o)
{
    $("#ctl00_Content_preview .active").removeClass("active");
    var li = $(o)
    li.addClass("active");
}

function add280(text)
{
    text = '<div style="border:solid 1px #747474; width:280px; height:280px;vertical-align:bottom;">' + text.replace(/<script[^>]*>[\S\s]*?<\/script[^>]*>/ig, "") + '</div><img src="/images/ad.gif" alt="реклама" class="adimage" width="66" height="11"/>';

    var dest = window.parent.document.getElementById("Ad280x280");
    dest.innerHTML = text;
}

function add400(text)
{
    text = '<div style="border:solid 1px #747474; width:240px; height:400px;">' + text.replace(/<script[^>]*>[\S\s]*?<\/script[^>]*>/ig, "") + '</div>';

    var dest = window.parent.document.getElementById("Ad240x400Main");
    dest.innerHTML = text;
}

function initMedia(id, shootdate, name, description, authorname, authorurl, viewscounter, link)
{
    var i = $("#g" + id);
    i.attr('fid', id);
    i.attr('fshootdate', shootdate);
    i.attr('fname', name);
    i.attr('fdescription', description);
    i.attr('fauthorname', authorname);
    i.attr('fauthorurl', authorurl);
    i.attr('fviewscounter', viewscounter);
    i.attr('factive', false);
    i.attr('flink', link);
}

function showMedia(instance, play)
{
    var id = jQuery.trim(instance.getAttribute("fid"));

    $("#Name").text(instance.getAttribute("fname"));
    $("#ShootDate").text(instance.getAttribute("fshootdate"));

    var authorElement = $("#AuthorLink");
    authorElement.attr("href", instance.getAttribute("fauthorurl"));
    authorElement.text(instance.getAttribute("fauthorname"));

    $("#ViewsCounter").text(instance.getAttribute("fviewscounter"));

    $("#Description").text(instance.getAttribute("fdescription"));
    $("#DetailLink").attr("href", instance.getAttribute("flink"));


    $(".main2 .all .fl a[factive=true] img").removeClass('clipImage');
    $(".main2 .all .fl a[factive=true]").attr("factive", false);

    markActive(instance);

    var player = swfobject.getObjectById("Playerembed");
    if (play)
    {
        player.load(id, play);
        //document.Playerembed.load(id, play);
        if (timerId > 0)
        {
            window.clearTimeout(timerId);
            timerId = -1;
        }

        changeAdMain();

    } else
        player.load(id, play, 10000);
    //document.Playerembed.load(id, play, 10000);

}

var timerId;

function firstElementSelect()
{
    var instance = $(".main2 .all .fl a")[0];

    markActive(instance);

    timerId = window.setTimeout("nextMedia()", 10000);
    swfobject.getObjectById("Playerembed").startTimeout(10000);
}

function markActive(instance)
{
    $("img", instance).addClass('clipImage');
    $(instance).attr("factive", true);
}

function nextMedia()
{
    var items = $(".main2 .all .fl a");
    var current = items.filter("a[factive=true]");
    var next;
    if (current.length == 0)
    {
        next = items[0];
    } else
    {
        var index = items.index(current);
        if (index + 1 == items.length)
            next = items[0];
        else
            next = items[index + 1];
    }

    showMedia(next, false);

    timerId = window.setTimeout("nextMedia()", 10000);
}

function changeAdMain()
{
    var frame = document.getElementById("frameAd");
    if (changeAdMainUrl == null)
        frame.src = "/Ad240x400MainSol.aspx";
    else
        frame.src = changeAdMainUrl;


}

function prerollStarted()
{
    //    var frame = document.getElementById("framePrerollStart");
    //    frame.src = "prerollStart.aspx";
    //
    if (1 != 4)
    {
        var i = new Image();
        i.src = "http://amch.questionmarket.com/adsc/d617183/10/625601/adscout.php?ord=" + Math.floor((new Date()).getTime() / 1000);
    }

}


function playerReady()
{
    if ($(".main2 .all").length > 0)
    {
        firstElementSelect();

        document.onclick = function(e)
        {
            if (timerId > 0)
            {
                window.clearTimeout(timerId);
                timerId = -1;
                document.onclick = null;
            }
        }
    }
}

function playerStart()
{
    if (timerId > 0)
    {
        window.clearTimeout(timerId);
    }
}

Sys.onReady(function()
{
    userauthenticatedUpdate();
});

function setUserAuthenticated(value, sessionHash)
{
    Sys.Services.AuthenticationService._setAuthenticated(value);
    setSessionHash(sessionHash);
    userauthenticatedUpdate();
}

function userauthenticatedUpdate()
{
    if (Sys.Services.AuthenticationService.get_isLoggedIn())
    {
        $(".userauthenticated").css("display", "block");
        $(".userauthenticated").css("visibility", "visible");
    } else
    {
        $(".userauthenticated").css("display", "none");
        $(".userauthenticated").css("visibility", "hidden");
    }
}

var m_sessionHash;

function setSessionHash(sessionHash)
{
    m_sessionHash = sessionHash;
}