var playerActive = false;

function log(msg)
{
    try {
        console.log(msg);
    }
    catch(e) {}
}

function showPlayer(doc, mediaId, mediaType)
{
    if(!mediaType) {
        // player id
        mediaType = 4;
    }
    playerActive = true;
    
    $("#page-player .page-inner").hide();
    $("#page-player").addClass("no-padding");
    $("#tsplayer").show().css({
            width: "100%",
            height: "100%"
    });
    if(!doc.tsPlayer) {
        initPlayer(doc, mediaId, mediaType);
    }
    else {
        
        if(mediaType == 4 && doc.tsPlayer.get_player_id() == mediaId) {
            doc.tsPlayer.onresize();
            setTimeout(function() {
                    doc.tsPlayer.play();
            },
            1000);
            
        }
        else {
            doc.tsPlayer.destroy();
            doc.tsPlayer = null;
            initPlayer(doc, mediaId, mediaType);
        }
    }
}

function hidePlayer(doc)
{
    playerActive = false;
    $("#page-player").removeClass("no-padding");
    
    try {
        if(doc.tsPlayer.getVar("menuVisible")) {
            showMenu(false, doc);
        }
        if(doc.tsPlayer.getVar("playlistVisible")) {
            showPlaylist(false, doc);
        }
    }
    catch(e) {}
    
    $("#tsplayer").css({
        width: "1px",
        height: "1px"
    });
    
    try {
        doc.tsPlayer.onresize();
    }
    catch(e) {
    }
    
    updateLocation(window.location.hash);
}

var messages;
function getLanguage(lang) {
	var xmlHttp = new XMLHttpRequest();
	xmlHttp.open('get', 'ajax/getlang.php?lang='+lang, true);
	xmlHttp.onreadystatechange = function() {
		if (xmlHttp.readyState == 4) {
			var income = '('+xmlHttp.responseText+')';
			messages = eval(income);
		}};
	xmlHttp.send(null);
}

function updateLocation(hash)
{
    if(hash.length == 0) {
        if(bigScreenVisible) {
            closeScreen();
        }
    }
    
    var path = hash.split("/")
    if(path.length > 1) {
        var pageId = path[1],
            innerPageId = null,
            showInnerPageFunc = null;
        
        if(path.length > 2) {
            innerPageId = path[2];
        }
        
        if(pageId == "player") {
            if(TS.pluginInstalled()) {
                if(innerPageId === null || innerPageId == "install" || innerPageId == "reinstall") {
                    window.location.hash = "/player/demo";
                    return;
                }
            }
            else {
                if(innerPageId === null || (innerPageId != "install" && innerPageId != "reinstall")) {
                    window.location.hash = "/player/install";
                    return;
                }
            }
        }
        else if(pageId == "products" && innerPageId === null) {
            window.location.hash = "/products/all";
            return;
        }
        else if(pageId == "login" && innerPageId === null) {
            window.location.hash = "/login/registration";
            return;
        }
        
        if(pageId === "login" && innerPageId === "recover-pass") {
            if(path.length > 3) {
                key_pass_change = path[3];
            }
        }
        
        if(innerPageId !== null) {
            showInnerPageFunc = function() {
                showInnerPage(pageId, innerPageId);
            };
        }
        
        if(bigScreenVisible) {
            openScreen(pageId, true);
            if(showInnerPageFunc) {
                showInnerPageFunc();
            }
        }
        else {
            openScreen(pageId, false, showInnerPageFunc);
        }
    }
}

function openScreen(pageId, skipAnimation, callback)
{
    bigScreenVisible = true;
    $("#big-screen").data("currentPage", pageId);
    
	if (pageId == "player" && TS.pluginInstalled())
	{
		$("#torrentstream-body .player-controls").show();
	}
	else
	{
		$("#torrentstream-body .player-controls").hide();
	}
	
	if(skipAnimation) {
	    $('#big-screen .page').hide();
	    $('#big-screen .page#page-' + pageId).show();
	    $('#big-screen').css({'top': '86px'});
	    $('#big-screen .page#page-' + pageId + ' .scroll-pane-container').jScrollPane();
	    if(callback) {
	        callback();
	    }
	}
	else {
	    $('#big-screen').animate({
	            top: 86 + 'px'
	    }, 600, 'easeOutQuart', function() {
	        $('#big-screen .page#page-'+ pageId).fadeIn(300, function() {
	                $('#big-screen .page#page-' + pageId + ' .scroll-pane-container').jScrollPane();
                    if(callback) {
                        callback();
                    }
	        });
	    });
    }
}

function closeScreen(force)
{
    if(force) {
        window.location.hash = "";
    }
    bigScreenVisible = false;
    
    navigation.history = [];
    navigation.current = -1;
    updateHistoryNavigation();
    
    var currentPage = $("#big-screen").data("currentPage");
    $("#big-screen").removeData("currentPage");
    
    if(currentPage == "player") {
        playerDestroy(document);
    }
    
    $('#big-screen').animate({
            top: -640 + 'px'
    }, 700, 'easeInQuart');
    $('#big-screen .page').fadeOut(300, function() {
            $("#page-" + currentPage + " .page-inner").hide();
    });
}

