    /* -------------------------------------------------------------------

	    Boondoggle - <css creator>
	    <client>
    	
	    This JavaScript file collects all general functions used
	    throughout the site, as well as some smaller specific
	    functions.

    ------------------------------------------------------------------- */



    // when the document is ready to be traversed and manipulated...
    $(document).ready(function(){
    						   
	    // LINK HANDLER
	    // when you click on a link with class externalLink
	    $("a.externalLink").click(function(){
		    // open a new window with the link's location
		    window.open($(this).attr("href"));
		    // and do nothing after (to prevent the link from actually firing)
		    return false;
	    });
	    $('#username-input').clearDefault();
    	
	    //introBox method switcher
	    $("#useSiteButton").click(function() {
		    $("#useSiteButton").addClass("active");
		    $("#useTwitterButton").removeClass("active");
		    $("#useTwitter").css("display","none");
		    $("#useSite").css("display","block");															 
	    })
	    $("#useTwitterButton").click(function() {
		    $("#useTwitterButton").addClass("active");
		    $("#useSiteButton").removeClass("active");
		    $("#useSite").css("display","none");
		    $("#useTwitter").css("display","block");															 
	    })
    });
    (function($){
	    $.fn.clearDefault = function(){
		    return this.each(function(){
			    var default_value = $(this).val();
			    $(this).focus(function(){
				    if ($(this).val() == default_value) $(this).val("");
			    });
			    $(this).blur(function(){
				    if ($(this).val() == "") $(this).val(default_value);
			    });
		    });
	    };
    })(jQuery);

    // Usage: $('input.clear-default').clearDefault();
    function tab(){
        var argv = tab.arguments;
        var argc = argv.length;
        $(argv[0]).show();
        $(argv[0]+"link").addClass('tab-active');
        for (var i = 1; i < argc; i++) {
            $(argv[i]).hide();
            $(argv[i]+"link").removeClass('tab-active');
        }
    }
    function score(matchid, factor, team, hometeam, awayteam){
	    var currScore = parseInt($('#'+team+matchid).val());
	    var newScore = currScore;
	    if(factor == "-1" && currScore > 0){
		    newScore = currScore - 1;
	    }
	    if(factor == "+1"){
		    newScore = currScore + 1;
	    }
	    $('#'+team+matchid).val(newScore);
	    var prefix = '';
	    var suffix = '';
	    
	    
	    
	    if( $('#hasShootout' + matchid).html() == 'yes' && $('#hometeam'+matchid).val() == $('#awayteam'+matchid).val()) {
            winningTeam = $("input:radio[name=shootoutTeamRadio" + matchid + "]:checked").val();
            scoreString = $('#hometeam'+matchid).val()+'-'+$('#awayteam'+matchid).val();
            if(winningTeam == "home"){
                scoreString = "P" + scoreString;
                prefix = "P";
            }
            else{
                scoreString = scoreString + "P";
                suffix = "P";
            }
            $('#twitter-link'+matchid).attr('href', 'http://twitter.com/home?status=%23cuptweets+%23'+hometeam+'+%23'+awayteam+'+'+ scoreString +'+prediction+via+http://cuptweets.com+%23worldcup');
            $("#shootoutText" + matchid).show();
            $("#shootoutHome" + matchid).show();
            $("#shootoutVisitor" + matchid).show();
        }
        else {
            $("#shootoutText" + matchid).hide();
            $("#shootoutHome" + matchid).hide();
            $("#shootoutVisitor" + matchid).hide();
            $('#twitter-link'+matchid).attr('href', 'http://twitter.com/home?status=%23cuptweets+%23'+hometeam+'+%23'+awayteam+'+'+$('#hometeam'+matchid).val()+'-'+$('#awayteam'+matchid).val()+'+prediction+via+http://cuptweets.com+%23worldcup');
        }
        
	    
	    if(team == "hometeam"){
		    if(newScore == undefined){
			    newScore = 0;
		    }
		    $('#status-score'+matchid).text(prefix + newScore+"-"+$('#awayteam'+matchid).val() + suffix);
	    }
	    if(team == "awayteam"){
		    if(newScore == undefined){
			    newScore = 0;
		    }
		    $('#status-score'+matchid).text(prefix + $('#hometeam'+matchid).val()+"-"+newScore + suffix);
	    }
    }
    function openUserpage(host){
	    var username = $('#username-input').val();
	    var url = "http://"+host+"/"+username
	    window.location=url;
    }

    function updateMatchScore(matchId){
        try{
            setTimeout( "getMatchScore(" + matchId + ")" , 10000 );
        }
        catch(exc){
        }
    }

    function getMatchScore(matchId){    
        $.ajax(
        {
            type: "POST",
            url: "/Service/service.asmx/GetMatchScore",          
            data: $.toJSON({matchId:matchId}),                                 
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: doUpdateMatchScore,
            error: function(){updateMatchScore(matchId);},
            async: true
        });
    }
    
    function doUpdateMatchScore(data){
      if(data !=null && data.d != null){
            $("#matchHomeScore" + data.d.MatchId).html(data.d.HomeTeamScore);
            $("#matchVisitorScore" + data.d.MatchId).html(data.d.VisitorTeamScore);
       }
       if(!data.d.IsDonePlaying){
        updateMatchScore(data.d.MatchId);
       }
       else{
        window.location.reload();
       }
    }
    
    function closeFancyBox(matchId){
        setTimeout( "doCloseFancyBox(" + matchId + ")" , 3000 );
    }
    
    function doCloseFancyBox(matchId){
        $.fancybox.close();
        $("#submit-result" + matchId).html("");                   
    }
    
    function CloseGettingStarted() {


        $('#getting-started').hide();
        $.cookie("hide-getting-started", true, { expires: 40 });
    }
    function ShowGettingStarted() {


        $('#getting-started').show();
        $.cookie("hide-getting-started", null);
    }
    
    function showFBShare(url,txt){
        window.open('http://www.facebook.com/sharer.php?u='+encodeURIComponent(url)+'&t='+encodeURIComponent(txt),'sharer','toolbar=0,status=0,width=626,height=436');
        return false;
    }
    
    function showDelShare(url, txt) {
        window.open('http://delicious.com/save?url='+encodeURIComponent(url)+'&title='+txt,'sharer','toolbar=0,status=0,width=796,height=436');
        return false;
    } 
    
    var currentUser = null;
    
    
        
    function postFBPredictionOnFail(matchId,type){
        $.fancybox.center();
        if(type=='nopost'){
            $("#submit-result" + matchId).html("To register your prediction, you have to post it to facebook...");  
        }
        else{
            $("#submit-result" + matchId).html("Something went wrong. Please try again...");
        }                     
    }
    
    function postFBPredictionOnSuccess(matchId,platformUserId,platformUserName,homeTeamScore,visitorTeamScore){
         $.fancybox.center();
         if(
            $("#homeTeamScore_" + matchId + "_" + platformUserId).length!=0){
            $("#homeTeamScore_" + matchId + "_" + platformUserId).html(homeTeamScore);
            $("#visitorTeamScore_" + matchId + "_" + platformUserId).html(visitorTeamScore);
         }
         else{
            $("#mostTweetedHomeTeamScore_" + matchId).html(homeTeamScore);
            $("#mostTweetedVisitorTeamScore_" + matchId).html(visitorTeamScore);
            $("#mostTweetedLabel_" + matchId).html("&lt;prediction of " + platformUserName + "&gt;");
            $("#submit-result" + matchId).html("Your prediction was registered succesfully!"); 
            closeFancyBox(matchId);
         }
    }
    //flash
    function htmlPostFBPrediction(matchId){
        homeTeam = $("#homeTeamShortCode" + matchId).html();
        visitorTeam = $("#visitorTeamShortCode" + matchId).html();
        homeTeamScore = $("#hometeam"+matchId).val();
        visitorTeamScore = $("#awayteam"+matchId).val();
        
        var winningTeam = "";
         if( $('#hasShootout' + matchId).html() == 'yes' && homeTeamScore == visitorTeamScore) {
            winningTeam = $("input:radio[name=shootoutTeamRadio" + matchId + "]:checked").val();
         }
        
        postFBPrediction(matchId,homeTeam,visitorTeam,homeTeamScore,visitorTeamScore,winningTeam,'',postFBPredictionOnSuccess,postFBPredictionOnFail)
    }
    
    function postFBPrediction(matchId,homeTeam,visitorTeam,homeTeamScore,visitorTeamScore,winningTeam,statusSuffix,onSuccess,onFail){ 
        var prefix = '';
        var suffix = '';
        if(winningTeam=='home'){
            prefix = 'P';
        }
        else if(winningTeam=='visitor'){
            suffix = 'P';
        }
        var post =  'My prediction for ' + homeTeam + ' - ' + visitorTeam + ' : ' + prefix +  homeTeamScore + ' - ' + visitorTeamScore + suffix + '.' + statusSuffix;

        getFBSession(function(){
            FB.ui(
               {
                 method: 'stream.publish',
                 message: post ,
                 attachment: {
                    'name': 'Check my ranking on cuptweets.com - can you do better?', 
                    'href': 'http://www.cuptweets.com/' + encodeURIComponent(currentUser.name)
                 },
                 action_links: [
                   { text: 'Make a prediction', href: 'http://www.cuptweets.com' }
                 ],
                 user_message_prompt: 'Post your world cup prediction.'
               },
               function(response) {
                 if (response && response.post_id) {
                    saveFBPrediction(response.post_id,matchId,post,onSuccess,onFail);
                 } else {
                   onFail(matchId,'nopost');
                 }
               }
            );
        });
    }
    
    function setUser(onUserSet){
        FB.api('/me', function(res) {
            currentUser = res;
            onUserSet();
       });
    } 
    
    function getFBSession(onUserSet){
        FB.getLoginStatus(
            function(response) {
                if (response.session) {
                    if(currentUser == null || currentUser.id != response.session.uid){
                        setUser(onUserSet);
                    } else{
                        onUserSet();
                    }
                }
                else {
                    connectFBUser(onUserSet);
                }
            }
       );
    }
    
    function connectFBUser(onUserSet){
        FB.login(
            function(response) {
                    if (response.session) {                   
                       setUser(onUserSet);
                    }
            }, {perms:'read_stream'}
        );
    }	  
    
    function saveFBPrediction(postId,matchId,post,onSuccess,onFail){
        $.ajax(
            {
                type: "POST",
                url: "/Service/service.asmx/SetFacebookPrediction",          
                data: $.toJSON({matchId:matchId,uid:currentUser.id,userName:currentUser.name,postId:postId,post:post}),                                 
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function(data){saveFBPredictionSuccess(data,matchId,onSuccess,onFail);},
                error: function(err,res){ saveFBPredictionFail(err,res,matchId,onFail);},
                async: true
            }
        );
     }
     
     function saveFBPredictionSuccess(data,macthId,onSuccess,onFail){
        if(data!=null && data.d != null){
            onSuccess(data.d.MatchId,data.d.PlatformUserId,data.d.PlatformUserName,data.d.HomeTeamScore,data.d.VisitorTeamScore);
        }
        else{
            onFail(matchId,'error')
        }
     }   
    
    function saveFBPredictionFail(err,res,macthId,onFail){
        onFail(matchId,'error');
     }
     
     
     
    function getAllPostsWithKeyword(){
        getFBSession(
              function(){
                var query = FB.Data.query("select message, post_id, created_time from stream where source_id={0} and attribution='{1}'",
                           currentUser.id,'CupTweets');
                query.wait(function(rows) {
                    recoverFBPredictions(rows);
                });
            }
        );
    }
    
     function recoverFBPredictions(rows){
        $.ajax(
            {
                type: "POST",
                url: "/Service/service.asmx/RecoverFacebookPredictions",          
                data: $.toJSON({postsAsJson:$.toJSON(rows),userName:currentUser.name,userId:currentUser.id}),                                 
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function(data){recoverFBPredictionSuccess(data);},
                error: function(err,res){  },
                async: true
            }
        );
     }
     
     function recoverFBPredictionSuccess(data){
        document.location = "/" + currentUser.name;
     } 
