$j(function(){
    $j(".meta input.txt").bind("focus",function(){
        this.select();
    });
    $j(".embed input.txt").bind("focus",function(){
        this.select();
    });
});


var $leaderboard = {
    active_chooser : null,
    chooser_key: null,
    items: null,
    show_chooser: function(chooser) {
        $j(chooser).find("ul").show()
    },
    hide_chooser: function(chooser){
        $j(chooser).find("ul").hide()
    },
    init_mode_chooser: function(url){
        $j(".play-mode ul li").click(function(){
            url += "&playMode=" + $j(this).attr("id");
            window.location = url;
            return false;
        });
    },
    init_chooser: function(path) {
        $j(path).find("h4").click(function(){
            if($leaderboard.active_chooser) {
                $leaderboard.hide_chooser($leaderboard.active_chooser);
            }
            $leaderboard.active_chooser = $j(this).closest(".chooser");
            $leaderboard.show_chooser($leaderboard.active_chooser);

            $leaderboard.chooser_key = $j($leaderboard.active_chooser).attr("rel");
            $leaderboard.items = $j($leaderboard.active_chooser).find("ul");

        });

        $j(path).find("ul").bind("mouseleave", function(){
            $j($leaderboard.items).children(".chooseritems").removeClass("highlight");
        });

        $j(path).bind("mouseleave",function(){
            if($leaderboard.active_chooser) {
                $leaderboard.hide_chooser($leaderboard.active_chooser);
                $leaderboard.active_chooser = null;
            }
        });
        $j(path).find(".chooseritems").mouseover(function(){
            $j(this).siblings().removeClass("highlight");
            $j(this).addClass("highlight");
        });
        $j(path).find(".chooseritems").click(function(){
            input_key = "input[name='" + $leaderboard.chooser_key + "']";
            $j(input_key).attr('value',$j(this).attr('rel'));

            $j($leaderboard.active_chooser).find("h4").html($j(this).html());
            $j(this).siblings().removeClass("highlight");
            $j($leaderboard.items).hide();
        });
    },
    iframe_embed: function(path,personaId,personaName,personaNamespace) {
        $j(path).each(function(i){
        	embedCont = $j(this).attr("rel");

            url = "http://" + document.domain + "/profile/embed";
            url += "?embedContext="+embedCont;
            url += "&friendPersonaId="+personaId;
            url += "&friendPersonaName="+personaName;
            url += "&friendNamespace="+personaNamespace;

            width = 425;
            
            if(embedCont == "profileBadge")
            {height = 188;}
    		if(embedCont == "killSummary")
    		{height = 343;}	
    		if(embedCont == "killRatio")
    		{height = 312;}
    		if(embedCont == "weapons")
    		{height = 262;}
    		if(embedCont == "collectibles")
    		{height = 318;}
    		if(embedCont == "achievements")
    		{	
				height = 434;
			}
    			
            $j(this).attr("value","<iframe src='"+url+"' frameborder='0' scrolling='no' height='"+height+"' width='"+width+"'></iframe>");
        });


    },
    get_embed_code: function(e){
        obj = $j("#"+e.id);
        h = $j(obj).attr('height');
        w = $j(obj).attr('width');
        url = $j(obj).attr('data');
        params = $j(obj).html();
        embedcode = "<object classid='clsid:D27CDB6E-AE6D-11cf-96B8-444553540000' width='" +w +"' height='" +h +"' data='"+url+"'>"
            + params + "</object>";

        $j(obj).closest(".block").find("input.txt").attr("value",embedcode);
    }
}

