function com_weatherbynation_399Video_doShowPlayer(vid) {
    // Don't load the same video twice
    var continueLoading = true;
    if( vid == $('#vid').val() ) {
        continueLoading = false;
    }

    // Check that we're on the browse interface
    if( $('#videoBrowse').length == 0 && continueLoading ) {
        window.location.href='/videocontest/browse/view/'+vid;
    }
    else if(continueLoading) {
        // Hide existing and show loading div
        $('#videoBrowse .video , #videoBrowse .videoDetails').hide();
        $('#videoBrowse .video-loading').show();
        $('#vid').val(vid);

        // Request video details and show the video
        $.getJSON(
            '/videocontest/ajax/view/' + vid + '?_requesttype=text/javascript',
            function(json) {
                if(json.status != "ok") {
                    window.alert(json.status);
                    $('#videoBrowse .video-loading').hide();
                    $('#videoBrowse .video , #videoBrowse .videoDetails').hide()
                }
                else {
                    function zeroPad(num) {
                        return num < 10 ? "0" + num : num;
                    }

                    // Embed code
                    var embedCode = '<object width="480" height="488"><param name="movie" value="http://'+window.location.hostname+'/_swf/wiwaw_embed_yt_vp.swf?submissionid=' +vid +'"></param><param name="allowFullScreen" value="true"></param><embed src="http://'+window.location.hostname+'/_swf/wiwaw_embed_yt_vp.swf?submissionid='+ vid +'" type="application/x-shockwave-flash" allowfullscreen="true" width="480" height="488"></embed></object>';
                    $('#detail-embed').val(embedCode);

                    // Title
                    $('#detail-title').html(json.data.title);

                    // Duration
                    if(parseInt(json.data.ytDuration) != 0) {
                        var minutes = Math.floor(json.data.ytDuration/60);
                        var seconds = json.data.ytDuration % 60;
                        var duration = zeroPad(minutes) + ':' + zeroPad(seconds);
                    }
                    else {
                        var duration = "N/A";
                    }
                    $('#detail-runtime').html(duration);

                    // Date added
                    var added = new Date(json.data.added * 1000)
                    var addedDate = zeroPad((added.getMonth() + 1)) + '/' + zeroPad(added.getDate()) + '/' + zeroPad(added.getFullYear());
                    var addedAP = "am";
                    var addedHour = added.getHours();
                    if( addedHour == 0 ) addedHour = 12;
                    if( addedHour > 11 ) addedAP = "pm";
                    if( addedHour > 12 ) addedHour -= 12;
                    var addedTime = zeroPad(addedHour) + ':' + zeroPad(added.getMinutes()) + addedAP;
                    $('#detail-added').html(addedDate + ' ' + addedTime);

                    // Author
                    $('#detail-posted').html(json.data.author);

                    // Votes
                    $('#detail-votes').html(json.data.votes);

                    // Render the video player
                    var flashvars = {
                        submissionid: vid
                    };
                    var params = {
                        menu: "false",
                        quality: "high",
                        scale: "noscale",
                        wmode: "transparent"
                    };

                    swfobject.embedSWF("/_swf/wiwaw_yt_vp.swf", "flash-399video-video", '480', "405", "8.0.0", "/_ui/srawn/swf/expressinstall.swf", flashvars, params);

                    // Hide loader and show everything
                    $('#videoBrowse .video-loading').hide();
                    $('#videoBrowse .video , #videoBrowse .videoDetails').show()
                }
            }
        );
    }
}

function com_weatherbynation_399Video_latest(width) {
    var flashvars = {};
    var params = {
        menu: "false",
        quality: "high",
        scale: "noscale",
        wmode: "transparent"
    };
    var randomValueForCache = new Date().getTime();

    $.getJSON(
        '/videocontest/ajax/latest/5?_requesttype=application/json',
        function(json) {
            if(json.data.length > 0) {
                // If results, show Flash
                $('#videoContestLatest').show();
                if(canVote == 1) {
                    swfobject.embedSWF("/_ui/srawn/swf/wiwaw_video_thumb_vote.swf?t="+randomValueForCache, "flash-399video-latest", width, "210", "8.0.0", "/_ui/srawn/swf/expressinstall.swf", flashvars, params);
                }
                else {
                    swfobject.embedSWF("/_ui/srawn/swf/wiwaw_video_thumb_novote.swf?t="+randomValueForCache, "flash-399video-latest", width, "210", "8.0.0", "/_ui/srawn/swf/expressinstall.swf", flashvars, params);
                }
            }
            else {
                $('#videoBrowseLatest').hide();
            }
        }
    );

}

