var THUMBS_HTTP_ROOT = "http://thumbs.freeporn.com/media/videos/tmb/";
function addBookmark(title,url){
    if (window.sidebar) // firefox
        window.sidebar.addPanel(title, url, "");
    else if(window.opera && window.print){ // opera
        var elem = document.createElement('a');
        elem.setAttribute('href',url);
        elem.setAttribute('title',title);
        elem.setAttribute('rel','sidebar');
        elem.click();
    }
    else if(document.all)// ie
        window.external.AddFavorite(url, title);
}

function addCommas(nStr)
{
    nStr += '';
    x = nStr.split('.');
    x1 = x[0];
    x2 = x.length > 1 ? '.' + x[1] : '';
    var rgx = /(\d+)(\d{3})/;
    while (rgx.test(x1)) {
        x1 = x1.replace(rgx, '$1' + ',' + '$2');
    }
    return x1 + x2;
}

function show_tab(the_tab) {
    tab_info = the_tab.metadata();
    $("#" + tab_info.name + " " + "a.show-tab").parent().removeClass("show-tab-selected");
    $("#" + tab_info.name + " " + ".tab").hide();
    the_tab.parent().addClass("show-tab-selected");
    $("#" + tab_info.name + " " + ".tab-" + tab_info.tab).show();
}


function favorite(action,game) {
    $.get("/game/"+ action +"Favorite/" + game,'',function(response){
        $(".button_favorite").hide();
        if(action=="add"){
            $(".button_favorite_remove").show();
        } else {
            $(".button_favorite_add").show();
        }
    });
}

function comments_showResponse(responseText, statusText) {
    if(responseText=="RATE") {
        $("#comments").prepend("<div class='error'><p>You must wait a few minutes to post another comment!</p></div>");
    } else if (responseText == "NO_EMAIL") {
        $("#comments").prepend("<div class='error'><p>You must confirm your email address before adding a comment. Please check your email or <a href='/user/resendEmailConfirmation'>click here</a> to resend.</p></div>");
    } else if(responseText == "false") {
        alert("An error ocurred");
    }else{
        $("#comments").prepend(responseText);
		
        $("#comments .comment:first-child .game_wall_post").effect("highlight", {}, 8000);
		
        // Get the newest comment and then scroll to it
        var myComment = $("#comments a:first-child").attr("name");
        //$.scrollTo("div." + myComment);
		
        $("#add_comment .button").removeAttr('disabled');
        comments_delete_buttons();
    }
}

function validate() {
    var text = $("#add_comment textarea#body").val();
    if(!text) {
        return false;
    } else {
        $("#comments .error").remove();
        //$("#add_comment .button").attr('disabled', 'disabled');
        return true;
    }
}

function comments_delete_buttons() {
    $('#comments a.delete').live("click", function(){
        var answer = confirm('Are you sure you want to delete this comment?');
        if (answer) {
            $("#comments .error").remove();
            $.get($(this).attr('href'),$(this).parent().parent().parent().remove());
        }
        return false;
    });
    $('#comments a.report').live("click", function(){
        var answer = confirm('Are you sure you want to report this comment?');
        if (answer) {
            $.get($(this).attr('href'),'',function(response){
                alert(response);
            });
        }
        return false;
    });
}


// Reply to a comment
function reply_comment(type, profileId){
    $('a.reply-comment').live('click', function() {
        var replyId = $(this).attr('rel');
		
        // Is already open?
        if($('div#reply-form').length!=0) {
            $('div#reply-form').remove();
        }
		
        $(this).parent().parent().parent().append('<div id="reply-form" class="reply-forms"><form class="reply-form" accept-charset="utf-8" method="post" action="/comment/add/'+profileId+'"><input type="hidden" name="type" value="'+type+'" /><input type="hidden" id="comment_id" name="comment_id" value="'+replyId+'"><textarea name="body" cols="5" rows="5"></textarea><button class="button button_small button_small_blue" type="submit"><span>Reply</span></button> or <a href="#" title="Cancel this reply" class="cancel-reply" rel="'+replyId+'">Cancel</a></form><br clear="all" /></div>');
		
        return false;
    });
	
    $('a.cancel-reply').live('click', function() {
        $('div#reply-form').remove();
    });
	
    var reply_options = {
        success:       replies_showResponse,
        beforeSubmit:  validateReply,
        clearForm: true
    };
	
    $('form.reply-form').livequery("submit", function() {
        $(this).ajaxSubmit(reply_options);
        return false;
    });
}

