﻿function ActivateImageFlow() {
    var onClickFunc = function(id) {
        $.nyroModalManual({
            url: 'Хоум/GetGuestDetails?guestId=' + id,
            width: 830, height: 450,
            endFillContent: function() { GuestLoaded(); }
        });
    };

    var instanceOne = new ImageFlow();
    instanceOne.init({
        ImageFlowID: 'guestsImageFlow',
        reflections: true,
        aspectRatio: 6,
        percentLandscape: 47,
        xStep: 70,
        imageFocusMax: 7,
        captions: true,
        startID: 7,
        reflectPath: 'Content/ImageFlow/',
        //imagePath: '.',
        onFirstClick: onClickFunc,
        onClick: onClickFunc,
        imageCursor: 'pointer',
        reflectionGET: '&bgc=e7836a',
        //reflectionP: 0.4,
        reflectionPNG: true,
        slider: false,
        circular: true,
        loadintTitle: 'Погрузка лиц... '
    });
}

function InitArchiveImageFlow() {

    var onclickFunc = function(id) {
        LoadArchiveItemDetails(id);
    };

    var instanceTwo = new ImageFlow();
    instanceTwo.init({
        ImageFlowID: 'archiveImageFlow',
        reflections: true,
        xStep: 100,
        aspectRatio: 3,
        percentLandscape: 75,
        imageFocusMax: 8,
        captions: true,
        startID: 8,
        reflectPath: 'Content/ImageFlow/',
        imagePath: '../..',
        onClick: onclickFunc,
        onFirstClick: onclickFunc,
        imageCursor: 'pointer',
        //reflectionGET: '&bgc=e7836a',
        //reflectionP: 0.3,
        reflectionPNG: true,
        slider: false,
        onLoad: function() {
            $("#ArchiveDetailsBlock").fadeIn('medium', function() {
                LoadFirstFrameDetails();
            });
        },
        loadintTitle: 'Погрузка бульбоксов... '
    });
}

var IsArchiveLoaded, IsArchiveBlockOpened;


function OnSurveyClick() {
    $('#TvImage').fadeOut('slow');
}

function ShowSurvey() {
    var zoomImage = $(QuestionBox).children('#ZoomImage');
    zoomImage.before('<img id="loader" style="position:absolute; margin:220px 0 0 240px;display:none" src="/Content/Images/loader.gif"/>');
    $('#loader').fadeIn('fast');
    $.get('/Хоум/GetCurrentSurvey', function(data) {
        $('#loader').fadeOut('fast');
        zoomImage.before(data);
    }, 'html');
}

function Vote(element) {
    var elementData = $('.QuestionBlock').serializeAnything();
    if (elementData.length > elementData.indexOf('=') + 1) {
        $('#loader').fadeIn();
        $('.QuestionBlock').fadeOut();

        $.post('/Хоум/Vote', elementData, function(data) {
            $('#loader').fadeOut('fast');
            $('.QuestionBlock').replaceWith(data);
        }, 'html');
    }
}

function EndVote(element) {
    zoomOut(element);
    $.unblockUI();
    $('#loader').remove();
    $('#TvImage').fadeIn('slow');
}

function GuestLoaded() {
    $('#guestImages a').fancyZoom({
        scaleImg: true,
        closeOnClick: true,
        directory: 'Content/FancyZoom'
    });
}

function ShowArchive() {
    IsArchiveLoaded = false;
    IsArchiveBlockOpened = false;
    try {
        HideAllForArchive();
    }
    catch (ex) {
        alert(ex);
    }

    $.get('/Хоум/Archive', function(data) {
        $('#ArchiveBlockContent').html(data);
        IsArchiveLoaded = true;
        if (IsArchiveBlockOpened) {
            ShowArchiveContent();
        }
    })
}

function HideAllForArchive() {
    $('#voteBand, #cadillak').fadeOut();
    $('#GuestsBlock').fadeOut('medium', function() {
        $('#TVBlock').animate({
            marginTop: "-240px"
        }, 'slow', function() {
            $('#ArchiveBlockContent').animate({
                width: "1280px"
            }, 'slow');
        });
        $('#links_block,').fadeOut('slow');
        $('#TVBlock').animate({
            marginLeft: "-520px"
        }, 'slow', function() {
            IsArchiveBlockOpened = true;
            if (IsArchiveLoaded) {
                ShowArchiveContent();
            };
        });
    });
}

function ShowArchiveContent() {
    $('#archive_content').fadeIn('fast');
    InitArchiveImageFlow();
}