function showInnerPage(pageId, innerPageId)
{
    $("#page-" + pageId + " .page-inner").hide();
    $("#page-" + pageId + " .page-inner-" + innerPageId).show();
    $("#page-" + pageId + " .page-inner-" + innerPageId + " .scroll-pane-container").jScrollPane();
}

function sendContactForm(button)
{
    if($(button).hasClass("disabled")) {
        return;
    }
    
    $(button).addClass("disabled");
    $.ajax({
            type: 'POST',
            url: 'ajax/send_contact_form.php',
            data: {
                lang: currentLang,
                email: $("#contact-form .input-email").val(),
                message: $("#contact-form .input-message").val()
            },
            dataType: 'json',
            success: function(data, status, xhr) {
                $(button).removeClass("disabled");
                if(data.status == 1) {
                    $("#contact-form .input-email").val("");
                    $("#contact-form .input-message").val("");
                    showMessage('info', data.msg);
                }
                else {
                    showMessage('error', data.msg);
                }
            },
            error: function(xhr, status) {
                $(button).removeClass("disabled");
                showMessage('error', messages['lang.error.ajax']);
            }
    });
}

function updateHistoryNavigation()
{
    if(navigation.history.length == 0) {
        $(".navigation .history-go-prev").addClass("disabled");
        $(".navigation .history-go-next").addClass("disabled");
    }
    else {
        if(navigation.current == 0) {
            $(".navigation .history-go-prev").addClass("disabled");
            $(".navigation .history-go-next").removeClass("disabled");
        }
        else if(navigation.current == (navigation.history.length - 1)) {
            $(".navigation .history-go-prev").removeClass("disabled");
            $(".navigation .history-go-next").addClass("disabled");
        }
        else {
            $(".navigation .history-go-prev").removeClass("disabled");
            $(".navigation .history-go-next").removeClass("disabled");
        }
    }
}

