/*
 * Return a random parameter to url
 */
function getRandom(){
    var rand = Math.round(10000 * Math.random());
    
    return "&rand=" + rand;
}

/*
 * Get Event Inner HTML
 */
function getEventInnerHTML(eventID){
    $.ajax({
        type: "GET",
        url: "templates/event-html.php",
        data: "eventid=" + eventID + getRandom(),
        success: function(html){
            $("#gallery").html(html);
            startGallery();
            initJQueryModal();
        }
    });
}

/*
 * Get Recent Event Inner HTML
 */
function getRecentEventInnerHTML(dateParam, keywordParam, recent, page){
	$.ajax({
        type: "GET",
        url: "templates/recentevent-html.php",
        data: "date=" + dateParam + "&keyword=" + escape(keywordParam) + "&recent=" + recent + "&page=" + page + getRandom(),
        success: function(html){
            $("#recent").html(html);
			
            if ((dateParam == "") && (keywordParam == "")) {
                $("#recentLabel").html("Coberturas mais recentes");
            }
            else {
                $("#recentLabel").html("Coberturas encontradas");
            }
        }
    });
}

function startGallery(){
    var galleries = $('.ad-gallery').adGallery({
        loader_image: 'imagens/loader.gif',
		width: 600, /* Width of the image, set to false and it will read the CSS width */
        height: 455, /* Height of the image, set to false and it will read the CSS height */
        thumb_opacity: 0.7,
        /* Opacity that the thumbs fades to/from, (1 removes fade effect) 
         Note that this effect combined with other effects might be resource intensive
         and make animations lag */
        start_at_index: 0, /* Which image should be displayed at first? 0 is the first image */
        animate_first_image: true, /* Should first image just be displayed, or animated in? */
        animation_speed: 400, /* Which ever effect is used to switch images, how long should it take? */
        display_next_and_prev: true, /* Can you navigate by clicking on the left/right on the image? */
        display_back_and_forward: true, /* Are you allowed to scroll the thumb list? */
        scroll_jump: 0, /* If 0, it jumps the width of the container */
        slideshow: {
            enable: true,
            autostart: false,
            speed: 5000,
            start_label: 'Iniciar',
            stop_label: 'Pausa',
            stop_on_scroll: true, /* Should the slideshow stop if the user scrolls the thumb list? */
            countdown_prefix: '(', /* Wrap around the countdown */
            countdown_sufix: ')',
            onStart: function(){
                /* Do something wild when the slideshow starts */
            },
            onStop: function(){
                /* Do something wild when the slideshow stops */
            }
        },
        effect: 'fade', /* or 'slide-vert', 'resize', 'fade', 'none' or false */
        enable_keyboard_move: true, /* Move to next/previous image with keyboard arrows? */
        cycle: true,
        /* If set to false, you can't go from the last image to the first, and vice versa
         All callbacks has the AdGallery objects as this reference */
        callbacks: {
            /* Executes right after the internal init, can be used to choose which images
             you want to preload */
            init: function(){
                /* Do something wild! */
                // preloadAll uses recursion to preload each image right after one another
                this.preloadImage(this.current_index + 1);
            },
            /* This gets fired right after the new_image is fully visible */
            afterImageVisible: function(){
                /* For example, preload the next image */
                var context = this;
                this.loading(true);
                this.preloadImage(this.current_index + 1, function(){
                    /* This function gets executed after the image has been loaded */
                    context.loading(false);
                });
            },
            /* This gets fired right before old_image is about to go away, and new_image
             is about to come in */
            beforeImageVisible: function(new_image, old_image){
                /* Do something wild! */
            }
        }
    });
}

