// JavaScript Document for Boomerang Pet Awards global elements.
var page = 4;
var overlayImagePath = '/images/frame-none.png';
var videoLoaded = false;
function mycarousel_itemAddCallback(carousel, first, last, data){
    var totalItems = $("#carousel").children().size();
    $.each(data,function(i,item){
        var n = i+1;
        $("<li></li>")
            .attr("class","jcarousel-item jcarousel-item-horizontal jcarousel-item-"+(totalItems+n)+" jcarousel-item-"+(totalItems+n)+"-horizontal")
            .attr("jcarouselindex",totalItems+n)
            .html('<a href="'+item.href+'"><img height="50" width="67" alt="" src="'+item.thumbnail+'"/></a>')
            .appendTo("#carousel");
        
        carousel.add(totalItems+n, '<a href="'+item.href+'"><img height="50" width="67" alt="" src="'+item.thumbnail+'"/></a>');
        var nw = $("#carousel").width()+82;
        $(".awards #carousel").css("width",nw+"px");
    });
    carousel.size($("#carousel").children().size());
};
function loadMoreItems(carousel, state){
    var category=$("#categoryJson").html().replace(/is the /,"").replace(/are the /,"").replace(/ /,"");
    $.ajax({
        type: "GET",
        url: "/ajax/watch-video-awards.ajax.php?category="+category+"&page="+page,
        dataType: 'json',
        error: function(){         
            showError("Oops! Upload error! Please try again.");
            return false;
        },
        success: function(data){
            if (data!=""){                               
                mycarousel_itemAddCallback(carousel, carousel.first, carousel.last, data);
            }
        }          
    });
    page++;
}
function mycarousel_itemAddImp(carousel, first, last, data){
    var totalItems = $("#carousel").children().size();
    $.each(data,function(i,item){
        var n = i+1;
        $("<li></li>")
            .attr("class","jcarousel-item jcarousel-item-horizontal jcarousel-item-"+(totalItems+n)+" jcarousel-item-"+(totalItems+n)+"-horizontal")
            .attr("jcarouselindex",totalItems+n)
            .html('<a href="'+item.href+'"><img height="50" width="67" alt="" src="'+item.thumbnail+'"/></a>')
            .appendTo("#carousel");
        
        carousel.add(totalItems+n, '<a href="'+item.href+'"><img height="50" width="67" alt="" src="'+item.thumbnail+'"/></a>');
        var nw = $("#carousel").width()+82;
        $("#carousel").css("width",nw+"px");
    });
    carousel.size($("#carousel").children().size());
};
function loadMoreImp(carousel, state){
    $.ajax({
        type: "GET",
        url: "/ajax/watch-video.ajax.php?page="+page,
        dataType: 'json',
        error: function(){         
            showError("Oops! Upload error! Please try again.");
            return false;
        },
        success: function(data){
            if (data!=""){                               
                mycarousel_itemAddImp(carousel, carousel.first, carousel.last, data);
            }
        }          
    });
    page++;
}



function mycarousel_itemAddPetoftheWeek(carousel, first, last, data){
    var totalItems = $("#carousel").children().size();
    $.each(data,function(i,item){
        var n = i+1;
        $("<li></li>")
            .attr("class","jcarousel-item jcarousel-item-horizontal jcarousel-item-"+(totalItems+n)+" jcarousel-item-"+(totalItems+n)+"-horizontal")
            .attr("jcarouselindex",totalItems+n)
            .html('<a href="'+item.href+'"><img height="50" width="67" alt="" src="'+item.thumbnail+'"/></a>')
            .appendTo("#carousel");
        
        carousel.add(totalItems+n, '<a href="'+item.href+'"><img height="50" width="67" alt="" src="'+item.thumbnail+'"/></a>');
        var nw = $("#carousel").width()+82;
        $("#carousel").css("width",nw+"px");
    });
    carousel.size($("#carousel").children().size());
};
function loadMorePetoftheWeek(carousel, state){
    $.ajax({
        type: "GET",
        url: "/ajax/watch-video-petoftheweek.ajax.php?page="+page,
        dataType: 'json',
        error: function(){         
            showError("Oops! Upload error! Please try again.");
            return false;
        },
        success: function(data){
            if (data!=""){                               
                mycarousel_itemAddImp(carousel, carousel.first, carousel.last, data);
            }
        }          
    });
    page++;
}









