﻿/*global $f:false */
var staM = getINTParam("taM");
var lang = getSTRParam("lang") || "PO";
var id = getINTParam("id");
var ide = getINTParam("ide");
var ida = getINTParam("ida");
var idan = getINTParam("idan");
var idi = getINTParam("idi");
var idv = getINTParam("idv");
var stipo = getSTRParam("stipo") || "";

function getINTParam(sparam) {
    //console.log('getINTParam ' + sparam);
    var stemp = '';
    var currentUrl = window.location.href;
    var surl = new URL(currentUrl);

    if (validateURL(surl)) {
        stemp = surl.searchParams.get(sparam) || 0;
        stemp = ($.isNumeric(stemp) ? parseInt(stemp) : 0);
    }
    return stemp;
}
function getSTRParam(sparam) {
    //console.log('getSTRParam ' + sparam);
    var stemp = '';
    var currentUrl = window.location.href;
    var surl = new URL(currentUrl);

    if (validateURL(surl)) {
        stemp = surl.searchParams.get(sparam) || "";
    }
    return stemp;
}

function validateURL(surl) {
    //debugger;
    //console.log('validateURL ' + surl);
    var regexp = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/
    return regexp.test(surl);
}

function parseURL(surl) {
    var a = document.createElement('a');
    a.href = surl;
    return {
        source: surl,
        protocol: a.protocol.replace(':', ''),
        hostname: a.hostname,
        host: a.host,
        port: a.port,
        query: a.search,
        params: (function () {
            var ret = {},
                seg = a.search.replace(/^\?/, '').split('&'),
                len = seg.length, i = 0, s;
            for (; i < len; i++) {
                if (!seg[i]) { continue; }
                s = seg[i].split('=');
                ret[s[0]] = s[1];
            }
            return ret;
        })(),
        file: (a.pathname.match(/\/([^\/?#]+)$/i) || [, ''])[1],
        hash: a.hash.replace('#', ''),
        path: a.pathname.replace(/^([^\/])/, '/$1'),
        relative: (a.href.match(/tps?:\/\/[^\/]+(.+)/) || [, ''])[1],
        segments: a.pathname.replace(/^\//, '').split('/')
    };
}  
//FIM validate url

$(document).ready(function () {
    //console.log('(document).ready(');
    staM = getINTParam("taM");
    lang = getSTRParam("lang") || "PO";
    id = getINTParam("id");
    ide = getINTParam("ide");
    ida = getINTParam("ida");
    idan = getINTParam("idan");
    idi = getINTParam("idi");
    idv = getINTParam("idv");
    stipo = getSTRParam("stipo") || "";

    //if ($('.jcarousel').length > 0) {
    //    var width = $(window).width();
    //    if (width > 0 && width <= 540) {
    //        $('.jcarousel').width(520);
    //    }
    //    }
    //    else if (width > 540 && width <= 980) {
    //        $('.jcarousel').width(780);
    //    }
    //    else if (width > 980 && width <= 1024) {
    //        $('.jcarousel').width(990);
    //    }
    //    else if (width > 1024 && width <= 1280) {
    //        $('.jcarousel').width(1040);
    //    }
    //    else if (width > 1280) {
    //        $('.jcarousel').width(1255);
    //    }
    //}
    if ($('#ficha_informante').length > 0) {
        var width = $(window).width();
        if (width > 0 && width <= 540) {
            $('#ficha_informante').width(520);
        }
        else if (width > 540 && width <= 980) {
            $('#ficha_informante').width(780);
        }
        else if (width > 980 && width <= 1024) {
            $('#ficha_informante').width(990);
        }
        else if (width > 1024 && width <= 1280) {
            $('#ficha_informante').width(1040);
        }
        else if (width > 1280) {
            $('#ficha_informante').width(1255);
        }
    }

    if ($('#ficha_tema').length > 0) {
        var width = $(window).width();
        if (width > 0 && width <= 540) {
            $('#ficha_tema').width(520);
        }
        else if (width > 540 && width <= 980) {
            $('#ficha_tema').width(780);
        }
        else if (width > 980 && width <= 1024) {
            $('#ficha_tema').width(990);
        }
        else if (width > 1024 && width <= 1280) {
            $('#ficha_tema').width(1040);
        }
        else if (width > 1280) {
            $('#ficha_tema').width(1255);
        }
    }
    if ($('#ficha').length > 0) {
        var width = $(window).width();
        if (width > 0 && width <= 540) {
            $('#ficha').width(520);
        }
        else if (width > 540 && width <= 980) {
            $('#ficha').width(780);
        }
        else if (width > 980 && width <= 1024) {
            $('#ficha').width(990);
        }
        else if (width > 1024 && width <= 1280) {
            $('#ficha').width(1040);
        }
        else if (width > 1280) {
            $('#ficha').width(1255);
        }
    }
    
});
$.ajaxSetup({
    timeout: 5000,
    error: function (event, request, settings) {
        console.log("Oops! ");
        console.log(event);
        console.log(request);
        console.log(settings);

        if ($.isFunction($('#activity_pane').hideLoading)) {
            $('#activity_pane').hideLoading();
        }
        $('#activity_pane').css('visibility', 'hidden');
        $('#activity_pane').css('display', 'none');
    }
});
$(window).error(function (e) {
    e.preventDefault();
});

var pageIndex = 0;
var pageCount;
var map;
var repeatColumns = 4;

function resizeW() {
    //console.log('resizeW');
    var width = $(this).width();
    //Check the width also you need to check it’s not in same ratio which was it before
    //So it will not call repeatedly for many times as infinite by checking ratio value which assigned from local storage.
    //And assign hidden field value and call the buttonclick event from jquery fuction so it will set the RepeatColumns value.
    if (width > 0 && width <= 540) {
        $("[id*=hfColumnRepeat]").val(2);
        repeatColumns = 2;
        $("[id*=btnfake]").click();
    }
    else if (width > 540 && width <= 980) {
        $("[id*=hfColumnRepeat]").val(3);
        repeatColumns = 3;
        $("[id*=btnfake]").click();
    }
    else if (width > 980 && width <= 1280) {
        $("[id*=hfColumnRepeat]").val(4);
        repeatColumns = 4;
        $("[id*=btnfake]").click();
    }
    else if (width > 1280) {
        $("[id*=hfColumnRepeat]").val(5);
        repeatColumns = 5;
        $("[id*=btnfake]").click();
    }
}
//construir os registos para a galeria
function GetRecords(surl, bpage)
{
    //console.log('GetRecords');
    $('#activity_pane').css('visibility', 'visible');
    $('#activity_pane').css('display', 'block');
    if ($.isFunction($('#activity_pane').showLoading)) {
        $('#activity_pane').showLoading();
    }

    var cat = getINTParam("idcat") || "0";
    if (surl == "pessoas") {
        var cat = document.getElementById('botao_pesquisa_submit').value || "0";
        if (cat == 'Procurar por') cat = '';
    }

    pageIndex++;
    //int pageIndex, string cat, string ide, string idi, string idv, string staM, string lang
    if (pageIndex == 1 || pageIndex <= pageCount) {
        //console.log('GetRecords');
        $("#loader").show();
        $.ajax({
            type: "POST",
            url: surl+".aspx/GetImages",
            data: "{'pageIndex': '" + pageIndex + "', 'cat':'" + cat + "','ide':'" + ide + "','idi':'" + idi + "','idv':'" + idv + "','staM':'" + staM + "','lang':'"+lang+"'}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: OnSuccess,
            failure: function (response) {
                console.log("failure GetRecords " + response.responseText);
                console.log(surl +".aspx/GetImages ('pageIndex': '" + pageIndex + "', 'cat':'" + cat + "','ide':'" + ide + "','idi':'" + idi + "','idv':'" + idv + "','staM':'" + staM + "','lang':'" + lang + "')");
            },
            error: function (response) {
                console.log("error GetRecords " + response);
                console.log(surl + ".aspx/GetImages ('pageIndex': '" + pageIndex + "', 'cat':'" + cat + "','ide':'" + ide + "','idi':'" + idi + "','idv':'" + idv + "','staM':'" + staM + "','lang':'" + lang + "')");
            }
        });
    }

    if ($.isFunction($('#activity_pane').hideLoading)) {
        $('#activity_pane').hideLoading();
    }
    $('#activity_pane').css('visibility', 'hidden');
    $('#activity_pane').css('display', 'none');
}

function OnSuccess(response) {

    var xmlDoc = $.parseXML(response.d);
    var xml = $(xmlDoc);
    pageCount = parseInt(xml.find("PageCount").eq(0).find("PageCount").text());
    var images = xml.find("Images");
    var ids = '';

    resizeW();
    //console.log('repeatColumns ' + repeatColumns.toString() + ' | images.length ' + images.length.toString());

    //var rowCount = Math.ceil(images.length / repeatColumns);
    //var countl = 0;
    var j = 0;

    //console.log('response OnSuccess');
    images.each(function () {
        var image = $(this);
        try {

            //console.log(j + ' | ' + image.find("Titulo").text());
            if (image.find("URL").text() != "") {
                //console.log(image.find("URL").text());
                var row = $("[id*=dlImages] .item:last").closest("tr");
                //console.log(row.context);
                //if (j == repeatColumns) {
                if ($(".is_used[value='1']", row).length == repeatColumns) {
                    //console.log('-------------- j == repeatColumns');
                    row = $("[id*=dlImages] tr").eq(0).clone();
                    $(".is_used", row).val("0");
                    $(".image", row).attr("src", "");
                    $(".img_file", row).attr("href", "");
                    $(".loader", row).remove();
                    $("[id*=dlImages]").append(row);
                    j = 0;
                } else {
                    row = $("[id*=dlImages] .item:last").closest("tr");
                }
                var cell = $(".item", row).eq(j);
                
                $(".img_file", cell).attr("href", image.find("URL").text() + ids);
                $(".is_used", cell).attr("value", "1");
                var img = $(".image", cell);

                var loader = $("<img class='loader' src='images/loading_old.gif' />");
                img.after(loader);
                img.hide();

                img.attr("title", image.find("Titulo").text());
                img.attr("ID", "img_"+image.find("ID").text());
                img.attr("alt", image.find("Titulo").text());
                $(".img_file div",cell).attr("ID", "div_"+image.find("ID").text())
                //console.log(image.find("PathWeb").text());

                if (image.find("PathWeb").text() != "") {
                    var spathweb = image.find("PathWeb").text();
                    var origin = window.location.origin;

                    if (spathweb.startsWith("~/")) {
                        spathweb = spathweb.replace("~/","/")
                    }
                    //console.log('spathweb');
                    //console.log(origin+ spathweb);
                    img.attr("src", origin + spathweb);
                }
                else {
                    img.attr("src", "images/noimage250x160.svg");
                }
				img.show();
                $(".img_file div", cell).html(image.find("Titulo").text());
                img.load(function () {
                    $(this).parent().find(".loader").remove();
                    $(this).fadeIn();
                });
            }
        }
        catch (err) {
            console.log('ERROR ' + err.message);
        }
        j++;
        //countl++;
    });
    $("[id*=dlImages] .is_used[value='0']").closest(".item").remove();
}

function errorloadimage(image)
{
    if (typeof jQuery !== 'undefined') {
        //console.log("Error occurred while loading image " + image.src);
        image.src = 'images/noimage250x160.svg';
        //console.log($(image).prev());
        //console.log(prevdiv);
        //var previousdiv = $(image).prev();
        //previousdiv.show();
    }
}
//esconder e mostrar a informação do autor
function show_ft() {
    var displayValue = document.getElementById('ft_autor').style.display;
    if ($('#ft_autor').css('display') == 'block') {
        document.getElementById('ft_autor').style.display = "none";
        $('div#ft_show a div.ft_menos').removeClass("ft_menos").addClass("ft_mais");
    }
    else {
        document.getElementById('ft_autor').style.display = "block";
        $('div#ft_show a div.ft_mais').removeClass("ft_mais").addClass("ft_menos");
    }
}

function fichaErrada() {
    $(".documento p").css('background-color', '#6e6e6e');
    $(".documento p a").css('color', '#FFFFFF');
    $(".documento p").css('background-image', 'url("images/icondoc_branco.png") !important');
}

//Pesquisa pelo texto
function SearchText(surl) {
    //console.log('autosuggest');
    $(".autosuggest").autocomplete({
        source: function (request, response) {
            //console.log('source');

            var bsearchtext = document.getElementById('botao_pesquisa_submit').value;
            if (bsearchtext == 'Procurar por') bsearchtext = '';
            if (bsearchtext != '' && bsearchtext != 'Procurar por') {
                $.ajax({
                    type: "POST",
                    contentType: "application/json; charset=utf-8",
                    url: surl + ".aspx/GetAutoCompleteData",
                    data: "{'nome':'" + bsearchtext + "','staM':'" + staM + "','stipo':'" + stipo + "'}",
                    dataType: "json",
                    timeout: 3000,
                    autoFill: true,

                    success: function (data) {
                        response(data.d);
                        $('#ui-id-1').css('display', 'block');
                        $('#ui-id-1').css('z-index', '999');
                    },
                    error: function (result) {
                        console.log("Error: " + result.status + " " + result.statusText);
                    },
                    failure: function (result) {
                        console.log("failure: " + result.status + " " + result.statusText);
                    }
                });
            }
        }
        , select: function (event, ui) {
            console.log('SearchText select');
        }
        , error: function (result) {
            console.log('SearchText error');
        }
    });
}

//Get Content for infowindow
function getC(marker, surl, stipo) {

    //console.log(marker.myID);
    //string title, string local, string stipo, string sta
    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: surl+".aspx/getInf",
        data: "{'title': '" + marker.title + "','markerID': '" + marker.myID + "','stipo':'" + stipo + "','staM':'" + staM+"'}",
        dataType: "json",
        success: function (data) {
            //infowindow.setTitle(marker.title);
            infowindow.setContent('<div class="info_window"><h2>' + marker.title + "</h2>" + data.d + '</div>');
            infowindow.open(map, marker);
        },
        failure: function (response) {
            console.log(response.data);
        }
    });
}

function getColorMarker(iconimg,param) {
    var _result = '';
    if (iconimg.indexOf('local_aud') >= 0) {
        if (param == 'select' || param == 'click') {
            _result = 'images/mapa/local_aud_clicar.png';
        }
        //else if (param == 'click') {
        //    _result = 'images/mapa/local_aud_clicar.png';
        //}
        else {
            _result = 'images/mapa/local_aud.png';
        }
    }
    else if (iconimg.indexOf('local_imv') >= 0) {
        if (param == 'select' || param == 'click') {
            _result = 'images/mapa/local_imv_clicar.png';
        }
        //else if (param == 'click') {
        //    _result = 'images/mapa/local_imv_clicar.png';
        //}
        else {
            _result = 'images/mapa/local_imv.png';
        }
    }
    return _result;
}
function cleanValue() {
    //console.log('cleanValue');
    $('#botao_pesquisa_submit').val('');
}

function goBack(voltar2, voltar1) {

    if (!voltar2.indexOf("pessoas.aspx?lang=" + lang + "&taM=" + staM))
        history.go(-2);
    else
        history.go(-1);
}

function getUrlVars() {
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for (var i = 0; i < hashes.length; i++) {
        hash = hashes[i].split('=');
        vars.push(hash[0]);
        vars[hash[0]] = hash[1];
    }
    return vars;
}

function SetSession(spage,_key, _ids, _search, stipo) {
    //console.log('SetSession');
    $.ajax({
        type: "POST",
        url: "temas.aspx/SetSessionI",
        data: '{key: "' + _key + '",search:"' + _search + '",ids:"' + _ids + '",sta:"' + staM + '",stipo:"' + stipo +'"}',
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (response) {
            //console.log('success');
            //console.log("resultado.aspx?lang=" + lang + "&taM=" + staM);
            window.location.href = "resultado.aspx?lang=" + lang + "&taM=" + staM;
        },
        failure: function (response) {
            console.log('failure ' + response.responseText);
        },
        error: function (response) {
            console.log("error " + response.responseText);
        }
    });
}

function showMenu() {
    //console.log('showMenu');
    $('#menulat').css("display", "block");
    $('.openML').attr("onclick", "hideMenu();");
    $('div.header_menu').addClass('menusel');
}
function hideMenu() {
    //console.log('hideMenu');
    $('#menulat').css("display", "none");
    $('.openML').attr("onclick", "showMenu()");

    $('div.header_menu').removeClass('menusel');
}

$("a.openML").bind("click touchstart", function (e) {
    console.log('touchstart');
    if ($('#menulat').css("display") == "none") {
        showMenu();
        $('div.header_menu').addClass('menusel');
    }
    else {
        hideMenu();
        $('div.header_menu').removeClass('menusel');
    }

    e.stopPropagation();
    e.preventDefault();
});

function HandleBackFunctionality(vsession) {
    var previousPageURL = vsession;
}

//Pausar o vídeo
function pauseVideo() {
    $("iframe").each(function () {
        var iframe = $(this)[0];
        var player = $f(iframe);
        player.api('pause');
    });

    var is_safari = false;
    if (navigator.userAgent.indexOf('Safari') != -1 && navigator.userAgent.indexOf('Chrome') == -1)
        is_safari = true;
    var pendingSeektoTime = '<%= tseconds %>';

    if (pendingSeektoTime == '') {
        pendingSeektoTime = '0';
    }

    var player = $f($(".embed_container iframe")[0]);
    if (navigator.userAgent.match(/(iPad|iPhone|iPod)/g) || is_safari) {
        player.api('seekTo', pendingSeektoTime);
    } else {
        player.api('seekTo', pendingSeektoTime);
    }
    //alert(pendingSeektoTime);
    //console.log(pendingSeektoTime);
}
function reloadpageclick(ide, ida, idan) {
    //debug;
    //console.log("pessoas_entrevista.aspx?ide=" + ide + "&ida=" + ida + "&idan=" + idan + "&lang=" + lang + "&taM=" + staM);
    window.location.href = "pessoas_entrevista.aspx?ide=" + ide + "&ida=" + ida + "&idan=" + idan + "&lang=" + lang + "&taM=" + staM;
    return false;
}

function reloadlocaltypeclick(stipo) {
    var surl = "lugares.aspx?lang=" + lang + "&taM=" + staM;
    if (stipo != '') {
        surl += "&stipo=" + stipo;
    }
    window.location.href = surl;
    
    return false;
}

function reloadMemtypeclick(stipo) {
    var surl = "temasleaf.aspx?lang=" + lang + "&taM=" + staM;
    if (stipo != '') {
        surl += "&stipo=" + stipo;
    }
    window.location.href = surl;

    return false;
}
/* When the user clicks on the button,
toggle between hiding and showing the dropdown content */
function myFunction() {
    document.getElementById("myDropdown").classList.toggle("show");
}

function filterFunction() {
    var input, filter, ul, li, a, i;
    input = document.getElementById("myInput");
    filter = input.value.toUpperCase();
    div = document.getElementById("myDropdown");
    a = div.getElementsByTagName("a");
    for (i = 0; i < a.length; i++) {
        txtValue = a[i].textContent || a[i].innerText;
        if (txtValue.toUpperCase().indexOf(filter) > -1) {
            a[i].style.display = "";
        } else {
            a[i].style.display = "none";
        }
    }
}