function initJQueryModal(){
    /*JQuery Modal*/
    /*select all the a tag with name equal to modal*/
    $('a[name=modal]').click(function(e){
        /*Cancel the link behavior*/
        e.preventDefault();
        
        /*Get the A tag*/
        var id = $(this).attr('href');
        
        /*Get the screen height and width*/
        var maskHeight = $(document).height();
        var maskWidth = $(window).width();
        
        /*Set heigth and width to mask to fill up the whole screen*/
        $('#mask').css({
            'width': maskWidth,
            'height': maskHeight
        });
        
        /*transition effect*/
        $('#mask').fadeIn(1000);
        $('#mask').fadeTo("slow", 0.8);
        
        /*Get the window height and width*/
        var winH = $(window).height();
        var winW = $(window).width();
        
        /*Set the popup window to center*/
        $(id).css('top', winH / 2 - $(id).height() / 2);
        $(id).css('left', winW / 2 - $(id).width() / 2);
        
        /*transition effect*/
        $(id).fadeIn(2000);
        
        document.getElementById("fieldNameFrom").focus();
    });
    
    /*if close button is clicked*/
    $('.window .sendMail').click(function(e){
        /*Cancel the link behavior*/
        e.preventDefault();
        
        /*Send e-mail*/
        var nameFrom = document.getElementById("fieldNameFrom");
        var emailFrom = document.getElementById("fieldEmailFrom");
        var nameTo = document.getElementById("fieldNameTo");
        var emailTo = document.getElementById("fieldEmailTo");
        var message = document.getElementById("fieldMessage");
        var recordId = document.getElementById("fieldRecordId");
        var table = document.getElementById("fieldTable");
        var image = document.getElementById("fieldImage");
        
        if ((nameFrom.value.length == 0) || (emailFrom.valuelength == 0) ||
        (nameTo.valuelength == 0) ||
        (emailTo.valuelength == 0)) {
            alert("Todos os campos sao obrigatorios!");
        }
        else {
            $('#errorMessage').html("");
            
            if ((table.value == "event") || (table.value == "stockphoto")) {
                emailImage(recordId.value, table.value, image.value, nameFrom.value, emailFrom.value, nameTo.value, emailTo.value, message.value);
            } else if ((table.value == "news") || (table.value == "magazine")) {
                emailNews(recordId.value, table.value, nameFrom.value, emailFrom.value, nameTo.value, emailTo.value, message.value);
            } else if (table.value == "calendar") {
				emailCalendar(recordId.value, table.value, nameFrom.value, emailFrom.value, nameTo.value, emailTo.value, message.value);
			}
			
            
            $('#mask').hide();
            $('.window').hide();
        }
    });
    
    /*if mask is clicked*/
    $('#mask').click(function(){
        $(this).hide();
        $('.window').hide();
    });
}

function setCurrentImageReference(recordId, table, image){
    var fieldRecordId = document.getElementById("fieldRecordId");
    var fieldTable = document.getElementById("fieldTable");
    var fieldImage = document.getElementById("fieldImage");
    
    fieldRecordId.value = recordId;
    fieldTable.value = table;
    fieldImage.value = image;
    
    if (document.getElementById("printImageBtn") != null) {
		document.getElementById("printImageBtn").onclick = function(){
			printImage(recordId, table, image);
		}
	}
}

function printImage(recordId, table, image){
    window.open('templates/printimage.php?recordid=' + recordId + '&table=' + table + '&image=' + escape(image), '_blank', 'toolbar=no, status=no, menubar=no, resizable=no, scrollbars=yes, copyhistory=no, width=650, height=580');
}

function printNews(recordId, table){
    window.open('templates/printnews.php?recordid=' + recordId + "&table=" + table, '_blank', 'toolbar=no, status=no, menubar=no, resizable=no, scrollbars=yes, copyhistory=no, width=650, height=580');
}

function emailImage(recordId, table, image, nameFrom, emailFrom, nameTo, emailTo, message){
    $.ajax({
        type: "GET",
        url: "templates/emailimage.php",
        data: "recordid=" + recordId + "&table=" + table + "&image=" + image +
        "&nameFrom=" +
        nameFrom +
        "&emailFrom=" +
        emailFrom +
        "&nameTo=" +
        nameTo +
        "&emailTo=" +
        emailTo +
        "&message=" +
        escape(message) +
        getRandom(),
        success: function(html){
        }
    });
}

function emailNews(recordId, table, nameFrom, emailFrom, nameTo, emailTo, message){
    $.ajax({
        type: "GET",
        url: "templates/emailnews.php",
        data: "recordid=" + recordId + "&table=" + table +
        "&nameFrom=" +
        nameFrom +
        "&emailFrom=" +
        emailFrom +
        "&nameTo=" +
        nameTo +
        "&emailTo=" +
        emailTo +
        "&message=" +
        escape(message) +
        getRandom(),
        success: function(html){
        }
    });
}

function emailCalendar(recordId, table, nameFrom, emailFrom, nameTo, emailTo, message){
    $.ajax({
        type: "GET",
        url: "templates/emailcalendar.php",
        data: "recordid=" + recordId + "&table=" + table +
        "&nameFrom=" +
        nameFrom +
        "&emailFrom=" +
        emailFrom +
        "&nameTo=" +
        nameTo +
        "&emailTo=" +
        emailTo +
        "&message=" +
        escape(message) +
        getRandom(),
        success: function(html){
        }
    });
}

