/*
 * Copyright (c) 2008 sk89q <http://sk89q.therisenrealm.com>
 * All rights reserved.
*/

//-------------------------------
// Initialize tabs
//-------------------------------

$(document).ready(function() {
    // Ads check
    if ($('#ad-b > iframe').length == 0) {
        $('#ad-b').append($('<img src="/images/block_message.png" alt="Please disable your ad blocker" />'));
    }
    
    // Make tabs
    $("div.tabbed > ul").tabs();
    $("div.tabbed > div > h2").css('display', 'none');
    
    // Hover images
    $("img.hover-image")
        .mouseover(function(event) {
            $(event.target).attr('src', $(event.target).attr('src').replace(/_(up|down)\./g, '_over.'));
        })
        .mouseout(function(event) {
            $(event.target).attr('src', $(event.target).attr('src').replace(/_(over|down)\./g, '_up.'));
        });
    
    // Thumbnails
    $("a[href*='design?designId']").add("a[href*='level?levelId']").mopTip({
        'w': 150+8,
        'h': 150+8,
        'delay': 200,
        'style': "overOut",
        'get': function(event) {
            if (!$(event.target).attr('href')) {
                return false;
            }
            var url = $(event.target).attr('href');
            var m;
            if (m = url.match(/(level|design)Id=([0-9]+)/)) {
                var type = m[1];
                var id = m[2];
                return '<div class="loading-bg" style="width: 150px; height: 150px"><img src="/image?type='+type+'&do=thumb&id='+id+'" alt="" /></div>';
            }
            return false;
        }
    });
    
    // Ratings
    $(".rate a").mouseout(function(event) {
        $(this).children('img').attr('src', '/images/stars/stars/none.png');
        $(this).prevAll().children('img').attr('src', '/images/stars/stars/none.png');
    });
    $(".rate a").mouseover(function(event) {
        var star = $(this).parent().hasClass('difficulty') ? 'stard' : 'star';
        $(this).children('img').attr('src', '/images/stars/stars/'+star+'.png');
        $(this).prevAll().children('img').attr('src', '/images/stars/stars/'+star+'.png');
    });
    $(".rate a").click(function(event) {
        event.preventDefault();
        
        var targetedLink = this;
        var metric = $(this).attr('href').match(/metric=([A-Za-z0-9]+)/)[1];
        var value = $(this).attr('href').match(/value=([0-9]+)/)[1];
            
        $(this).parent().fadeTo(100, .3);
        
        $.ajax({
            type: 'GET',
            url: $(this).attr('href')+'&service=true',
            dataType: 'json',
            cache: false,
            complete: function() {
                $(targetedLink).parent().fadeTo(100, 1);
            },
            success: function(data, textStatus) {                
                if (data.error) {
                    alert('Something went wrong while trying to save your rating:\n'+data.error+'.');
                    return;
                }
                
                var rating = data.rating > 5 ? 5 : data.rating;
                var percent = rating/5*100;
                $('.s-'+metric+'-rating').html('<div class="rating '+metric+'" title="'+rating+'"><div class="rating-inner" style="width: '+percent+'%">'+rating+'</div></div> ('+( Math.round(rating*100)/100)+' out of 5)');
                
                var rating = value;
                var percent = rating/5*100;
                $(targetedLink).parent().html('<div class="rating '+metric+'" title="'+rating+'"><div class="rating-inner" style="width: '+percent+'%">'+rating+'</div></div>');
                
                // Ranking
                if ($('#s-ranking').length > 0 && 'rank' in data) {
                    var m = $('#s-ranking').html().match(/No\. ([0-9]+)/);
                    if (m) {
                        var oldRank = parseInt(m[1]);
                        
                        if (oldRank == data.rank) {
                            $('#s-ranking').html('No. '+oldRank+' (still)')
                        } else if (data.rank == false) {
                            $('#s-ranking').html('<em>(no longer in the top 100)</em> (was no. '+oldRank+' before you, a destroyer of worlds, came along)')
                        } else if (data.rank > oldRank) {
                            $('#s-ranking').html('No. '+data.rank+' (was no. '+oldRank+' before you came along)')
                        } else {
                            $('#s-ranking').html('No. '+data.rank+' (was no. '+oldRank+')')
                        }
                    } else {
                        if (data.rank == false) {
                            $('#s-ranking').html('<em>(still not in the top 100)</em>')
                        } else {
                            $('#s-ranking').html('No. '+data.rank+' (was unranked)')
                        }
                    }
                }
            }
        });
    });
    
    // Registration tooltips
    /*if (!fcAccount.isRegistered) {
        $("a[href*='/?levelId'][class!='tip-no-reg']").add("a[href*='/?editId']").add("a.tip-need-reg").mopTip({
            'w': 200,
            'h': 70,
            'delay': 0,
            'style': "overOut",
            'get': function(event) {
                return '<img src="/images/icons/alert.png" alt="[Alert]" class="inline-icon-16" /> <strong>You need to buy the full version to do this.</strong> If you already have, please ignore this message.';
            }
        });
    }*/
});

//-------------------------------
// Initialize menu
// http://www.candesprojects.com/downloads/flickr-horizontal-menu/
//-------------------------------