var pageNum = 1;
var $leaderboard_profile = {

    init: function(){
    
	//Add Friend Profile

    	$j(".profile-detail .friend a").click(function(){
            a = this;
            $j.getJSON(this.href,function(data) {
                if(data.status != "success") {
                	alert(data.errors[0].description);
                } else {
                    $j(a).hide();
                    $j().find(".added").show();
                }
            });
            return false;
        });
    	
        $j(".feed .scroll-pane").jScrollPane( { showArrows:true, scrollbarWidth:18, scrollbarMargin:10, maintainPosition:true } );

        $j(".status-update form input.btn").click(function(){
            $formObj = $j(this).closest("form");
            $leaderboard_profile.post_activity_update($formObj,1);
            return false;
        });
		//Older
        $j(".activity-feed .other .more a.go-link.older").click(function(){
            $feed = $j(".activity-feed .feed");
            $link = $j(this);
			
            //pageNum = $link.attr("pagenum");
            pageSize = $link.attr("pagesize");
            href = $link.attr("href");

            window.pageNum++;
            url = href + "pageNum="+pageNum+"&pageSize="+pageSize;
            $feed.find(".feed-results").addClass("loading");

            $j.ajax({
                url: url,
				method:"GET",
				data: "",
                type: "html",
                success: function(response) {
                    $j(".activity-feed .feed .feed-results").html(response);
                    $feed.find(".feed-results").removeClass("loading");
                    $leaderboard_profile.init_activity_results();
                    tb_init(".activity-feed .feed .thickbox");
                    $j(".activity-feed .feed .feed-results .scroll-pane").jScrollPane( { showArrows:true, scrollbarWidth:18, scrollbarMargin:10, maintainPosition:true } );
                    $link.attr("pageNum",pageNum);
                    $link.attr("pageSize",pageSize);
                },
				error: function (XMLHttpRequest, textStatus, errorThrown) {
				   alert(XMLHttpRequest.status);
				   alert(XMLHttpRequest.responseText);
				}
            });
            return false;
        });
        //
        //Newer
        $j(".activity-feed .other .more a.go-link.newer").click(function(){
            $feed = $j(".activity-feed .feed");
            $link = $j(this);

            //pageNum = $link.attr("pagenum");
            pageSize = $link.attr("pagesize");
            href = $link.attr("href");

            window.pageNum--;
            url = href + "pageNum="+pageNum+"&pageSize="+pageSize;
            $feed.find(".feed-results").addClass("loading");

            $j.ajax({
                url: url,
				method:"GET",
				data: "",
                type: "html",
                success: function(response) {
                    $j(".activity-feed .feed .feed-results").html(response);
                    $feed.find(".feed-results").removeClass("loading");
                    $leaderboard_profile.init_activity_results();
                    tb_init(".activity-feed .feed .thickbox");
                    $j(".activity-feed .feed .feed-results .scroll-pane").jScrollPane( { showArrows:true, scrollbarWidth:18, scrollbarMargin:10, maintainPosition:true } );
                    $link.attr("pageNum",pageNum);
                    $link.attr("pageSize",pageSize);
                },
				error: function (XMLHttpRequest, textStatus, errorThrown) {
				   alert(XMLHttpRequest.status);
				   alert(XMLHttpRequest.responseText);
				}
            });
            return false;
        });
        //
        $leaderboard_profile.init_activity_results();
    },
    load_activity_feed: function(page){

        $feed = $j(".activity-feed .feed");
        url = $feed.attr("rel");

        $feed.find(".feed-results").addClass("loading");

        if(page > 0) {
            url += "pageNum="+page+"&pageSize=10";
        }
        $j.ajax({
            url: url,
            method:"GET",
			data: "",
            type: "html",
            success: function(response) {
                $j(".activity-feed .feed .feed-results").html(response);
                $feed.find(".feed-results").removeClass("loading");
                $leaderboard_profile.init_activity_results();
                tb_init(".activity-feed .feed .thickbox");
                $j(".activity-feed .feed .feed-results .scroll-pane").jScrollPane( { showArrows:true, scrollbarWidth:18, scrollbarMargin:10, maintainPosition:true } );
            },
			error: function (XMLHttpRequest, textStatus, errorThrown) {
			   alert(XMLHttpRequest.status);
			   alert(XMLHttpRequest.responseText);
			}
        });
    },
	checkBeforeSubmit: function(id) {
		$j(".flag-comment."+id+" .submit.btn").unbind().addClass('inactive');
		$j(".flag-graphic."+id+" .submit.btn").unbind().addClass('inactive');
		
		//Comments
		
		$j(".flag-comment."+id+" textarea.gg-flagReason").keyup(function() {
			if($j(this).val() != "" && $j(".flag-comment."+id+" select.complaintType").val() != ""){
	        	$j(".flag-comment."+id+" .submit.btn").bind("click",$leaderboard_profile.flag_or_comment_feed_action).removeClass('inactive');
			} else {
				$j(".flag-comment."+id+" .submit.btn").unbind().addClass('inactive');
			}
		});
		
		$j(".flag-comment."+id+" select.complaintType").change(function() {
			$j(".flag-comment."+id+" textarea.gg-flagReason").keyup();
		});
		
		// Graphics
		
		$j(".flag-graphic."+id+" textarea.gg-flagReason").keyup(function() {
			if($j(this).val() != "" && $j(".flag-comment."+id+" select.complaintType").val() != ""){
	        	$j(".flag-graphic."+id+" .submit.btn").bind("click",$leaderboard_profile.flag_or_comment_feed_action).removeClass('inactive');
			} else {
				$j(".flag-graphic."+id+" .submit.btn").unbind().addClass('inactive');
			}
		});
		
		$j(".flag-graphic."+id+" select.complaintType").change(function() {
			$j(".flag-graphic."+id+" textarea.gg-flagReason").keyup();
		});
		
	},
    init_activity_results: function(){
        $j(".activity-feed .detail .comment-trigger").click(function(){
            $j(this).hide();
            $j(this).closest(".detail").find(".comment-response").show();
            return false;
        });
        $j(".activity-feed .comment-response .cancel").click(function(){
            $j(this).closest(".detail").find(".comment-response").hide();
            $j(this).closest(".detail").find(".comment-trigger").show();
            return false;
        });
        $j(".activity-feed .comment-response .btn").click(function(){
            $formObj = $j(this).closest("form");
            $leaderboard_profile.post_activity_update($formObj,0);

            $j(this).closest(".detail").find(".comment-response").hide();
            $j(this).closest(".detail").find(".comment-submitted").fadeIn(1500,function(){
                comment_success = setTimeout(function(){
                    $j(this).closest(".detail").find(".comment-submitted").fadeOut();
                    $j(this).closest(".detail").find(".comment-trigger").show();
                },2000);
            });
            return false;
        });
		$leaderboard_profile.checkBeforeSubmit();
    },
    flag_or_comment_feed_action: function(){
        $form = $j(this).closest("div.form");
        url = $form.attr("rel");
        params = {};

        $form.find("span.input").each(function(i){
            params[$j(this).attr('rel')] = $j(this).html();
        });

        $form.find("select").each(function(i){
            params[this.name]= this.value;
        });
        $form.find("textarea").each(function(i){
            params[this.name] = this.value;
        });
        
		$j.ajax({
            url: url,
            dataType:"json",
            data: params,
            success: function(data){
                if(data.status == "success") {
                    tb_remove();
                } else {
                    alert("Submission failed");
                }
            }
        });
        return false;
    },
    post_activity_update: function(formObj) {
        params = {};
        $j(formObj).find("input").each(function(i){
            params[this.name] = this.value;
        });
        $textarea = $j(formObj).find("textarea");
        $textarea.each(function(i){
            params['commentText'] = $j(this).val();
            $j(this).val('');
        });
        url = $j(formObj).attr("action");

        $j.ajax({
            url: url,
            dataType: "json",
            data: params,
            method: "POST",
            success: function(data){
                if(data.status == "success") {
                    if(typeof(params['pageNum']) != "undefined") {
                        $leaderboard_profile.load_activity_feed(params['pageNum']);
                    } else {
                        $leaderboard_profile.load_activity_feed(1);
                    }
                } else {
                    alert('Could not be posted to activity feed');
                }
                $j(".activity-feed .more a").attr('pagenum',1);
            }
        });
        
    }

    
}