function emailVideo(){
    var videoId = document.getElementById("fieldVideoId");
    var nameFrom = document.getElementById("fieldNameFrom");
    var emailFrom = document.getElementById("fieldEmailFrom");
    var nameTo = document.getElementById("fieldNameTo");
    var emailTo = document.getElementById("fieldEmailTo");
    var message = document.getElementById("fieldMessage");
    /*var eventId = document.getElementById("fieldEventId");*/
    
    if ((nameFrom.value.length == 0) || (emailFrom.valuelength == 0) ||
    (nameTo.valuelength == 0) ||
    (emailTo.valuelength == 0)) {
        alert("Todos os campos sao obrigatorios!");
    }
    else {
        $('#errorMessage').html("");
        
        $.ajax({
            type: "GET",
            url: "templates/emailvideo.php",
            data: "videoid=" + videoId.value +
            "&nameFrom=" +
            nameFrom.value +
            "&emailFrom=" +
            emailFrom.value +
            "&nameTo=" +
            nameTo.value +
            "&emailTo=" +
            emailTo.value +
            "&message=" +
            escape(message.value) +
            getRandom(),
            success: function(html){
                nameFrom.value = "";
                emailFrom.value = "";
                nameTo.value = "";
                emailTo.value = "";
                message.value = "";
            }
        });
    }
}

function truncateText(){
    for (var i = 1; i < 5; i++) {
        var divname = '#detailsDiv' + i;
        $(divname).jTruncate({
            length: 50,
            moreText: "(mais)",
            lessText: "(menos)"
        });
        
        var divname = '#attractionsDiv' + i;
        $(divname).jTruncate({
            length: 50,
            moreText: "(mais)",
            lessText: "(menos)"
        });
    }
}

/*
 * Get Video Inner HTML
 */
function getVideoInnerHTML(videoID){
    $.ajax({
        type: "GET",
        url: "templates/video-html.php",
        data: "videoid=" + videoID + getRandom(),
        success: function(html){
            $("#gallery").html(html);
            
            var videoId = document.getElementById("fieldVideoId");
            videoId.value = videoID;
        }
    });
}

/*
 * Get Recent Video Inner HTML
 */
function getRecentVideoInnerHTML(dateParam, keywordParam, pageParam){
    $.ajax({
        type: "GET",
        url: "templates/recentvideo-html.php",
        data: "date=" + dateParam + "&keyword=" + escape(keywordParam) + "&page=" + pageParam + getRandom(),
        success: function(html){
            $("#recent").html(html);
            
            if ((dateParam == "") && (keywordParam == "")) {
                $("#recentLabel").html("&Uacute;ltimos v&iacute;deos");
            }
            else {
                $("#recentLabel").html("V&iacute;deos encontrados");
            }
            
            videoCallback();
        }
    });
}

/*
 * Get StockPhoto Inner HTML
 */
function getStockPhotoInnerHTML(stockphotoID){
    $.ajax({
        type: "GET",
        url: "templates/stockphoto-html.php",
        data: "stockphotoid=" + stockphotoID + getRandom(),
        success: function(html){
            $("#gallery").html(html);
            startGallery();
            initJQueryModal();
        }
    });
}

/*
 * Get Recent Event Calendar Inner HTML
 */
function getRecentEventCalendarInnerHTML(dateParam){
    $.ajax({
        type: "GET",
        url: "templates/recenteventcalendar-html.php",
        data: "date=" + dateParam + getRandom(),
        success: function(html){
            $("#recent").html(html);
        }
    });
}

function getTodayStr(){
    var today = new Date()
    return today.getFullYear() + "-" + (today.getMonth() + 1) + "-" + today.getDate();
}

/* ------------------------------------------------------------------------- */
/*
 * POLL
 */
function setCurrentAnswerPollReference(questionId, answerId){
    var buttonVote = document.getElementById("buttonVote");
    
    buttonVote.onclick = function(){
        votePoll(questionId, answerId);
    }
}

function votePoll(questionId, answerId){
    if (questionId != null) {
		$("#poll-container").fadeOut("slow",function(){
		$.ajax({
			type: "GET",
			url: "votepoll.php",
			data: "questionid=" + questionId + (answerId != null ? "&answerid=" + answerId : "") + getRandom(),
			success: function(html){
				if (html != "null") {
					$("#poll-container").html(html).fadeIn("slow", function(){
						animateResults();
					});
				}
			}
		});
		});
	}
}

function animateResults(){
  $("#poll-results div").each(function(){
      var percentage = $(this).next().text();
      $(this).css({width: "0%"}).animate({
				width: percentage}, 'slow');
  });
}

