var addthis_disable_flash = true;

function page_path() {
    var url = location.href.toString();
        url = url.split('?');
        url = url[0].split('/');
        
    var new_url = '/';

    for(var i = 3; i < url.length; i++) {
        new_url += url[i] + '/';
    }
    
    url = new_url.split('#')[0];
    
    if( url.charAt( url.length - 1) != '/' ) {
        url += '/';
    }

    return url.replace('.html/', '.html');
}

function show_error(trigger, message) {

    var position  = trigger.offset();
        position.top  += 10;
        position.left += trigger.width() + 5;

    $('#bubble-message .message-text').text(message);
    $('#bubble-message').css({ top : position.top + 'px', left : position.left + 'px' }).show();
    trigger.addClass('error').removeClass('valid');
}

function hide_error(trigger) {
    trigger.addClass('valid').removeClass('error');
}

function show_panel(panel_id) {
    var show = false;

    $('.top-nav a, a.close-panels').each(function(){
        if( $(this).hasClass('selected') )
            $(this).removeClass('selected');
    });

    $('.header-panels').children().each(function(){
        if( this.id == panel_id && $(this).css('display') == 'none' ) {
            $(this).slideDown();
            show = true;
        } else {
            $(this).slideUp();
        }
    });
    
    return show;
}

function refered_from_award_page() {
    var refer = document.referrer.toString();
    var url   = location.href.toString();
    
    var clean_url   = url.split('/');
    
    url = '';

    for(var i = 0; i < clean_url.length - 2; i++) {
        url += clean_url[i] + '/';
    }

    if( url == refer )
        return true;
    else
        return false;
}