var $leaderboard_friends = {
    clear_pending_friend_requests: function() {
        $j(".pending .pending-requests").html(0);
    },
    decrement_pending_friend_requests: function() {
        pending_requests = $j(".pending .pending-requests").html();
        pending_requests--;
        $j(".pending .pending-requests").html(pending_requests);
        alert("Updating friends list");
        $leaderboard_friends.load_friends(1);
    },
    check_pending_count: function() {
        pending_requests = $j(".pending .pending-requests").html();
        if( pending_requests == 0 ) {
            $j(".pending").slideUp(1000);
        }
    },
    init: function(){
        default_friend_search = $j(".friend-search input.txt").attr("value");
        friend_search = "";
        $j(".friend-search input.txt").bind('focus',function(){
            if(this.value == default_friend_search) {
                this.value = '';
                friend_search = "";
            } else {
                friend_search = this.value;
            }
        });
        $j(".friend-search input.txt").bind('blur',function(){
            if(this.value == "") {
                this.value = default_friend_search;
            }
        });
        $j("#friend-search-form").submit(function(){
            q = $j(".friend-search input.txt").attr("value");
            if( q == "" || q == default_friend_search) {
                alert('Please provide search parameters');
                return false;
            }
            friend_search = q;
            $leaderboard_friends.load_friends(1);
            return false;
        });

        $j('.lb-filter-header form input.btn').click(function(){
            $leaderboard_friends.load_friends(1);
            return false;
        });

        $j(".pending .notice a.confirm").click(function(){
            a = this;
            $j.getJSON(this.href,function(data){
                if(data.status != "success") {
                    alert(data.errors.error.description);
                } else {
                    item = $j(a).closest("li");
                    $j(item).find(".notice").fadeOut(1000, function(){
                        $j(item).find(".added").fadeIn(1000,function(){
                            added = setTimeout(function(){
                                $j(item).fadeOut(1000);
                                $leaderboard_friends.check_pending_count();
                            },3000);
                        });
                    });
                    $leaderboard_friends.decrement_pending_friend_requests();
                }
            });
            return false;
        });
        $j(".pending .notice a.ignore").click(function(){
            a = this;
            $j.getJSON(this.href,function(data){
                if(data.status != "success") {
                    alert(data.errors.error.description);
                } else {
                    item = $j(a).closest("li");
                    $j(item).find(".notice").fadeOut(1000, function(){
                        $j(item).find(".ignored").fadeIn(1000,function(){
                            ignored = setTimeout(function(){
                                $j(item).fadeOut(1000);
                                $leaderboard_friends.check_pending_count();
                            },3000);
                        });
                    });
                    $leaderboard_friends.decrement_pending_friend_requests();
                }
                return false;
            });
            return false;
        });

        $j(".pending .all a.add").click(function(){
            a = this;
            $j.getJSON(this.href,function(data){
                if(data.status != "success") {
                    alert(data.errors.error.description);
                } else {
                    $j(a).closest(".pending").find("ul.requests").hide();
                    $j(a).closest(".pending").find("p.added").show();
                    $leaderboard_friends.clear_pending_friend_requests();
                    added_all = setTimeout(function(){
                        $leaderboard_friends.check_pending_count();
                    },3000);
                }
                return false;
            });
            return false;
        });
        $j(".pending .all a.ignore").click(function(){
            a = this;
            $j.getJSON(this.href,function(data){
                if(data.status != "success") {
                    alert(data.errors.error.description);
                } else {
                    $j(a).closest(".pending").find("ul.requests").hide();
                    $j(a).closest(".pending").find("p.ignored").show();
                    $leaderboard_friends.clear_pending_friend_requests();
                    removed_all = setTimeout(function(){
                        $leaderboard_friends.check_pending_count();
                    },3000);
                }
                return false;
            });
            return false;
        });
    },

    init_friends_results: function() {


        $j(".lb-friend-results #lb-friend-pager a").click(function(){
            page = this.rel;
            $leaderboard_friends.load_friends(page);
            return false;
        });

        $j("ul.friends a.remove").click(function(){
            a = this;
            $j.getJSON(this.href,function(data) {
                if(data.status != "success") {
                    alert(data.errors.error.description);
                } else {
                    $j(a).hide();
                    $j(a).closest(".actions").find(".removed").show();
                }
                return false;
            });
            return false;
        });


        $j(".lb-friend-results #lb-friend-pager a").click(function(){
            page = this.rel;
            $leaderboard_friends.load_friends(page);
            return false;
        });


    },
    load_friends: function(page) {
		$j("#friendspinner").show(); //show spinner
        params = {
            'pageNum':page,
            'searchPersonaName': friend_search
        };
        results_url = "/profile/user/friends/results";
        $j.ajax({
            type:"GET",
            url: results_url,
            data: params,
            dataType: "html",
            success: function(data){
                $j(".lb-friend-results").html(data);
                $leaderboard_friends.init_friends_results();
                tb_init(".lb-friend-results .thickbox");
				$j("div.pending").hide(); // hide the pending list
				$j("#keyword-results").show() //show the results bar
				$j("#friendspinner").hide(); // hide spinner
				$j("#rtnString").text('"'+q+'"'); // add result text
            }
        });

    },
    init_associations_results: function() {
        $j("ul.associations a.remove").click(function(){
        	a=this;
        	$j.getJSON(this.href,function(data) {
                if(data.status != "success") {
                    alert(data.errors[0].description);
                } else {
                    $j(a).hide();
                    $j(a).closest(".actions").find(".removed").show();
                }
                return false;
            });
            //$j(this).hide();
            //$j(this).closest(".actions").find(".removed").show();
            return false;
        });

        $j("ul.associations a.add").click(function(){
        	a=this;
        	$j.getJSON(this.href,function(data) {
                if(data.status != "success") {
                    alert(data.errors[0].description);
                } else {
                    $j(a).hide();
                    $j(a).closest(".actions").find(".added").show();
                }
                return false;
            });
            //$j(this).hide();
            //$j(this).closest(".actions").find(".added").show();
            return false;
        });
    },
    load_associatons: function(page) {
        $leaderboard_friends.init_associations_results();
        tb_init(".lb-records .associations .thickbox");
    }
}