$(document).ready(function() {
    $("#menu").removeClass('inactive').addClass('active');
    
	$("#menu img.arrow")
        .click(function() {        
            $("span.head-menu").removeClass('active');
            
            submenu = $(this).parent().parent().find("div.sub-menu");
            
            if (submenu.css('display') == "block") {
                $(this).parent().removeClass("active"); 	
                submenu.hide(); 		
                $(this).attr('src','/images/menu_arrow_over.png');									
            } else {
                $(this).parent().addClass("active"); 	
                submenu.slideDown(100);
                $(this).attr('src','/images/menu_arrow_down.png');	
            }
            
            $("div.sub-menu:visible").not(submenu).hide();
            $("#menu img.arrow").not(this).attr('src', '/images/menu_arrow_up.png');
                            
        })
        .mouseover(function() {
            $(this).attr('src', '/images/menu_arrow_over.png');
        })
        .mouseout(function() { 
            if ($(this).parent().parent().find("div.sub-menu").css('display') != "block") {
                $(this).attr('src', '/images/menu_arrow_up.png');
            } else {
                $(this).attr('src', '/images/menu_arrow_down.png');
            }
        });

	$("#menu span.head-menu")
        .mouseover(function() { $(this).addClass('over') })
        .mouseout(function() { $(this).removeClass('over') });
	
	$("#menu div.sub-menu")
        .mouseover(function() { $(this).slideDown(100); })
        .blur(function() { 
            $(this).hide();
            $("span.head-menu").removeClass('active');
        });		
								
	$(document).click(function(event) { 		
        var target = $(event.target);
        if (target.parents("#menu").length == 0) {				
            $("#menu span.head-menu").removeClass('active');
            $("#menu div.sub-menu").hide();
            $("#menu img.arrow").attr('src','/images/menu_arrow_up.png');
        }
	});
});

//-------------------------------
// Global Ajax handling
//-------------------------------

var runningRequests = 0;

$(document).ajaxSend(function() {
    runningRequests++;
    if (runningRequests == 1) {
        $('#working-indicator > span').text('');
        $('#working-indicator').fadeIn(200);
    } else if (runningRequests > 1) {
        $('#working-indicator > span').text(' ('+runningRequests+' waiting)');
    } else {
        $('#working-indicator > span').text('');
    }
});

$(document).ajaxComplete(function() {
    runningRequests--;
    if (runningRequests == 0) {
        $('#working-indicator').fadeOut(200);
    } else if ($('#working-indicator > span').text() != "") {
        $('#working-indicator > span').text(' ('+runningRequests+' waiting)');
    }
});

$.ajaxSetup({
    error: function() {
        alert('Something went wrong while performing a request.');
    }
});

//-------------------------------
// Management
//-------------------------------

// Only do this on the "My Designs/Levels" page!
if (window.location.href.match(/mydesigns|mylevels/)) {
    $(document).ready(function() {
        // (Un)Publishing
        $('.manage-publish').click(function(event) {
            event.preventDefault();
            
            var targetedLink = this;
            var type = $(this).attr('href').match(/(design|level)Id=([0-9]+)/)[1];
            var id = $(this).attr('href').match(/(design|level)Id=([0-9]+)/)[2];
            
            $(this).fadeTo(100, .3);
            
            $.ajax({
                type: 'GET',
                url: $(this).attr('href')+'&service=true',
                dataType: 'json',
                cache: false,
                complete: function() {
                    $(targetedLink).fadeTo(100, 1);
                },
                success: function(data, textStatus) {
                    $(targetedLink).fadeTo(100, 1);
                    
                    if (data.error) {
                        alert('Something went wrong while trying to publish '+type+' #'+id+':\n'+data.error+'.');
                        return;
                    }
                    
                    if (data.published) {
                        $(targetedLink).children('img').attr('src', $(targetedLink).children('img').attr('src').replace(/\bpublish\b/g, 'unpublish'));
                        $(targetedLink).attr('href', $(targetedLink).attr('href').replace(/\bpublish\b/g, 'unpublish'));
                        $(targetedLink).attr('title', "Unpublish");
                        $(targetedLink).parent().parent().removeClass("unpublished");
                    } else {
                        $(targetedLink).children('img').attr('src', $(targetedLink).children('img').attr('src').replace(/\bunpublish\b/g, 'publish'));
                        $(targetedLink).attr('href', $(targetedLink).attr('href').replace(/\bunpublish\b/g, 'publish'));
                        $(targetedLink).attr('title', "Publish");
                        $(targetedLink).parent().parent().addClass("unpublished");
                    }
                }
            });
        });
        
        // Deleting
        $('.manage-delete').click(function(event) {
            event.preventDefault();
            
            var targetedLink = this;
            var type = $(this).attr('href').match(/(design|level)Id=([0-9]+)/)[1];
            var id = $(this).attr('href').match(/(design|level)Id=([0-9]+)/)[2];
            
            if (!confirm('Are you sure you wish to delete this '+type+'?\nNote that it will still be accessible via a direct link, but it will no longer show in your list of '+type+'s.')) {
                return false;
            }
            
            $(this).fadeTo(100, .3);
            
            $.ajax({
                type: 'GET',
                url: $(this).attr('href')+'&service=true',
                dataType: 'json',
                cache: false,
                complete: function() {
                    $(targetedLink).fadeTo(100, 1);
                },
                success: function(data, textStatus) {
                    if (data.error) {
                        alert('Something went wrong while trying to delete '+type+' #'+id+':\n'+data.error+'.');
                        return;
                    }
                    
                    if (data.deleted) {
                        $(targetedLink).parent().parent().removeClass('unpublished').addClass('deleted');
                        $(targetedLink).parent().parent().children('td:last').children().fadeOut(200, function() {
                            $(targetedLink).parent().parent().children('td:last').html('(deleted)');
                        });
                    }
                }
            });
        });
    });
}