function HideArchive() {
    $('.archive_item_desc').fadeOut('fast', function() {
        $(".potato_right").animate({
            marginLeft: "-80px"
        }, 'medium', function() {
            $('.archive_details').fadeOut('fast', function() {
                $('#ArchiveBlockContent').animate({
                    width: "0px"
                }, 'slow', function() {

                    $('#links_block').fadeIn('slow');
                    $('#ArchiveBlockContent').html('');
                });
                $('#TVBlock').animate({
                    marginLeft: "0px"
                }, 'slow');

                PlayArchiveItem('/Content/Video/video.flv', '/Content/Video/title.jpg');

                $('#TVBlock').animate({
                    marginTop: "0px"
                }, 'slow', function() {
                    $('#GuestsBlock, #voteBand, #cadillak').fadeIn('medium');
                });
            });
        });
    });
}

// This function returns the appropriate reference, 
// depending on the browser.
function getFlexApp(appName) {
    if (navigator.appName.indexOf("Microsoft") != -1) {
        return window[appName];
    }
    else {
        return document[appName];
    }
}

function PlayArchiveItem(path, imagePath) {
    getFlexApp("BPlayer").setNewVideo(path, imagePath);
}

function LoadFirstFrameDetails() {
    $.get('/Хоум/GetCurrentArchiveItem', function(data) {
        setTimeout(function() {
            ShowArchiveItemDescription(data);
        }, 0);
    }, 'html');
}

function LoadArchiveItemDetails(itemId) {
    $('.archive_item_desc').fadeOut('fast', function() {
        $('.archive_item_desc').html('');
        $(".potato_right").animate({
            marginLeft: "-80px"
        }, 'slow', function() {

            $.ajax({
                type: 'GET',
                dataType: 'json',
                url: '/Хоум/GetArchiveItemDetails?archiveItemId=' + itemId,
                success: function(response) {
                    PlayArchiveItem(response.videoPath, response.imgPath);
                    ShowArchiveItemDescription(response.view);
                }
            });
        });
    });
}

function ShowArchiveItemDescription(data) {
    $(".potato_right").animate({
        marginLeft: "300px"
    }, 'slow', function() {
        $('.archive_item_desc').html(data);
        $('.archive_item_desc').fadeIn('fast');
    });
}

function GetVideoCode(trackId) {
    var code = '<iframe src="http://bulbox.tv/Video/VideoFrame/' + trackId + '" width="561" height="384" frameborder="0"></iframe>'
    $('#VideoFrameCodeTxt').val(code);
    $('#VideoCodeDialog').dialog('open');
}

function SaveTicket() {

    var name = $('#TicketName').val();
    var surname = $('#TicketSurname').val();
    var mail = $('#TicketEmail').val();

    if (name == '' || surname == '' || mail == '') {
        alert('Пожалуйста, для регистрации билета введите Имя, Фамиилию и контактный e-mail (на него будет выслано напоминание о фестивале)')
    }
    else {
        $('#ticketPositioning').fadeOut('medium', function() {
            $('#TicketContainer').append('<img id="FestDetailsLoader" src="/Content/Images/loader.gif" style="display:none; margin:135px 0 0 245px" />');
            $('#FestDetailsLoader').fadeIn('fast');
            SaveTicket2();
        })
    }
}

function SetAjaxEncoding() {
    $.ajaxSetup({ contentType: "application/x-www-form-urlencoded; charset=utf-8" });
}

function SaveTicket2() {
    var elementData = $('#ticketPositioning').serializeAnything();

    SetAjaxEncoding();

    $.post('/Fest/SaveTicket', elementData, function(data) {
        if (data.limit) {
            $('#FestDetailsLoader').remove();
            $('#ticketPositioning').fadeIn('medium', function() {
                alert('К сожалению мы не можем сохранить Ваш билет. Достигнут допустимый предел выделенных билетов.');
            });
        }
        else if (data.ticketExists) {
            $('#ticketPositioning').fadeIn('medium', function() {
                alert('На введенные Вами Имя и Фамилию уже зарегистрирован билет. К сожалению мы не можем позволить Вам повторной регистрации, т.к. клоны в нашей стране запрещены :)');
            });
            $('#FestDetailsLoader').remove();
        }
        else {
            $.get('/Fest/GetConpleteTicket/' + data.number, function(ticket) {
                $('#TicketContainer').html(ticket);
                $('#TicketContainer').fadeIn();
                if (data.mailFailed) {
                    alert('К сожалению, по не зависящим от нас причинам, нам не удалось отправить Вам напоминание по введенному e-mail адресу.. :(. Но, тем не менее, билет был зарегистрирован. Уповаем на Вашу память!');
                }
                else {

                }
            });
        }
    }, 'json');
}