var $leaderboard_head2head = {
    init: function(){
        $j(".user span").click(function(e){
            $j(".user .flyout").hide();
            $j(this).closest(".user").find(".flyout").show();
            return false;
        });
        $j(".user li.close a").click(function(){
            $j(".user .flyout").hide();
            return false;
        });

        $j(".user a.add").click(function(){
            a = this;
            $j.getJSON(this.href,function(data) {
                if(data.status != "success") {
                	alert(data.errors[0].description);
                } else {
                    $j(a).closest("li").hide();
                    $j(a).closest("ul").find(".added").show();
                }
            });
            return false;
        });
    },

    init_head2head_chooser: function(personaId,personaNamespace,personaName){

        $j(".head2head-chooser ul li").click(function(){
            url = "/profile/compare/head2head";
            comparePersonaId = $j(this).attr("id");
            comparePersonaName = $j(this).attr("rel");
            compareNamespace = personaNamespace;

            url = url + "?comparePersonaId=" + comparePersonaId;
            url = url + "&compareNamespace=" + compareNamespace;
            url = url + "&comparePersonaName=" + comparePersonaName;

            if(personaId != "") {
                url = url + "&friendPersonaId=" + personaId;
                url = url + "&friendNamespace=" + personaNamespace;
                url = url + "&friendPersonaName=" + personaName;
            }
            window.location = url;
            return false;
        });
    }
}