$(document).ready(function(){
    /* header panels */

    $('.top-nav a, a.close-panels, a.sign-up-btn').live('click', function() {
        // show selected panel, hide others
        var panel_id = $(this).attr('href').split('#');
            panel_id = panel_id[1];

        var show  = show_panel(panel_id);

        if( show ) $(this).addClass('selected');
        
        if( $(this).hasClass('top-nav-links') && show )
            $('#second-nav').css({ paddingTop : '20px' });
        else
            $('#second-nav').css({ paddingTop : '' });
            
        return false;
    });
    
    // search form
    $('#search-form').bind('submit', function(e){
    
        if( $('#search-results').css('display') == 'none' )
            show_panel('none');
        else {
            $('#search-results').css({ height : $('#search-results').height() + 'px', overflow : 'hidden' });
        }

        $('#search-results').load('/search.html?ajax=true&' + $('#search-field').serialize(), function(){
            if( $('#search-results').css('display') == 'none' )
                show_panel('search-results');
            else
                $('#search-results').animate({ height : $('#search-results>div').height() + 'px' }).animate({ overflow : 'auto' });
        });

        return false;
    });

    $('input#search-field').val('Search').css({ color : '#999'});

    $('input#search-field').focus(function(){
        if( $(this).val() == 'Search' ) {
            $(this).val('').css({ color : ''});
        }
    });

    $('input#search-field').blur(function(){
        if( $(this).val() == '' )
            $(this).val('Search').css({ color : '#999'});
    });
    
    // contact form
    $('#contact-form').submit(function(){

        var valid_form = true;

        if( jQuery.trim($('#contact-form input[name="email.name"]').val()) == '' ) {
            show_error($('#contact-form input[name="email.name"]'), 'please provide your name');
            valid_form = false;
        } else 
            hide_error($('#contact-form input[name="email.name"]'));

        if( jQuery.trim($('#contact-form textarea').val()) == '' ) {
            show_error($('#contact-form textarea'), 'please provide your name');
            valid_form = false;
        } else
            hide_error($('#contact-form textarea'));

        if( !valid_email($('#contact-form input[name="email.email"]').val()) ) {
            show_error($('#contact-form input[name="email.email"]'), 'please provide a valid email');
            valid_form = false;
        } else
            hide_error($('#contact-form input[name="email.email"]'));
        
        if( valid_form ) {
            $.post('/contact_email.json', $('#contact-form').serialize(), function(){

            });
        }
        
        return false;
    });

    $('#nominees a').bind('click', function(e){
        $('#search-results').load( $(this).attr('href') + '&ajax=true', function(){
            show_panel('search-results');
        });

        return false;
    });
    
    
    /* forgot pass */
    $('.button.forgot-pass-btn').bind('click', function(){
        var url = '/users/' + $('form#login input[name="login"]').val() + '/forgot_password.json';

        $.getJSON(url, function(response) {
            if( !response.success ) {
                show_error(trigger, response.message);
            } else {
                hide_error(trigger);
            }
        });
    });

    /* header panels end */
    
    /* search results */
    $('a.search-year, a.award-categories').live("click", function(){

        var panel_id = $(this).attr('href').split('#');
            panel_id = panel_id[1];

        if( $('#results_' + panel_id).css('display') == 'none' ) {
            $('#results_' + panel_id).slideDown();
            $(this).children('span').removeClass('hidden');

            if( $(this).hasClass('award-categories') ) {
                $(this).find('span').text('Click to hide categories');
                $.post('/session_vars.json', { category_state : '' });
            }

        } else {
            $('#results_' + panel_id).slideUp();

            if( $(this).hasClass('award-categories') ) {
                $(this).find('span').text('Click to show categories');
                $.post('/session_vars.json', { category_state : 'hidden' });
            }
            
            $(this).children('span').addClass('hidden');
        }
        
        return false;
    });
    /* search results end */

    /* flash in homepage */
    if( $('#flash-home').length > 0 ) {
        swfobject.embedSWF("/static/swf/home.swf", 'flash-home', '945px', '260px', "8");
    }
    /* flash in homepage end */

    /* footer links */
    
    $('#footer .home-links a').click(function(e){
        $('html, body').animate({scrollTop:0}, 'slow');
        $('.top-nav a[href="' + $(this).attr('href') + '"]').click();
        return false;
    });

    /* sign up */
    $('#sign-up-form input[name="user.id"], #sign-up-form input[name="user.email"]').bind('blur focus', function(){
        // check email
        if( jQuery.trim($(this).val()) == '') {
            $('#bubble-message').hide();
            $(this).removeClass('error').removeClass('valid');
            return false;
        }

        var variables   = $(this).serialize();
        var trigger     = $(this);

        $.getJSON('/check_unique.json', variables, function(response) {
            if( !response.unique ) {
                show_error(trigger, response.message);
            } else {
                hide_error(trigger);
            }
        });
    });
    
     $('#sign-up-form input[name="user.password"]').bind('blur focus', function() {
        if( jQuery.trim($(this).val()).length < 4 && jQuery.trim($(this).val()) != '' ) {
            show_error($(this), 'Password is too short');
        } else if( jQuery.trim($(this).val()) != '' ) {
            hide_error($(this));
        }
     });

     $('#sign-up-form input[name="user.password.confirm"]').bind('blur focus', function() {
        if( $(this).val() != $('#sign-up-form input[name="user.password"]').val() && jQuery.trim($(this).val()) != '' ) {
            show_error($(this), 'Passwords do not match');
        } else if( jQuery.trim($(this).val()) != '' ) {
            hide_error($(this));
        }
     });
    /* sign up end */
    
    /* select other year */
    $('select#change-year').change(function(){
        if( $(this).val() == 0 ) return false;
        
        location.href = $(this).val();
    });

    /* favourite a video */
    $('a#favourite, a#remove-favourite').bind('click', function(){

        var add_to_fav = true;
        
        var url = page_path();

        if( $(this).attr('id') == 'favourite' )
            url += '/add_as_favourite.json'
        else {
            url += '/remove_as_favourite.json';
            add_to_fav = false;
        }

        $.getJSON(url, function(data) {
            if( typeof(data.success) != 'undefined' && data.success ) {
                jAlert(data.message, 'Success');
                
                if( add_to_fav ) {
                    $('a#favourite').hide();    $('a#remove-favourite').show();
                } else {
                    $('a#favourite').show();    $('a#remove-favourite').hide();
                }
            } else {
                jConfirm('Do you wish to log in?', data.message, function(accept) {
                    if( accept ) {
                        $('html, body').animate({scrollTop:0}, 'slow');
                        $('a.sign-up.top-nav-links').click();
                    }
                });
            }
        });
        
        return false;
    });
    /* favourite a video end */
    
    /* toggle winners and favourites */

    $('h2#fav-win-title a').bind('click', function(){

        var title = 'Winners';

        if( $(this).text().indexOf('Winners') < 0 )
            title = 'Nominees';

        if( $('#fav-list').css('display') == 'none' ) {
                
            $(this).html('<span>' + title + '</span> | Favourites').attr({ title : 'View Winners and Highly Commended', href : '#View Winners and Highly Commended'});

            $('#right-video-listing').css({ height : $('#right-video-listing').height() + 'px', overflow : 'hidden' });

            $('#winners-list, #highly-commended-list').fadeOut(500);
            
            setTimeout(function(){
                $('#fav-list').fadeIn(500);
                $('#right-video-listing').animate({ height : $('#right-video-listing>div').height() + 'px'}, 'slow');

                setTimeout(function(){
                    $('#right-video-listing').css({ height : '', overflow : ''});
                }, 1000);

            }, 550);

        } else {

            $(this).html( title + ' | <span>Favourites</span>').attr({ title : 'View Favourites', href : '#View Favourites'});

            $('#right-video-listing').css({ height : $('#right-video-listing').height() + 'px', overflow : 'hidden' });

            $('#fav-list').fadeOut(500);
            
            setTimeout(function(){
                $('#winners-list, #highly-commended-list').fadeIn(500);
                $('#right-video-listing').animate({ height : $('#right-video-listing>div').height() + 'px'}, 'slow');

                setTimeout(function(){
                    $('#right-video-listing').css({ height : '', overflow : ''});
                }, 1000);

            }, 550);
        }
        
        return false;
    });

    /* toggle winners and favourites */
    
    /* comment on a video */
    $('#submission-form').bind('submit', function(){

        if( jQuery.trim($('#submission-form textarea[name="content"]').attr('value')) == '' ) {
            // blank comment
            $('#submission-form textarea').css({ borderColor : '#ff9999' });
            jAlert('Your comment cannot be left blank', 'Sorry', function(){
                $('#submission-form textarea').focus();
            });
            return false;
        } else {
            $('#submission-form textarea').css({ borderColor : '' });
        }

        var url = page_path() + 'add_comment.json';
        var post = $(this).serialize();

        $.post(url, post, function(data) {
            if( typeof(data.success) != 'undefined' && data.success ) {
                // comment added
                var url = page_path() + 'get_comments.xml?page=1';
                var scroll_to_comment = $("#video-comments").load(url).offset().top;    // load comments
                $('html, body').animate({scrollTop:scroll_to_comment}, 'slow');         // scroll to comments
                $('#submission-form textarea').attr({ value : ''});
            } else {
                // must be logged in
                jConfirm('Do you wish to log in?', data.message, function(accept) {
                    if( accept ) {
                        $('html, body').animate({scrollTop:0}, 'slow');
                        $('a.sign-up.top-nav-links').click();
                    }
                });
            }
        }, 'json');

        return false;
    });
    /* comment on a video end */

    /* comment pagination */
    $('.video-comment-pagination a').live('click', function(){
        var page = $('.video-comment-pagination li.selected a').text();

        if( $(this).attr('href') == '#next' && page < ($('.video-comment-pagination a').length - 2 ) ) {
            page ++;
        } else if( $(this).attr('href') == '#next' ) {
            return false;
        }else if( $(this).attr('href') == '#prev' && page > 1 ) {
            page --;
        } else if( $(this).attr('href') == '#prev' ) {
            return false;
        } else {
            page = $(this).text();
        }

        var url = page_path() + 'get_comments.xml?page=' + page;

        $("#video-comments").css({ height : $("#video-comments").height() + 'px', overflow : 'hidden'});

        $("#video-comments").load(url, function() {

            $("#video-comments").animate({ height : ($("#video-comments>div").height() + 20) + 'px'}, 'slow');

            setTimeout(function(){
                $("#video-comments").css({ height : '', overflow : ''});
                var scroll_to_comment = $('#video-comments').offset().top;
                $('html, body').animate({scrollTop : scroll_to_comment}, 'slow');         // scroll to comments
            }, 1000);
        });    // load comments

        return false;
    });
    /* comment pagination end */

    /* post a comment link */
    $('a[href="#post-a-comment"]').live('click', function(){
        var scroll_to_comment = $('a[name="post-a-comment"]').offset().top;
        $('html, body').animate({scrollTop : scroll_to_comment}, 'slow');         // scroll to comments
        $('#submission-form textarea').focus();
        return false;
    });
    /* post a comment link end */

    /* flag a comment */
    $('a.flag-btn').live('click', function(){
        var num      = $(this).attr('href').split('?id=')[1];
        var username = $('.comment.number-' + num + ' .who').html();
            username = jQuery.trim(username.split('<span>')[0]);

        var trigger = $(this);

        jConfirm('Are you sure you want to flag ' + username + '\'s comment', 'Flag comment', function(accept) {
            if( accept ) {
                var url = page_path() + 'flag_comment.json?id=' + num;

                $.getJSON(url, function(response) {
                    if( response.success)
                        // jAlert('The comment has been flagged.', 'Success');
                        trigger.replaceWith('<span class="flagged"></span>');
                    else {
                        jConfirm('Do you wish to log in?', response.message, function(accept) {
                            if( accept ) {
                                $('html, body').animate({scrollTop:0}, 'slow');
                                $('a.sign-up.top-nav-links').click();
                            }
                        });
                    }
                        
                });
            }
        });

        return false;
    });
    /* flag a comment end */
    
    /* select input area for share embed codes */
    $('.share-embed input[readonly="readonly"]').bind('focus click', function(){
        this.select();
    });
    /* select input area for share embed codes end */

    /* admin */
    $('.check-next').bind('change', function(){
        if( !$(this).attr('checked') ) {
            $(this).parent().next().find('input[type="checkbox"]').each(function(){
                $(this).removeAttr('checked');
            });
        }
    });
    
    $('.ad-indent input[type="checkbox"]').bind('change', function() {
        if( $(this).attr('checked') ) {
            $(this).parent().parent().parent().prev().find('.check-next').attr('checked', true);
        }
    });
    

    /* rating */
    $(function(){ // wait for document to load 
        $('input.rating').rating({
            half : true,
            callback: function(value, link){ 
                $.getJSON(page_path() + 'rate.json?value=' + value, function(response) {
                    if( !response.success ) {
                        jConfirm('Do you wish to log in?', response.message, function(accept) {
                            if( accept ) {
                                $('html, body').animate({scrollTop:0}, 'slow');
                                $('a.sign-up.top-nav-links').click();
                            }
                        });
                    } else {
                        $('.not-rated-star').text('Thank you for rating');
                    }
                });
            }
        });
    });
    
    $('.rated-star').mouseover(function(){

        if( $.browser.mozilla && jQuery.browser.version.substr(0,3) == '1.9')
            $('.rated-star span:first-child').text('You rated').css({ cursor : 'default', marginRight : '8px'});
        else
            $('.rated-star span:first-child').text('You rated').css({ cursor : 'default', marginRight : '7px'});
        
        $('.rated-star span.star-rating-control').find('.star-rating').each(function(count){
            if( count < i_rated )
                $(this).addClass('star-rating-on');
            else
                $(this).removeClass('star-rating-on');
        });

    });

    $('.rated-star').mouseout(function(){
        $('.rated-star span:first-child').text('Rating').css({ marginRight : ''});
        
        $('.rated-star span.star-rating-control').find('.star-rating').each(function(count){
            if( count < rating )
                $(this).addClass('star-rating-on');
            else
                $(this).removeClass('star-rating-on');
        });

    });
    /* rating end */
    
    /* add this code - add at the end so that the load time is not affected */
    $('.add-this').html('<a class="addthis_button" href="http://www.addthis.com/bookmark.php?v=250&amp;pub=xa-4ad6edab2bc626a2"><img src="http://s7.addthis.com/static/btn/v2/lg-addthis-en.gif" width="125" height="16" alt="Bookmark and Share" style="border:0"/></a><script type="text/javascript" src="http://s7.addthis.com/js/250/addthis_widget.js#pub=xa-4ad6edab2bc626a2"></script>')
    /* add this end */
    
    $('#judge-comments').click(function(){
        var save_html = $('#video-info').html();
        $('#video-info').html($('#hidden-text-comments').html());
        $('#hidden-text-comments').html(save_html);

        var scroll_to_comment = $("#top").offset().top;    // load comments
        $('html, body').animate({scrollTop:scroll_to_comment}, 'slow');         // scroll to comments
        
        if( $(this).text() == 'Judges comments' )
            $(this).text('Nominee description');
        else
            $(this).text('Judges comments');

        return false;
    });

});

function valid_email(strEmail){
    validRegExp = /^[^@]+@[^@]+.[a-z]{2,}$/i;

    if (strEmail.search(validRegExp) == -1)  {
        return false;
    } else
        return true; 
}

largeBlueVideo.onResize = function() {
    if( $('#video-player').width() == 800 ) {
        $('#video-info').addClass('video-info-side');
        $('.share-embed.in-info').css({display : 'none'});
        $('.right-half.share-embed').css({display : ''});
        $.post('/session_vars.json', { quality: 'hi', format: 'mp4' } );

    } else {
        $('#video-info').removeClass('video-info-side')
        $('#flash-video').css({width : ''});
        $('.share-embed.in-info').css({display : ''});
        $('.right-half.share-embed').css({display : 'none'});
        
        $.post('/session_vars.json', { quality: 'lo', format: 'mp4' } );
    }
}