function comments_showResponse(responseText, statusText) {
    if(responseText=="RATE") {
        $("#comments").prepend("<div class='error'><p>You must wait a few minutes to post another comment!</p></div>");
    } else if (responseText == "NO_EMAIL") {
        $("#comments").prepend("<div class='error'><p>You must confirm your email address before adding a comment. Please check your mailbox.<br>Having trouble confirming your email? Resend the activation <a href='/user/resendEmailConfirmation'>link</a>.</p></div>");
		
		
    } else if(responseText == "false") {
        alert("An error ocurred");
    }else{
        $("#comments").prepend(responseText);
		
        //$("#comments .comment:first-child .game_wall_post").effect("highlight", {}, 8000);
		
        // Get the newest comment and then scroll to it
        var myComment = $("#responses a:first-child").attr("name");
        //$.scrollTo("div." + myComment);
		
        $("#add_comment .button").removeAttr('disabled');
        comments_delete_buttons();
    }
}

function validateReply() {
    var text = $("#reply-form form textarea").val();
    if(!text) {
        return false;
    } else {
        $("#comments .error").remove();
        //$("#add_comment .button").attr('disabled', 'disabled');
        return true;
    }
}

function replies_showResponse(responseText, statusText) {
    if(responseText=="RATE") {
        $("#comments").prepend("<div class='error'><p>You must wait a few minutes to post another comment!</p></div>");
    } else if (responseText == "NO_EMAIL") {
        $("#comments").prepend("<div class='error'><p>You must confirm your email address before adding a comment. Please check your email or <a href='/user/resendEmailConfirmation'>click here</a> to resend.</p></div>");
    } else if(responseText == "false") {
        alert("An error ocurred");
    }else{
        loadContent("wall");
    }
}


var thumb_t_ID=null;
var thumb_t_selected=null;

$(document).ready(
    function(){
        var ThumbsCacheStack = [];

        $.preLoadImages = function(images) {
            for (var i=0; i<images.length; i++){
                var cacheImage = document.createElement('img');
                cacheImage.src = images[i];
                ThumbsCacheStack.push(cacheImage);
            }
        }
        $.cicleThumbsfrom = function(ThumbImageObject) {
            thumb_t_selected++;
            if(thumb_t_selected >= ThumbImageObject.thumbs.length){
                thumb_t_selected = 0;
            }
            ThumbImageObject.attr("src",ThumbImageObject.thumbs[thumb_t_selected]);
        }
        //$("div.sidebox, div.box").corner("5px bottom");
        $(".small_button").blur();
        $("a.show-tab").click(function(){
            show_tab($(this));
        });
        
        /* -- FOR THE PROFILE -- */
        /* Add-remove friend */
        $('a.add_friend').click(function(){
            $.get($(this).attr('href'),function(data){
                $('a.add_friend').hide();
                $('a.remove_friend').show();
            });
        });
        $('a.remove_friend').click(function(){
            $.get($(this).attr('href'),function(data){
                $('a.remove_friend').hide();
                $('a.add_friend').show();
            });
        });
        /* -- END FOR THE PROFILE */

        // qTip
        $('a[rel*=register-qtip], button.register-qtip').live("click", function() {
            $(this).qtip({
                content: "<div id='registerAnAccount'><h3>Register a free acount today!</h3><p>You don't have an account yet? What are you waiting? <a href='/signup' title=''>Register a free</a> account with us today and you will be able to:</p><ul><li>Post comments</li> <li>Have a profile and save your favorite videos</li></ul><p>If you already have an account, please <a href='/login' title='Login into your account'>login</a> here.</p></div>",
                show: {
                    when: false, // Don't specify a show event
                    ready: true // Show the tooltip when ready
                },
                hide: 'unfocus', // Hide it when inactive...
                position: {
                    corner: {
                        target: 'topMiddle',
                        tooltip: 'bottomLeft'
                    }
                },
                style: {
                    border: {
                        width: 5,
                        radius: 10
                    },
                    padding: 10,
                    textAlign: 'left',
                    tip: true, // Give it a speech bubble tip with automatic corner detection
                    name: 'dark' // Style it according to the preset 'cream' style
                }
            });
        });
        try{
        $("img.rotate-thumbs").livequery("mouseenter",
            function(){
                clearInterval(thumb_t_ID);
                var self=$(this);
                var params = self.metadata();
                self.thumbs = new Array();
                thumb_t_selected = params.selected_thumb;
                for(var i = 0; i < params.thumbs_no; i++){
                    self.thumbs[i] = THUMBS_HTTP_ROOT + params.video_id+"/"+i+".jpg";
                }
                $.cicleThumbsfrom(self);
                thumb_t_ID = setInterval(function(){
                    $.cicleThumbsfrom(self);
                }, 500);
            }
            );
        }catch(e){}
        try{
        $("img.rotate-thumbs").livequery("mouseleave",
            function(){
                var self=$(this);
                var params = self.metadata();
                self.attr("src", THUMBS_HTTP_ROOT + params.video_id+"/"+params.selected_thumb+".jpg");
                clearInterval(thumb_t_ID);
                thumb_t_selected = null;
            }
            );
        }catch(e){}
    }
    );