$(document).ready(function() {

    // SITE-WIDE

    $("#nav li, #home-page #why-sage a.read-more, #home-page a.take-the-challenge, #your-stats .buttons a, #game-share #email button, a.copy-button, a.preview-button, a.copy-to-clipboard, a.edit-profile, a.embed, ul#game-types h2, ul#sage-links li a, #create-your-player #form button,#tuc-ur-great a.copy, #tuc-login button, #not-registered a, #login-overlay button, a.close-box, a.button-continue,a.button-apply,a.button-upload,a.start-your-training,a.play-challenge").hover(
		function() {
		    $(this).find("span, div").fadeIn(400);
		},
		function() {
		    $(this).find("span, div").stop(true,true).hide();
		}
	);

    $("#login-links li div, #loggedin-links li div").hover(
		function() {
		    $(this).find("a").fadeIn(400);
		},
		function() {
		    $(this).find("a").stop(true,true).hide();
		}
	);

    $("li#login-link a").overlay({
        close: "a.close-box",
        absolute: false,
        target: "#login-overlay",
        left: "center",
        top: 220,
        expose: "#f5f5f5"
    });

    $("#sister-links ul li#s3").tooltip({
        tip: '#sister-links ul li#s4',
        effect: 'toggle',
        position: 'bottom center',
        predelay: 200,
        delay: 200,
        relative: true
    });

    // HOME PAGE

    $('#home-page #slide-show').cycle({
        fx: 'fade',
        speed: 2000,
        timeout: 5000,
        slideExpr: 'img.slide'
    });

    $('#home-page .link').hover(
		function() {
		    $(this).find(".hover-bg, a.read-more div").fadeIn(300);
		},
		function() {
		    $(this).find(".hover-bg, a.read-more div").stop(true,true).hide();
		}
	);

    // BUSINESS IQ

    function videoSubnav() {

    };

    $('#videos .more-videos a').click(
		function() {
		    var target = $(this).attr("rel");
		    $(".video").hide();
		    $(target).show();
		    pageTracker._trackEvent('BusinessIQ Video begun', $(this).text());
		    return false;
		}
	);

    $('#business-iq #video-container #videos ul.more-videos li').hover(
		function() {
		    $(this).find(".hoverbg").fadeIn(300);
		    $(this).find("a").addClass("hover");
		},
		function() {
		    $(this).find(".hoverbg").stop(true,true).hide();
		    $(this).find("a").toggleClass("hover");
		}
	);

    // REGISTER PAGES

    $('#your-avatar input.radio-upload').click(function() {
        $("#your-avatar #image-browser").show()
    });

    $('#your-avatar input.radio-facebook, #your-avatar input.radio-avatar').click(function() {
        $("#your-avatar #image-browser").hide()
    });

    $('input[type="checkbox"], input[type="radio"]').checkBox();

    $('a[rel="#validation-error"]').overlay({
        left: 0,
        top: 0,
        absolute: true,
        close: 'a.button-continue, a.close-box'
    });

    $('a[rel="#successful-submission"]').overlay({
        left: 0,
        top: 0,
        absolute: true,
        close: 'a.button-continue, a.close-box'
    });

    $('button[rel="#image-crop"]').overlay({
        api: true,
        left: 0,
        top: 0,
        absolute: true,
        target: "#image-crop"
    });

    if (typeof document.body.style.maxHeight === "undefined") { //if IE 6
        $("button[rel],a[rel]").click(function() {
            $('select').css({ "visibility": "hidden" });
        });
        $("a.button-continue, a.button-upload").click(function() {
            $('select').css({ "visibility": "visible" });
        });
    };

    $('#create-your-player .ReplacedBrowseButton').hover(
		function() {
		    $(this).siblings("div").fadeIn(300);
		},
		function() {
		    $(this).siblings("div").fadeOut(300);
		}
	);

    $("input[type='file']").filestyle({
        image: "images/register-browse_button.png",
        imageheight: 35,
        imagewidth: 91,
        width: 179
    });

    // START TRAINING

    $("#game-details > ul.tabs").tabs("#game-details .panes > div", {
        current: 'here',
        tabs: 'li'
    });

    $("#game-stats > ul.tabs").tabs("#game-stats .panes > div", {
        current: 'here',
        tabs: 'li'
    });

    $("#game-stats #league ul.tabs").tabs("#game-stats #league > .year-data", {
        current: 'here',
        tabs: 'li'
    });

    $("#game-stats #league .pagination ol li:first-child").addClass("first-child");

    $("#game-share > ul.tabs").tabs("#game-share .panes > div", {
        current: 'here',
        tabs: 'li',
        onClick: function() {
            try {
                buildCopyLink();
            } catch (Error) {
            }
            try {
                buildCopyEmbed();
            } catch (Error) {
            }
        }
    });

    $("#game-share .code-to-copy, #tuc-ur-great input.code-to-copy").click(
		function() {
		    this.select();
		}
	);

    $(".no-flash").hover(
		function() {
		    $(this).find("div").fadeIn(400);
		},
		function() {
		    $(this).find("div").stop(true,true).hide();
		}
	);

    // PROFILE PAGE

    $("#stats #iq-card ul.tabs").tabs("#stats #iq-card > table.yearly-data", {
        current: 'here',
        tabs: 'li'
    });

    $('#stats .graph-container').hover(
		function() {
		    $(this).addClass("hover");
		},
		function() {
		    $(this).removeClass("hover");
		}
	);

    $('#stats #iq-card table tr:last-child').addClass("last-child");

});


function initStatsTab() {
    $("#game-stats > ul.tabs li:contains('Your Stats')").click(function() {
        $("#game-stats #your-stats > ul.tabs").tabs("#game-stats #your-stats > .year-pane", {
            current: 'here',
            tabs: 'li'
        });
        try {
            graph();
        } catch (Error) {
        }
        $("#gamerCardEmbed").css("display", "none !important");
        buildCopyProfileEmbed();
    });
    $("#embedGamerCardLink").click(function() { return false; });
}

var pclip;

function buildCopyProfileEmbed() {
	pclip = null;
	gclip = new ZeroClipboard.Client();
	gclip.glue('copyEmbedLink');
	gclip.setHandCursor(true);
	gclip.setText($("#gamerCardEmbed").val());
	gclip.addEventListener('complete', function(client, text) {
		alert("The profile embed code has been copied to your clipboard");
    });
    gclip.addEventListener('onMouseOver', function(client) {
        $("#copyEmbedLink").find("span, div").fadeIn(400);
    });
    gclip.addEventListener('onMouseOut', function(client) {
        $("#copyEmbedLink").find("span, div").hide();
    });
}

// Facebook stuff

function elevateFBPermissions() {
	//check is user already granted for this permission or not
	FB.Facebook.apiClient.users_hasAppPermission('publish_stream', function(result) {
		// prompt offline permission
		if (result == 0) {
			// render the permission dialog
			FB.Connect.showPermissionDialog('publish_stream', fetchPermissions);
		} else {
			// permission already granted.
			fetchPermissions(true);
		}
	});
}

function fetchPermissions(perms) {
	if (perms != true) {
		if (perms == "publish_stream") {
			perms= true;
		}
	}
	//Send perm value to flash using callback function;  Function is called permissionsDone()
	document.getElementById("challengeEmbed").permissionsDone(perms);
}

var facebookUser;

function detectFacebookUser() {
	FB.Connect.ifUserConnected(function() { facebookUser = true; }, function() { facebookUser = false });
}

function isFacebookUser() {
	detectFacebookUser();
	return facebookUser;
	//Until completion, disable this.
	//return false;
}