function com_weatherbynation_399Video_prizes() {
    var flashvars = {};
    var params = {
        menu: "false",
        quality: "high",
        scale: "noscale",
        wmode: "transparent"
    };

    swfobject.embedSWF("/_swf/wiwaw_prizes.swf", "flash-399video-prizes", "600", "249", "8.0.0", "/_ui/srawn/swf/expressinstall.swf", flashvars, params);
}

function com_weatherbynation_399Video_GPTour() {
    var flashvars = {};
    var params = {
        menu: "false",
        quality: "high",
        scale: "noscale",
        wmode: "transparent"
    };

    swfobject.embedSWF("/_ui/srawn/swf/wiwaw_photos.swf", "flash-399photo-GPTour", "600", "450", "8.0.0", "/_ui/srawn/swf/expressinstall.swf", flashvars, params);
}

function com_weatherbynation_399Video_upload() {
    var flashvars = {};
    var params = {
        menu: "false",
        quality: "high",
        scale: "noscale",
        wmode: "transparent"
    };

    swfobject.embedSWF("/_swf/wiwaw_entry_form.swf", "flash-399video-submit", "600", "500", "8.0.0", "/_ui/srawn/swf/expressinstall.swf", flashvars, params);
}

function com_weatherbynation_399Video_curtain() {
    if( $('#message-399video-curtain').length > 0) {
        // Curtain exists, remove and hide elements
        $('#message-399video-curtain').remove();
        $('#message-399video-vote').hide();
        $('#message-399video-fail').hide();
        $('#message-399video-share').hide();
    }
    else {
        // No curtain, create and bind
        $('#videoBrowse').after('<div id="message-399video-curtain"></div>');
        $('#message-399video-curtain').show().css('height', $('#main').height()+305+'px').css('width', $(document).width()+'px');
        $('#message-399video-curtain').unbind().click(function() {
            com_weatherbynation_399Video_curtain();
            return false;
        });
    }
}

function com_weatherbynation_399Video_share() {
    com_weatherbynation_399Video_curtain();
    $('#message-399video-share').show();

    // Close
    $('#message-399video-share a.close').unbind().click(function() {
        com_weatherbynation_399Video_curtain();
        return false;
    });

    // Send
    $('#message-399video-share a.send').unbind().click(function() {
        $('#message-399video-share form').addClass('loading');
        $.post(
            '/videocontest/ajax/share',
            {
                from_name: $('#shareName').val(),
                to_email: $('#shareAddresses').val(),
                message: $('#shareMessage').val(),
                video_id: $('#vid').val()
            },
            function(data) {
                var data = eval('(' + data + ')');
                $('#message-399video-share form').removeClass('loading');
                if(data.status == "ok") {
                    $('#message-399video-share dd input , #message-399video-share dd textarea').val('');
                    com_weatherbynation_399Video_curtain();
                    window.alert('Message sent!');
                }
                else if(data.status != "") {
					window.alert(data.status);
				}
                else {
                    window.alert('There was a problem sending your message.')
                }
            }
        );
        return false;
    });
}

function com_weatherbynation_399Video_vote(uid, vid) {
    com_weatherbynation_399Video_curtain();
    $('#message-399video-vote').show();

    // Cancel button
    $('#message-399video-vote a.close , #message-399video-vote a.cancel').unbind().click(function() {
        com_weatherbynation_399Video_curtain();
        return false;
    });

    // Vote button
    $('#message-399video-vote a.vote').unbind().click(function() {
        $.getJSON(
            '/videocontest/ajax/vote/' + vid + '?_requesttype=text/javascript',
            function(json) {
                if( json.status != "ok" ) {
                    com_weatherbynation_399Video_curtain();
                    com_weatherbynation_399Video_curtain();
                    $("#399video-vote-failure-message").text(json.status);
                    $('#message-399video-fail').show();
                    $('#message-399video-fail a.close').unbind().click(function() {
                        com_weatherbynation_399Video_curtain();
                        return false;
                    });
                } else {
                	com_weatherbynation_399Video_curtain();
                }
            }
        );

        return false;
    });
}