function AnimateCadillak() {
    $('#cadillak').css("left", "-400px");
}

var FestDetailsLoaded;
var ReadyToShowFestDetails;
var FestDetailsContent;

function ShowFestDetails(detailsContainer, detailsUrl) {
    FestDetailsLoaded = false;
    ReadyToShowFestDetails = false;

    $('#MainContent').html(detailsContainer);

    $.get(detailsUrl, function(data) {
        FestDetailsLoaded = true;
        FestDetailsContent = data;

        if (ReadyToShowFestDetails) {
            InsertFestDetails(data);
        }
    }, "html");

    $('#FestDetailsContainer, #FestDetailsContainerFoot, #FestDetailsContainerHead, #CloseFestDetailsBtn').fadeIn('fast');
    $('#FestDetailsContainer').animate({
        height: "680px"
    }, 'slow', function() {
        ReadyToShowFestDetails = true;
        if (FestDetailsLoaded) {
            InsertFestDetails(FestDetailsContent);
        }
    });
}



function InsertFestDetails(data) {
    $('#FestDetailsContainer').append(data);
    $('#FestDetailsContent').fadeIn('slow');
}

function CloseFestDetails() {
    var festDetails = $('#FestDetailsContent');
    var contentBlockId = '#FestDetailsContent';
    if (festDetails.length == 0) {
        contentBlockId = '#BandsBlock'
    }
    $(contentBlockId).fadeOut('slow', function() {
        $('#CloseFestDetailsBtn').fadeOut('fast');
        $('#FestDetailsContainer').animate({
            height: "0px"
        }, 'slow', function() {
            $('#FestDetailsContainer, #FestDetailsContainerFoot, #FestDetailsContainerHead').fadeOut('fast');
            $('#cadillak, #voteBand').fadeIn();

            $.get('Хоум/GetMainContent', function(data) {
                $('#MainContent').html(data);
                LoadMainContent(false);
                $('#GuestsBlock').fadeIn();
            }, 'html');
        });
    });
}

function LoadMainContent(isFirstTime) {
    setupZoom();

    $("#TvImageRef").click(function(event) {
        event.preventDefault()
    });
    setTimeout(function() {
        $(".TV").fadeIn("slow");
    }, isFirstTime ? 1000 : 0);
    setTimeout(function() {
        if (isFirstTime)
        { ActivateImageFlow() };
    }, 1500);
    setTimeout(function() {
        $(".Player").fadeIn("slow");
    }, isFirstTime ? 2000 : 0);
}

function CheckTicket(id, checked) {
    $.post('/Fest/CheckTicket/' + id, { Checked: checked }, function(data) {
        $('#PayedLabel').html(data);
    }, 'html');
}

function VoteBand() {
    var data = $('#BandsBlock').serializeAnything();
    $('#FestDetailsLoader').fadeIn();
    $('#BandsBlock').fadeOut("medium", function() {
        $('#FestDetailsContent').remove();
    });
    $.post('/Fest/VoteBand', data,
        function(data) {
            $('#FestDetailsLoader').fadeOut(function() {
                $('#FestDetailsContainer').append(data);
            });
        }, 'html'
    )
}

function LoadBands() {
    $('#FestDetailsLoader').fadeIn();
    $('#FestDetailsContent').fadeOut('medium', function() {
        $('#FestDetailsContent').replaceWith("");
    });
    $.get('/Fest/GetBandsView', function(view) {
        $('#FestDetailsLoader').fadeOut(function() {
            $('#FestDetailsContainer').append(view);
        });
    }, 'html');
    return false;
}

function OnCadillakClick() {
    LoadFestDetailsConntainer("/Fest/GetFestDetails");
}

function OnVoteBandsClick() {
    LoadFestDetailsConntainer("/Fest/GetBandsView");
}

function LoadFestDetailsConntainer(contentUrl) {
    $.get('/Fest/GetFestDetailsContainer', function(data) {
        $('#voteBand').fadeOut();
        $('#cadillak').fadeOut("medium", function() {
            ShowFestDetails(data, contentUrl);
        });
        $('#GuestsBlock, #HomeViewContainer').fadeOut();
    });
}