$(document).ready(function() {
        $(window).hashchange(function() {
                updateLocation(location.hash);
        });
        updateLocation(location.hash);
        
		getLanguage(currentLang);
		attachControlsEvents(document);
		$('div#menu-box').addClass(currentLang);
		
		$("#page-player a.nav-history").click(function() {
		        if(navigation.history.length == 0) {
	                navigation.history.push(window.location.hash);
	            }
	            else if(navigation.current < (navigation.history.length - 1)) {
	                navigation.history.splice(navigation.current + 1, navigation.history.length - navigation.current - 1);
	            }
	            navigation.history.push($(this).attr("href"));
	            navigation.current = navigation.history.length - 1; 
	            updateHistoryNavigation();
		});
		
		$("#page-player .navigation .history-go-prev").click(function() {
		        if($(this).hasClass("disabled")) {
		            return;
		        }
		        navigation.current -= 1;
	            if(navigation.current >= 0) {
	                window.location.hash = navigation.history[navigation.current];
	            }
	            updateHistoryNavigation();
		});
		
		$("#page-player .navigation .history-go-next").click(function() {
		        if($(this).hasClass("disabled")) {
		            return;
		        }
		        navigation.current += 1;
	            if(navigation.current < navigation.history.length) {
	                window.location.hash = navigation.history[navigation.current];
	            }
	            updateHistoryNavigation();
		});
		
		$('#button-send-mail').click(function() {
		        var $button = $(this);
		        if($button.hasClass("disabled")) {
		            return;
		        }
		        $button.addClass("disabled");
		        
                $email = $('#recovery-mail').val();
                if ($email == "") {
                    $button.removeClass("disabled");
                    showMessage('error', messages['lang.error.email_empty']);
                    return;
                }
                $.ajax({
                    type: 'POST',
                    url: 'ajax/email.php',
                    data: {
                        email : $email
                    },
                    dataType: 'json',
                    success: function(data, status, xhr) {
                        $button.removeClass("disabled");
                        if(data.status == 0) {
                            showMessage('error', data.error);
                        }
                        else if(data.status == 2) {
                            showMessage('error', messages['lang.error.wrong_email_format']);
                        }
                        else if(data.status == 3) {
                            showMessage('error', messages['lang.error.email_not_found']);
                        }
                        else if(data.status == 1) {
                            showMessage('info', messages['lang.notice.recovery_pass'], 7000); //An e-mail with instructions how to reset your password was sent to your e-mail adress
                        }
                    },
                    error: function(xhr, status) {
                        $button.removeClass("disabled");
                        showMessage('error', messages['lang.error.ajax']);
                    }
                });
		});
		
		$("#form-register .button-register").click(function(){
		        var $button = $(this);
		        if($button.hasClass("disabled")) {
		            return;
		        }
		        
		        if( ! $("#form-register .input-agree").attr("checked")) {
		            showMessage("error", "You must accept user agreement to continue registration");
		            return;
		        }
		        
		        $button.addClass("disabled");
                $.ajax({
                        type: 'POST',
                        url: 'ajax/register.php',
                        data: {
                            lang: currentLang,
                            login: $("#form-register .login").val(),
                            pwd: $("#form-register .password").val(),
                            pwd2: $("#form-register .password-confirm").val()
                        },
                        dataType: 'json',
                        success: function(data, status, xhr) {
                            $button.removeClass("disabled");
                            if(data.status == 0) {
                                $("#form-register .password").val('')
                                $("#form-register .password-confirm").val('')
                                showMessage('error', data.error);
                            }
                            else {
                                window.location.hash = "/login/reg-done";
                                $("div#text").html("<p>"+messages['lang.notice.recovery_pass']+"</p>");
                            }
                        },
                        error: function(xhr, status) {
                            $button.removeClass("disabled");
                            showMessage('error', 'user.login.error.internal');
                        }
                });
        });
		
		$(".button-recovery").click(function(){
		        var $button = $(this);
		        if($button.hasClass("disabled")) {
		            return;
		        }
		        $button.addClass("disabled");
		        
                var pass = $('.password-recovery').val();
                var pass_c = $('.password-confirm-recovery').val();
                var key = key_pass_change;
                
                if (pass == "") {
                    showMessage('error', messages['lang.error.password_empty']);
                    return;
                }
                if (pass_c == "") {
                    showMessage('error', messages['lang.error.password_confirm_empty']);
                    return;
                }
                if (pass != pass_c) {
                    showMessage('error', messages['lang.error.passwords_wrong']);
                    return;
                }
                
                $.ajax({
                        type: 'POST',
                        url: 'ajax/checkrecovery.php',
                        data: {
                            recovery_key: key,
                            pass: pass,
                        },
                        dataType: 'json',
                        success: function(data, status, xhr) {
                            $button.removeClass("disabled");
                            if(data.status == 0) {
                                $("#pass-recovery .password").val('')
                                $("#pass-recovery .password-confirm").val('')
                                showMessage('error', data.error);
                            }
                            else if(data.status == 1) {
                                $("div#text").html("<p>"+messages['lang.notice.pass_success']+"</p>");
                                $('#pass-recovery').hide();
                                $("#registration-info").show();
                            }
                        },
                        error: function(xhr, status) {
                            $button.removeClass("disabled");
                            showMessage('error', messages['lang.error.ajax']);
                        }
                });
	    });

        $("span.switch-page").click(function() {
                window.location.hash = $(this).attr("rel");
        });
        
        $("#page-login .show-options-image").click(function() {
                $("#page-login #view-options").show();
                $("#page-login #password-recovery").hide();
                $("#page-login .inner-overlay").show();
                $("#page-login .popup-window").css("width", "226px").show();
                return false;
        });
        
        $("#page-login .show-popup-remind-password").click(function() {
                $("#page-login #view-options").hide();
                $("#page-login #password-recovery").show();
                $("#page-login .inner-overlay").show();
                $("#page-login .popup-window").css("width", "386px").show();
                return false;
        });
        
        $("#page-login .close-popup").click(function() {
                $("#page-login #view-options").hide();
                $("#page-login #password-recovery").hide();
                $("#page-login .inner-overlay").hide();
                $("#page-login .popup-window").hide();
                return false;
        });
        
        $("#page-login .button-accept-agreement").click(function() {
                $("#page-login .input-agree").attr("checked", true);
        });
});

function showMessage(type, message, delay)
{
    if(message === undefined) {
        return;
    }
    
    if(type == 'alert') {
        alert(message);
        return;
    }
    
	if (delay === undefined) {
		delay = 1500;
	}
	
    $("#warning").attr("class", type).html(message).slideDown(350,
	function(){
		var $box = $(this);
		setTimeout(function (){$box.slideUp(350);}, delay);
	});
}

function createPlayer(type)
{
    if(type == 'file') {
        document.getElementById('create-player-upload-form').submit();
        return;
    }
    else if(type == 'url') {
        var url = $('#create-player-url').val();
        $.ajax({
                type: 'POST',
                url: 'ajax/upload.php',
                data: {
                    type: 'url',
                    url: url
                },
                dataType: 'json',
                success: function(data, status, xhr) {
                    if(data.status == 1) {
                        showPlayer(document, data.uid, 4);
                    }
                    else if(data.status == 0) {
                        showMessage('alert', data.msg);
                    }
                    else {
                        showMessage('alert', 'Ошибка на сервере. Попробуйте позже.');
                    }
                },
                error: function(xhr, status) {
                    showMessage('alert', 'Сервер не отвечает. Попробуйте позже.');
                }
        });
    }
    else if(type == 'direct_url') {
        var url = $('#create-player-direct-url').val();
        showPlayer(document, url, 2);
    }
}

function playerUploadComplete(success, data)
{
    try {
        if(success == 1) {
            showPlayer(document, data, 4);
        }
        else if(success == 0) {
            showMessage('alert', data);
        }
        else {
            showMessage('alert', 'Ошибка на сервере. Попробуйте позже.');
        }
    }
    catch(e) {
        log(e);
    }
}