function com_weatherbynation_399Video_entries(url) {
    if( $('#videoBrowseEntries div.table').children().length > 0 ) {
        $('#videoBrowseEntries').find('div.table').addClass('loading');
        $('#videoBrowseEntries > div.pages').remove();
        $('#videoBrowseEntries div.table').empty();
    }
    if( typeof(url) == "undefined" ) {
        var url = "/videocontest/ajax/browse";
    }

    // Load table markup
    $('#videoBrowseEntries div.table').load(
        url,
        function() {
            com_weatherbynation_399Video_entries_pages();
            $('#videoBrowseEntries div.table').removeClass('loading');

            // Sort fields
            $('#videoBrowseTable a.sort').unbind().click(function() {
                var url = '/videocontest/ajax/browse?' + $('#videoBrowseTableQuery').val();
                com_weatherbynation_399Video_entries(url + '&orderBy=' + $(this).attr('rel'));
                return false;
            });

            // Search box
            $('#videoBrowseTable a.searchLink').unbind().click(function() {
                $('#videoBrowseEntriesSearch').toggle();
                return false;
            });
            $('#videoBrowseEntriesSearch form').unbind().submit(function() {
                var url = '/videocontest/ajax/browse?' + $('#videoBrowseTableQuery').val();
                com_weatherbynation_399Video_entries(url + '&author=' + $('#videoBrowseEntriesSearch input').val() );
                return false;
            });
            $('#videoBrowseEntriesSearch a.search').unbind().click(function() {
                $('#videoBrowseEntriesSearch form').trigger('submit');
                return false;
            });
            $('#videoBrowseEntriesSearch a.close').unbind().click(function() {
                $('#videoBrowseEntriesSearch').hide();
                return false;
            });

            // Item links
            $('#videoBrowseTable a.itemLink').unbind().click(function() {
                var sid = $(this).attr('href').replace(/.*\/view\//, '');
                com_weatherbynation_399Video_doShowPlayer(sid);
                return false;
            });

            // Load default table
            $('#videoBrowseEntries a.returnToDefault').unbind().click(function() {
                com_weatherbynation_399Video_entries('/videocontest/ajax/browse');
                return false;
            });
        }
    );
}

function com_weatherbynation_399Video_entries_pages() {
    $('#videoBrowseEntries div.table div.pages').insertAfter('#videoBrowseEntries > h3');
    $('#videoBrowseEntries div.table div.pages').remove();
    $('#videoBrowseEntries > div.pages').find('a').each(function() {
        if( $(this).text() == ">>" ) {
            $(this).addClass('nextBtn');
        }
        if( $(this).text() == "<<" ) {
            $(this).addClass('prevBtn');
        }
        $(this).click(function() {
            var href = $(this).attr('href').replace(/\?q\=videocontest\/ajax\/browse/, '?').replace(/\&\&/, '&').replace(/\?\&/, '?');
            com_weatherbynation_399Video_entries(href);
            return false;
        });
    });
}

$(document).ready(function() {
    // Miscellaneous
    $('#detail-embed').focus(function() {
        document.getElementById('detail-embed').select();
    });
	$('#videoContestHome .introduction').addClass('jsmargins');
	$('#videoContestHome .left p:last-child , #videoContestHome .bottom p:last-child').addClass('last-child');

    // Voting
    if( $('#videoBrowse').length > 0 ) {
        $('#videoBrowse .videoDetails a.vote').click(function() {
            com_weatherbynation_399Video_vote( $(this).attr('rel'), $('#vid').val() );
            return false;
        });
    }

    // Latest Entries
    if( $('#videoContestHome').length > 0 ) {
        com_weatherbynation_399Video_latest('600');
    }
    if( $('#videoBrowse').length > 0 ) {
        com_weatherbynation_399Video_latest('845');
    }

    // Entry Form
    if( $('#videoContestForm').length > 0 && $('#flash-399video-submit').length > 0 ) {
        com_weatherbynation_399Video_upload();
    }

    // Prizes
    if( $('#videoContestHome').length > 0 ) {
        com_weatherbynation_399Video_prizes();
    }
    
    // Ceremony
    if( $('#videoContestGPTour').length > 0 ) {
    	com_weatherbynation_399Video_GPTour();
    }

    // All Entries
    if( $('#videoBrowse').length > 0 ) {
        com_weatherbynation_399Video_entries();
    }
});