var $leaderboard_board = {
    max_pages : 99, //default
    default_player_search : "",
    init: function(){
		$filter = false;
		$j("#filter-results").hide();
        player_search = "";
        $j(".player-search input.txt").bind('focus',function(){
            if(this.value == $leaderboard_board.default_player_search) {
                this.value = '';
            }
        });
        $j(".player-search input.txt").bind('blur',function(){
            if(this.value == "") {
                this.value = $leaderboard_board.default_player_search;
                player_search = "";
            } else {
                player_search = this.value;
            }
        });
        $j(".player-search input.btn").click(function(){
            q = $j(".player-search input.txt").attr("value");
            if( q == "" || q == $leaderboard_board.default_player_search) {
                alert('Please provide a search string');
                return false;
            }
            return true;
        });

        $j('.lb-filter-header form input.btn').click(function(){
            $leaderboard_board.load_page(1);
			$filter = true;
            return false;
        });
		
		rel = $j(".view-players h4").attr("rel"); // check for initial state
        if(typeof(rel) === "undefined") { // if logged out
            $j("#platformFilter").show();
        } else if(rel!="all") {
            $j("#platformFilter").hide();
        } else {
			$j("#platformFilter").show();
		}
		
        $j(".view-players .chooseritems").click(function(){
            rel = $j(this).attr("rel");
            if(rel!="all") {
                $j("#platformFilter").hide();
            } else {
                $j("#platformFilter").show();
            }
        });

        $leaderboard_board.init_results();
    },
    init_results: function() {
        $j("#lb-records th.SCORE").addClass("sortable");
        $j("#lb-records th.SCORE").attr("id","sort-score");
        
        var query = $j(".player-search input.txt").attr("value");
        
        $j("#rtnString").html('"'+query+'"');

        // get rid of other functions?
        $j("table .player .detail li a").unbind();

        $j(".go-to input.btn").click(function(){
            page = $j(".lb-results input[name='go-to']").attr('value');
            if(!page || page == "" || isNaN(page)) {
                alert($leaderboard_board.message_invalid_page_number);
                return false;
            }
            if(page < 1){
                page = 1;
            }
            if(page > $leaderboard_board.max_pages) {
                page = $leaderboard_board.max_pages;
            }
            $leaderboard_board.load_page(page);
            return false;
        });

        $j("#lb-records th.SCORE").click(function(){
            sort_value = $j("input[name='sortScore']").attr('value');
            if(sort_value != "" && sort_value != null) {
                $j(this).removeClass(sort_value);
            }
            if(sort_value == "" || sort_value == "descending") {
                sort_value = "ascending";
            } else {
                sort_value = "descending";
            }
            $j(this).addClass(sort_value);
            $j(this).attr('rel',sort_value);
            $j("input[name='sortScore']").attr('value',sort_value);
            $leaderboard_board.load_page(1);
        });

        $j(".lb-results #lb-board-pager a").click(function(){
            page = $j(this).attr("rel");
            $leaderboard_board.load_page(page);
            return false;
        });

        $j("table .player .detail span").click(function(e){
            $j("table .player .detail .flyout").hide();
            $j(this).closest(".detail").find(".flyout").show();
            return false;
        });
        $j("table .player .detail li.close a").click(function(){
            $j("table .player .detail .flyout").hide();
            return false;
        });
        $j("table .player .detail a.add").click(function(){
            a = this;
            $j.getJSON(this.href,function(data) {
                if(data.status != "success") {
                	alert(data.errors[0].description);
                } else {
                    $j(a).closest("li").hide();
                    $j(a).closest("ul").find(".added").show();
                }
            });
            return false;
        });
           
    },
    load_page: function(page) {
        $j(".lb-results table").addClass("loading");
        params = {
            'pageNum':page,
            'filter': $j("input[name='filter']").attr('value'),
            'playMode': $j("input[name='playMode']").attr('value'),
            'platformType': $j("input[name='platformType']").attr('value'),
            'searchPersonaName': player_search,
            'sortScore': $j("input[name='sortScore']").attr('value'),
            'sortBy': "SCORE"
        };

        $rss_links = $j("a.rss");
        href = $rss_links.attr("href");
        href = href + "?filter="+params.filter+"&playMode="+params.playMode+"&platformType="+params.platformType;
        $rss_links.attr("href",href);

        results_url = "/leaders/results";
        $j(".lb-results input[name='go-to']").attr('value','');

        $j.ajax({
            type:"GET",
            url: results_url,
            data: params,
            dataType: "html",
            success: function(data){
                $j(".lb-results").html(data);
                $j(".lb-results table").removeClass("loading");
                $leaderboard_board.init_results();
                tb_init("table .player .detail .thickbox");
				if($filter === true) {
					$j("#filter-results").show();
				}
            }
        });
    }
}

var $leaderboard_stats = {
    init: function(friendPersonaId,friendNamespace,friendPersonaName){
        $j(".filter .chooser li").click(function(){
            //online = $j(this).attr("id");  //IE6 does not like this for some reason
            extra = "";
            if( friendPersonaId != "" ) {
                extra = "&friendPersonaId=" + friendPersonaId + "&friendNamespace=" + friendNamespace + "&friendPersonaName=" + friendPersonaName;
            }
            $j(".stats table").addClass("loading");
            location.href="/profile/statistics?playMode="+ $j(this).attr("id") + extra;
        });
    }
}


// binding for footer open/close
$j(document).ready(function(){
		$j('#footer-links')
            .hover(function() {
                $j('#footer #links').slideDown('slow');
            }, function() {
                $j('#footer #links').slideUp('slow');
            });
	})