$(document).ready(function() {
    $("a[rel='ext']").each(function(){
        $(this).attr("target","_blank");
        $(this).attr("title","This link will open in a new window/tab.");
    });

    // For testing...
    //alert('window height= ' + $(window).height() + '\ncontainerMain height= ' + ($('#containerMain').height() + 283));
    
    // We need to play with the footer a little. It must always appear to either sit at the bottom of the browser window or the document depending on which is higher. See function below $(document).ready().
    //positionFooter();
    
    // The footer positioning happens onLoad. We also need to make sure it occurs if the window is resized.
    //$(window).resize(positionFooter);
    
    // We are using jCarousel for the image scroller on the homepage.
    if ($('body').attr('id') == 'home'){
        $('#carousel').jcarousel();         
    }
    if ($('body').hasClass('hasCarousel')){          
        $('#carousel').jcarousel();
        $("#carousel LI A").click(function(){
            var clickedImage=$(this).find("img").attr("id").replace(/thumbImage/,"bigImage");         
            $("#flashContainer IMG").each(function(){
                if($(this).css("display")!="none") $(this).slideUp();
            })
            $("#"+clickedImage).slideDown();
            return false;
        });
    }
    if ($('body').attr('class') == 'awards'){
        $('#carousel').jcarousel({                 
            buttonNextCallback: loadMoreItems
        });        
    }
    if ($('body').attr('class') == 'allImpressions') {
        $('#carousel').jcarousel({                 
            buttonNextCallback: loadMoreImp
        });        
    }
	if ($('body').hasClass('potwScroller')) {
        $('#carousel').jcarousel({                 
            buttonNextCallback: loadMorePetoftheWeek
        });        
    }
    if ($('body').attr('id') == 'tellUsWhyWin' || $('body').attr('id') == 'tellUs' || $('body').attr('id') == 'tellUsOops' || $('body').attr('id') == 'tellUsThanks' || $('body').attr('id') == 'watchVideo' || $('body').attr('id') == 'a-zVideo') {
        
        function thisMovie(movieName) {
            if (navigator.appName.indexOf("Microsoft") != -1) {
                return window[movieName];
            } else {
                return document[movieName];
            }
        }
        function playFLV(flvUrl) {
            thisMovie("VideoPlayerComponent").playFLV(flvUrl);
        }
        function loadFLV(flvUrl) {
            thisMovie("VideoPlayerComponent").loadFLV(flvUrl);
            thisMovie("VideoPlayerComponent").loadOverlay(overlayImagePath);
            videoLoaded = true;
        }
        function stopFLV() {
            thisMovie("VideoPlayerComponent").stopFLV();
        }
        function showProcessing() {
            thisMovie("VideoPlayerComponent").showProcessing();
        }
        function showError(message) {
            thisMovie("VideoPlayerComponent").showError(message);
        }
      
        window.onload = function() {
            var section;
            if ($("body").hasClass("bodyAwards")) {
                section = "petawards2009";
            }
            if ($("body").hasClass("petOfTheWeekPlayer")) {
                section = "petoftheweek";
            }
            else {
                throw new Exception("can't identify section");
            }
            if (mediaType == 'video') {
                if (checkTranscodeStatus) {
                    showProcessing();
                    var pollHandle = null;
                    var pollForTranscodeCompletion = function() {
                        $.ajax({
                            type: "GET",
                            url: "/ajax/get-transcode-status.php?section="+section,
                            dataType: 'text',
                            error: function(){         
                                showError("Oops! Upload error! Please try again.");
                                return false;
                            },
                            success: function(data) {
                                switch (data) {
                                    case "done":
                                        clearInterval(pollHandle);
                                        loadFLV(mediaUrl);
                                        break;
                                    case "timeout":
                                        showError("Oops! We still haven't processed your video!");
                                        break;
                                    case "error":
                                        showError("Oops! Your file is a bit funny! We can't quite work out what type of video or image file you have sent us.");
                                        clearInterval(pollHandle);
                                        break;
                                    case "incomplete":
                                        // still waiting
                                        break;
                                    default:
                                        showError("Unexpected response: " + data);
                                        break;
                                }
                            }
                        });
                    }
                    pollHandle = setInterval(pollForTranscodeCompletion, 1000);
                }
                else {
                    loadFLV(mediaUrl);
                }
            }
        };
        
    }
    
    // Inserts a lightbox container dynamically.
    if (($('body').attr('id') == 'animpressionsGeneric') || ($('body').attr('id') == 'a-zForm') || ($('body').attr('id') == 'aboutAwards')){
        $('#wrapper').after(
                                                                
            '<div id="lightBoxBg"></div>' + 
            '<div id="lightBoxContainer">' +
                '<div id="lightBox">' +
                '</div>' +
            '</div>'
            
        );              
        $('.lb').click(function() {
            
            var url = this.href;               
            $('#lightBox').load(url + ' .overlay', function() {
            
                $('#lightBox').find('#lrgContainer').append('<span id="close"></span>')
                $(document).scrollTop(0);
                        
                $('#lightBoxBg').height($(document).height());
                $('#lightBoxBg').css('opacity', '0.5').fadeIn('slow');
                $('#lightBoxContainer').fadeIn('slow');
                $('#lightBox').css('margin-top', ($('#content').position().top));
                if($(document).height() > $('#lightBox').height()) {
                    $('#lightBoxBg').height($(document).height());                                               
                } else {
                    $('#lightBoxBg').height($('#lightBox').height());
                }
                
                $('#close').click(function() {
                                        
                    $('#lightBoxBg').fadeOut('slow');
                    $('#lightBoxContainer').fadeOut('slow');
                    return false;
                        
                });                    
            });                
            return false;
                
        });
        
    }

    if ($('body').attr('id') == 'watchVideo' && $('body').attr('class') != 'awards') {
        $('#rateThis').load('rate-this.php .rateThisContent', function(){
                                                                      
            var clicked = false;                                                            
                                                                      
            $('.rateThisContent h1').after(
                '<div id="rate">' +
                    '<ul></ul>' +
                '</div>'
            );          
            
            $('.rateThisContent input[type="radio"]').each(function() {
                var listTxt = $(this).attr('value');
                $('.rateThisContent ul').append(
                    '<li><span>' + listTxt + '</span></li>'
                );
                $(this).hide();
                $(this).next().hide();
            });
            $('.rateThisContent input[type="submit"]').hide();
            
            // Grabbing the average rating from a cookie.
            var youR = get_cookie("petoftheweek_yourated");
            
            if (youR) {
                
                var u = youR.split(',');
                
                for (var i = 0; i < u.length; i++) {
                    var u2 = u[i].split('=');
                    //u2[0] = id of video or photo
                    //u2[1] = rating
                    if (u2[0] == id) {
                        $('#rateThis h1').text('you rated this');
                        $('.rateThisContent ul').css('background-position', '0 -' + (u2[1] * 28) + 'px');
                        $('#rate').append('<div id="blockRate"></div>');
                        $('#blockRate').css('opacity', '0').show();        
                        $('#rating img').hide();
                    }
                }
                
            }
            
            $('.rateThisContent ul li').hover(
                function() {
                    var rating = $(this).text();
                    $('.rateThisContent ul li').each(function(i) {
                        if ($(this).text() == rating) {
                            $(this).parent().css('background-position', '0 -' + ((i + 1) * 28) + 'px');
                        }                                                   
                    });
                },
                function() {
                    if(!(clicked)) {
                        $(this).parent().css('background-position', '0 0');
                    }
                }
            );
            
            $('.rateThisContent ul li').click(function() {
                var post = 'rating= ' + $(this).text() + "&id=" + id;
                $.ajax({
                    type: 'POST',
                    url: '/ajax/rate-this-petoftheweek.ajax.php',
                    data: post,
                    dataType: 'json',
                    error: function(){         
                        alert('Unexpected response!');
                        return false;
                    },
                    success: function(ratingData) {
                        $('.rateThisContent ul li').each(function(i) {
                            if (parseInt($(this).text()) == ratingData.rating) {
                                $(this).parent().css('background-position', '0 -' + ((i + 1) * 28) + 'px');
                                clicked = true;
                            }                                                   
                        });
                        $('#rateThis h1').text('you rated this');
                        $('#rate').append('<div id="blockRate"></div>');
                        $('#blockRate').css('opacity', '0').show();
                        $('#rating img').hide();
                        $('#currentRating p').text(ratingData.numVoters + " voters");
                        $('.stars span').fadeOut('fast', function() {
                            $(this).attr('id', 'avg' + (ratingData.avg).toString().replace(".", "-"));
                            $(this).fadeIn('fast');
                        });
                    }
                });
                return false;
            });
            
        });
    }
    
    if ($('body').attr('id') == 'watchVideo' && $('body').attr('class') == 'awards') {
        
        $('#rateThis').load('rate-this.php .rateThisContent', function(){
                                                                      
            var clicked = false;                                                            
                                                                      
            $('.rateThisContent h1').after(
                '<div id="rate">' +
                    '<ul></ul>' +
                '</div>'
            );          
            
            $('.rateThisContent input[type="radio"]').each(function() {
                var listTxt = $(this).attr('value');
                $('.rateThisContent ul').append(
                    '<li><span>' + listTxt + '</span></li>'
                );
                $(this).hide();
                $(this).next().hide();
            });
            $('.rateThisContent input[type="submit"]').hide();
            
            // Grabbing the average rating from a cookie.
            var youR = get_cookie("petawards2009_yourated");
            
            if (youR) {
                
                var u = youR.split(',');
                
                for (var i = 0; i < u.length; i++) {
                    var u2 = u[i].split('=');
                    //u2[0] = id of video or photo
                    //u2[1] = rating
                    if (u2[0] == id) {
                        $('#rateThis h1').text('you rated this');
                        $('.rateThisContent ul').css('background-position', '0 -' + (u2[1] * 28) + 'px');
                        $('#rate').append('<div id="blockRate"></div>');
                        $('#blockRate').css('opacity', '0').show();        
                        $('#rating img').hide();
                    }
                }
                
            }
            
            $('.rateThisContent ul li').hover(
                function() {
                    var rating = $(this).text();
                    $('.rateThisContent ul li').each(function(i) {
                        if ($(this).text() == rating) {
                            $(this).parent().css('background-position', '0 -' + ((i + 1) * 28) + 'px');
                        }                                                   
                    });
                },
                function() {
                    if(!(clicked)) {
                        $(this).parent().css('background-position', '0 0');
                    }
                }
            );
            
            $('.rateThisContent ul li').click(function() {
                var post = 'rating= ' + $(this).text() + "&id=" + id;
                $.ajax({
                    type: 'POST',
                    url: '/ajax/rate-this-awards.ajax.php',
                    data: post,
                    dataType: 'json',
                    error: function(){         
                        alert('Unexpected response!');
                        return false;
                    },
                    success: function(ratingData) {
                        $('.rateThisContent ul li').each(function(i) {
                            if (parseInt($(this).text()) == ratingData.rating) {
                                $(this).parent().css('background-position', '0 -' + ((i + 1) * 28) + 'px');
                                clicked = true;
                            }                                                   
                        });
                        $('#rateThis h1').text('you rated this');
                        $('#rate').append('<div id="blockRate"></div>');
                        $('#blockRate').css('opacity', '0').show();
                        $('#rating img').hide();
                        $('#currentRating p').text(ratingData.numVoters + " voters");
                        $('.stars span').fadeOut('fast', function() {
                            $(this).attr('id', 'avg' + (ratingData.avg).toString().replace(".", "-"));
                            $(this).fadeIn('fast');
                        });
                    }
                });
                return false;
            });
            
        });
    }
    $('#sendit').click(function() {
        var validFields = 0;
        
        if ($('#upload').attr('value') == '') {
            $('#upload').prev().addClass('error');
        } else {
            $('#upload').prev().removeClass('error');
            validFields++; 
        }
        
        if ($('#confirm').attr('checked') == false) {
            $('#confirm').next().addClass('error'); 
        } else {
            $('#confirm').next().removeClass('error');
            validFields++; 
        }
        
        if (validFields == 2) {
            $(this).attr('disabled', 'true');
            $(this).css('cursor', 'default');
            $(this).prev().html('Uploading, <strong>please wait</strong>...');
            $('#uploadFrm').submit();
        }
        
        return false;
    });
    
    $('#searchText').focus(function() {
        if ($(this).attr('value') == 'Enter name') {
            $(this).attr('value', '');  
        }
    });
    
    // Rollover on "find" submit button.
    $('#findSubmit, #next').hover(
        function() {
            $(this).css('background-position', '0 -57px');
        },
        function() {
            $(this).css('background-position', '0 0');
        }
    );
    $('.hoverThis').hover(
        function() {
            myUrl = $(this).attr('src');
            myUrl = myUrl.substring(0,myUrl.length-4);
            myUrl += "-over.png";
//                  alert(myUrl);
            $(this).attr('src',myUrl);
        },
        function() {
            myUrl = $(this).attr('src');
            myUrl = myUrl.substring(0,myUrl.length-9);
            myUrl += ".png";
//                  alert(myUrl);
            $(this).attr('src',myUrl);
        }
    );
			if ($('UL').hasClass('frameThumbs')) {
				
				jQuery.preloadImages = function() {
				  for (var i = 0; i<arguments.length; i++) {
					jQuery("<img>").attr("src", arguments[i]);
				  }
				}
				
				$.preloadImages("/images/frame-none.png", "/images/frame-snowman.png", "/images/frame-holly.png", "/images/frame-gifts.png");
				
				$('#frameThumbs LI INPUT').click(function() {
					var frame = $(this).attr('name').split('_')[1];
					
					$('#frameThumbs LI INPUT').each(function() {
						$(this).removeClass('on');									   
					});
					
					$(this).addClass('on')
                    overlayImagePath = '/images/frame-' + frame + '.png';
					$('#frame DIV').css('background', 'url(' + overlayImagePath + ')');
					$('#frameChoice').attr('value', frame);
					
                    if (videoLoaded) {
                        thisMovie("VideoPlayerComponent").loadOverlay(overlayImagePath);
                    }

					return false;
				});
			}
    
});
function get_cookie ( cookie_name )
{
    var results = document.cookie.match ( '(^|;) ?' + cookie_name + '=([^;]*)(;|$)' );

    if ( results )
        return ( unescape ( results[2] ) );
    else
        return null;
}

function callJSTracker(){
    $.ajax({
    type: "GET",
    url: "/virtual-puppy-download-tracking.php",
    dataType: 'text',          
    success: function(data) {}
    });        
}
