function Random() {
    var myDate = new Date();
    var rand = myDate.getTime();
    return rand;
}

function BidAuction(AuctionID){ 
	AuctionBid = document.getElementById('AuctionBid' + AuctionID).value
	$('#AuctionSubmit'+AuctionID).fadeTo('fast', 0);
	$('#left_wrapper').load('Marketplace/GetAuctions.php?AuctionID=' + AuctionID + '&AuctionBid=' + AuctionBid + '&Rand=' + Random());
}


//function BidAuction(AuctionID){
	//AuctionBid = document.Auction + AuctionID.AuctionBid + AuctionID.value;
//	alert ('admin test, please ignore');
	//$('#profile_right').load('Marketplace/GetAuctions.php?AuctionID=' + AuctionID + '&AuctionBid=' + AuctionBid + '&Rand=' + Random());
//}


function SignupLink(){

	// Expand Panel

		$("div#panel").slideDown("slow");
	
		$("#toggle a").toggle();


}

function HideForm(){
	$('.hiddenform').hide();
}

function RefreshAccountSummary(){
	$('#coinsandcommunityscore').load('Main/GetAccountSummary.php?Rand=' + Random());
}

function RefreshTips() {
	$('.tip').cluetip({splitTitle: '|', showTitle: true, arrows: true, dropShadow: false, clickThrough: true, positionBy: 'auto',
    fx: {open: 'fadeIn', openSpeed:  '3000'}, hoverIntent: {sensitivity: 3, interval: 200, timeout: 0}});
}

function RefreshCardPopUp() {
	$('a.cardlink').cluetip({showTitle: false, arrows: true, dropShadow: false, clickThrough: true, waitImage: true, positionBy: 'auto', width: 306, height: 409});
}

function Profile_Friends(UserID, Page) {
    $('#profile_friendcontainer').load('Profile/Friends.php?UserID=' + UserID + '&Page=' + Page + '&Rand=' + Random());
}

function Profile_Requests(UserID, Page) {
    $('#profile_right').load('Profile/Requests.php?UserID=' + UserID + '&Page=' + Page + '&Rand=' + Random());
}

function Profile_Photos(UserID, Page) {
    $('#profile_right').load('Profile/Photos.php?UserID=' + UserID + '&Page=' + Page + '&Rand=' + Random(), function() {
        $('a.lightbox').lightBox();
    });
}

function Profile_Thoughts(UserID, Page) {
    $('#profile_right').load('Profile/Thoughts.php?UserID=' + UserID + '&Page=' + Page + '&Rand=' + Random());
}

function Profile_Messages(UserID, Page) {
    $('#profile_right').load('Profile/Messages.php?UserID=' + UserID + '&Page=' + Page + '&Rand=' + Random());
}

function Profile_Achievements(UserID, Page) {
    $('#profile_right').load('Profile/Achievements.php?UserID=' + UserID + '&Page=' + Page + '&Rand=' + Random());
}

function SendThought() {
    ThoughtText = document.postthought.ThoughtText.value;
    ToUserID = document.postthought.ToUserID.value;

    var ThoughtText = ThoughtText.replace(new RegExp("\\n", "g"), " <br /> ");
    var ThoughtText = ThoughtText.replace(/&/g, "[amp]");
    var ThoughtText = ThoughtText.replace(/\+/g, "[plus]");

    if (document.postthought.ThoughtText.value.length > 0) {
        $.get("/Profile/ProcessThought.php?ThoughtText=" + ThoughtText + "&UserID=" + ToUserID + "&Rand=" + Random(), function(data) {
            $('#profile_right').load('Profile/Thoughts.php?UserID=' + ToUserID + '&Page=1&Rand=' + Random());
            document.postthought.ThoughtText.value = '';
        });
        closeform();
    }
}


function ProcessLogin() {
    $.post("/Main/ProcessLogin.php", {name: $('[name=loginname]').val(), pass: $('[name=loginpwd]').val()}, 
		function(data){
			$('#LoginError').html(data);
	});
}

function ProcessSignup() {
    $.post("/Main/ProcessSignup.php", {username: $('[name=newname]').val(), email: $('[name=newemail]').val(), agree: $('[name=agree]').val(), faction: $('[name=faction]').val(), refid: $('[name=refid]').val()}, 
		function(data){
			$('#SignupError').html(data);
	});
}


function ForgotPassword() {
    $.post("/Main/ProcessForgotPassword.php", {name: $('[name=newpasswordname]').val()}, 
		function(data){
			$('#NewPasswordError').html(data);	
	});
}

function ForgotUserName() {
    $.post("/Main/ProcessForgotUserName.php", {email: $('[name=forgotusernameemail]').val()}, 
		function(data){
			$('#UserNameError').html(data);	
	});
}


function SendMessage() {

    MessageText = document.postmessage.MessageText.value;
    ToUserID = document.postmessage.ToUserID.value;

    var MessageText = MessageText.replace(new RegExp("\\n", "g"), " <br /> ");
    var MessageText = MessageText.replace(/&/g, "[amp]");
    var MessageText = MessageText.replace(/\+/g, "[plus]");

    if (document.postmessage.MessageText.value.length > 0) {
        $.get("/Profile/ProcessMessage.php?MessageText=" + MessageText + "&UserID=" + ToUserID + "&Rand=" + Random(), function(data) {
        	HideForm();
            $.pnotify({pnotify_text: 'Your message has been sent'});
        });


    }
}

function RemoveFriend(UserID) {
    var answer = confirm("Remove Friend, are you sure?")
    if (answer) {
        $.get("/Profile/ProcessRemoval.php?UserID=" + UserID + "&Rand=" + Random(), function(data) {
            $('#profile_friendcontainer').load('Profile/Friends.php?Page=1&Rand=' + Random());
        });
    }
}

function AcceptFriend(ProfileUserID, Page, FriendUserID) {
    var answer = confirm("Accept Friend, are you sure?")
    if (answer) {
        $.get("/Profile/ProcessAccept.php?UserID=" + FriendUserID + "&Rand=" + Random(), function(data) {
            $('#profile_messagecontainer').load('Profile/Messages.php?UserID=' + ProfileUserID +'&Page=1&Rand=' + Random());
            $('#profile_friendcontainer').load('Profile/Friends.php?UserID=' + ProfileUserID +'&Page=1&Rand=' + Random());
         });
    }
}

function DeclineFriend(ProfileUserID, Page, FriendUserID) {
    var answer = confirm("Decline Friend, are you sure?")
    if (answer) {
        $.get("/Profile/ProcessDecline.php?UserID=" + FriendUserID + "&Rand=" + Random(), function(data) {
             $('#profile_messagecontainer').load('Profile/Messages.php?UserID=' + ProfileUserID +'&Page=1&Rand=' + Random());
        });
    }
}



function FindGame(ID) {
    $.get("/Lobby/ProcessDeck.php?Rand=" + Random(), function(data) {
        if (data == 1) {
            document.getElementById('lobby_overlay').style.display = 'block';
            $.get("/Lobby/ProcessGame.php?Rand=" + Random() + "&ID=" + ID, function(data) {
                if (data == 1) {
                    $.pnotify({pnotify_text: 'Game does not exist'});
                    setTimeout("window.location = 'Lobby.php'", 4000);
                }
                else
                if (data == 2) {
                    $.pnotify({pnotify_text: 'Game already started'});
					window.location = "Battle.php";
                }
                else {
                    window.location = "Battle.php";
                }
            });

        }
        else {
            $.pnotify({pnotify_text: '40 cards required for minimum deck size'});
        }
    });
}

function CancelGame(ID) {
    $.get("/Lobby/CancelGame.php?Rand=" + Random() + "&ID=" + ID, function(data) {
        $('#chat-games').load('/Lobby/GetActiveGames.php?Rand=' + Random());

    });


}


function ReadyGame(GameType) {
    $.get("/Lobby/ProcessDeck.php?Rand=" + Random(), function(data) {
        $('#chat-games').load('/Lobby/GetActiveGames.php?GameType=' + GameType + '&Rand=' + Random());
    });
}


function PollMessages(){

    $.get("/Lobby/PollMessages.php?Rand=" + Random(), function(data) {
        if (data > 0) {
           $.pnotify({pnotify_text: '<a href=\"Profile.php\" class=\"lightlink\" >You have ' + data + ' new message(s)</a>'});
        }
    });
    
    $.get("/Lobby/PollFriends.php?Rand=" + Random(), function(data) {
        if (data > 0) {
           $.pnotify({pnotify_text: '<a href=\"Profile.php\" class=\"lightlink\" >You have ' + data + ' friend requests(s)</a>'});
        }
    });
    
    $.get("/Lobby/PollVoting.php?Rand=" + Random(), function(data) {
        if (data == 1) {
           $.pnotify({pnotify_text: '<a href=\"http://www.mmorpg100.com/in.php?id=5832\" class=\"lightlink\" >You haven\'t voted today</a>'});
        }
        

    });

	setTimeout("PollMessages()", 30000);
}

/*
function PollLobbyStatus(){
	$('#lobby_gamestatus').load('/Lobby/GetGameStatus.php?Rand=' + Random());
	$('#chat-games').load('/Lobby/GetLobbyUsers.php?Rand=' + Random());
	setTimeout("PollLobbyStatus()", 10000);
}

function PollLobbyChat(){
	$.get("/Lobby/PollLobby.php?Rand=" + Random(), function(data) {
        if (data == 1) {
            $('#chat-area').load('/Lobby/GetLobbyChat.php?Rand=' + Random());
            
        }
    });
	setTimeout("PollLobbyChat()", 1000);
}	

function PollLobbyGames(){
	$('#lobby_availablegames').load('/Lobby/GetActiveGames.php?Rand=' + Random());
	
	$.get("/Lobby/PollGame.php?Rand=" + Random(), function(data) {
        if (data == 1) {
            window.location = "Battle.php";
        }
    });

    setTimeout("PollLobbyGames()", 4000);
}
*/


function PollLobby() {

	$.get("/Lobby/PollLobby.php?Rand="+Random(), 
		function(data) {
		
		var Resp = data;
		
		chatposition = Resp.indexOf("chat"); 
		gameposition = Resp.indexOf("game");	
	
			if (chatposition != -1){$('#chat-area').load('/Lobby/GetLobbyChat.php?Rand=' + Random());} 	
			if (gameposition != -1) {window.location = "Battle.php";} 

			$('#lobby_gamestatus').load('/Lobby/GetGameStatus.php?Rand=' + Random());
			$('#chat-games').load('/Lobby/GetActiveGames.php?Rand=' + Random());
			$('#lobby_availablegames').load('/Lobby/GetLobbyUsers.php?Rand=' + Random());
			
			setTimeout("PollLobby()", 4000);

		});
}


function GetReviews(CardID, ReviewPage) {
    $('#footer_wrapper_review').load('Community.php?ReviewCardID=' + CardID + '&ReviewPage=' + ReviewPage + '&Rand=' + Random(), function() {
        RefreshTips();
	    RefreshCardPopUp();
        HideForm();
        }
    );
}

function GetReviews_Profile(UserID, ReviewPage) {
    $('#profile_reviewcontainer').load('Profile/Review.php?UserID='+UserID+'&ReviewPage=' + ReviewPage + '&Rand=' + Random(), function() {
        RefreshTips();
	    RefreshCardPopUp();
        HideForm();
        }
    );
}

function GetPosts_Profile(UserID, ReviewPage) {
    $('#profile_postcontainer').load('Profile/Posts.php?UserID='+UserID+'&ReviewPage=' + ReviewPage + '&Rand=' + Random());
}

function GetMessages_Profile(UserID, Page) {
    $('#profile_messagecontainer').load('Profile/Messages.php?UserID=' + UserID + '&Page=' + Page + '&Rand=' + Random());
}


function GetUserMarketplace(Type, Page) {
    $('#left_wrapper').load('Marketplace/GetUserMarketplace.php?Type=' + Type + '&Page=' + Page + '&Rand=' + Random());
}

function GetGlobalMarketplace(Page) {
    $('#left_wrapper').load(Page + '&Rand=' + Random(), function() {
	    RefreshTips();
	    RefreshCardPopUp();
	 }
    );
}

function GetArtist_Gallery(Artist, Page) {

    $('#artist_gallery_wrapper').load('Artists/GetGallery.php?artist='+encodeURIComponent(Artist)+'&Page=' + Page + '&Rand=' + Random(), function(){
    	RefreshTips();
    	RefreshCardPopUp();
    	HideForm();
    	}
    );
}

function GetMembers(Search, Sort, Page) {
    $('#left_wrapper').load('Community/GetMembers.php?Search=' + Search + '&Sort=' + Sort + '&Page=' + Page + '&Rand=' + Random());
}


function ToggleDiv(element, targetpage, container) {

    if (document.getElementById(element).style.display == 'none') {
        $('#' + container).load('' + targetpage + '&Rand=' + Random(), function() {
        	
            $('#' + element).show("slow");
            $('#form_inner_wrapper').jScrollPane();
           prepform();
            
        });

        //ajaxpage(targetpage, container);
    }
    else if (document.getElementById(element).style.display == 'block') {
        //document.getElementById(element).style.display = 'none';
        //$('#'+element).toggle("slow");
        //ajaxpage('blank.php', container);
        $('#' + element).hide("slow");

        if (element != '') {
            $('#' + container).load('' + targetpage + '&Rand=' + Random(), function() {
            	
                $('#' + element).show("slow");
                $('#form_inner_wrapper').jScrollPane();
                prepform();
            });
        }

    }


/*
$('#'+container).load(''+targetpage+'&Rand='+Random(), function(){
$('#'+element).toggle("slow");
});
*/
}

function prepform(){

//alert('admin test, please refresh');
$('textarea.tinymce').tinymce({
	    script_url : '../Javascript/tiny_mce/tiny_mce.js',
	    mode : "textareas",
	    theme : "advanced",
	    plugins : "emotions,spellchecker,advhr,preview",
	    theme_advanced_buttons1 : "newdocument,|,bold,italic,underline,|,justifyleft,justifycenter,justifyright,fontselect,fontsizeselect,formatselect",
	    theme_advanced_buttons2 : "cut,copy,paste,|,bullist,numlist,|,outdent,indent,|,undo,redo,|,link,unlink,image,|,preview,|,forecolor,backcolor,|,spellchecker,advhr,removeformat,|,emotions",   
	    theme_advanced_buttons3 : false,   
	    theme_advanced_toolbar_location : "top",
	    theme_advanced_toolbar_align : "left",
	    theme_advanced_resizing : false
	});
}

function closeform() {

    $('#formcontainer').hide("slow");
}



function ToggleDiv_beta(element, targetpage, container) {
    $('#' + container).load('' + targetpage, function() {
        $('#' + element).toggle("slow");
        RefreshTips();
    });
}

function CloseComments() {
    var x = document.getElementsByName('comments');
    for (i = 0; i < x.length; i++) {
        x[i].style.display = "none";
    }

}

function RateCard(CardRating) {
    $('#review_rating').load('Reviews/GetCardRating.php?CardRating=' + CardRating + '&Rand=' + Random());
}

function RateArtist(CardRating, CardName) {
    $('#review_rating').load('Artists/GetArtRating.php?Card='+encodeURIComponent(CardName)+'&CardRating=' + CardRating + '&Rand=' + Random());
}


function VoteMMORPG100() {
    $.get("/Reviews/ProcessVote.php?VoteID=1&Rand="+Random(), function(data){
    window.location = " http://www.mmorpg100.com/in.php?id=5832";
    });
//    var myDate = new Date();
//    var rand = myDate.getTime();
//    var url = "/Reviews/ProcessVote.php?Rand=" + rand + "&VoteID=1";
//    xmlHttp = GetXmlHttpObject();
//    if (xmlHttp == null) {
//        alert("Browser does not support HTTP Request");
//        return;
//    }
//    xmlHttp.open("GET", url, false);
//    xmlHttp.send(null);

}

function DeleteReview(ReviewID, CardID, ReviewPage) {
    var answer = confirm("Delete, are you sure?")
    if (answer) {
        $.get("/Reviews/ProcessDelete.php?ReviewID=" + ReviewID + "&Rand=" + Random(), function(data) {
            $('#footer_wrapper').load('Library/GetCardReviews.php?ReviewCardID=' + CardID + '&ReviewPage=' + ReviewPage + '&Rand=' + Random());
        });
    }
}

function VoteReview(Rating, ReviewID, CardID, ReviewPage) {

    $.get("/Reviews/ProcessVote.php?ReviewID=" + ReviewID + "&Rating=" + Rating + "&CardID=" + CardID + "&Rand=" + Random(), function(data) {
        $('#footer_wrapper_review').load('Community.php?ReviewCardID=' + CardID + '&ReviewPage=' + ReviewPage + '&Rand=' + Random());
        });
    }

function VoteReview_Profile(Rating, ReviewID, UserID, ReviewPage) {
	
    $.get("/Reviews/ProcessVote.php?ReviewID=" + ReviewID + "&Rating=" + Rating + "&UserID=" + UserID + "&Rand=" + Random(), function(data) {
       $('#profile_reviewcontainer').load('Profile/Review.php?UserID='+UserID+'&ReviewPage=' + ReviewPage + '&Rand=' + Random(), function() {
        RefreshTips();
	    RefreshCardPopUp();
        HideForm();
        });
        });
    
    }



function VotePoll(PollID, TopicID) {
    $.get("/Reviews/ProcessVote.php?Rand=" + Random() + "&PollID=" + PollID + "&TopicID=" + TopicID, function(data) {
        $('#forum_pollwrapper').load('Forum/GetPoll.php?TopicID=' + TopicID + '&Rand=' + Random());
    });
}


function UploadAvatar() {
    filename = document.avatar.file.value;
}



function PostNewCommentary(ReviewRating) {
    ReviewCardID = document.postreview.ReviewCardID.value;
    ReviewBody = document.postreview.ReviewBody.value;
    ReviewStars = document.getElementById('starvalue').innerHTML
    var ReviewBody = ReviewBody.replace(new RegExp("\\n", "g"), " <br /> ");
    var ReviewBody = ReviewBody.replace(/&/g, "[amp]");
    var ReviewBody = ReviewBody.replace(/\+/g, "[plus]");

    if (document.postreview.ReviewBody.value.length <= 30) {
        $.pnotify({pnotify_text: 'Review too short'});
    }
    else if (document.postreview.ReviewBody.value.length > 9999) {
        $.pnotify({pnotify_text: 'Review body is too long (9999 characters max)'});
    }
    else if (ReviewStars < 1 || ReviewStars > 5) {
        $.pnotify({pnotify_text: 'Please rate the card'});
    }
    else {
        $.get("/Reviews/ProcessReview.php?ReviewCardID=" + ReviewCardID + "&ReviewBody=" + ReviewBody + "&ReviewRating=" + ReviewStars + "&Rand=" + Random(), function(data) {
            $('#footer_wrapper_review').load('Community.php?ReviewCardID=' + ReviewCardID + '&ReviewPage=1&Rand=' + Random());
            $('img.reflect').reflect({
                height: 0.2,
                opacity: 0.6
            });
            $('#formcontainer').hide("slow");
        });
    }
}


function PostReviewComment(ReviewID, ReviewCardID) {

    var formid = 'text' + ReviewID;
    CommentBody = document.getElementById(formid).value
    var CommentBody = CommentBody.replace(new RegExp("\\n", "g"), " <br /> ");
    var CommentBody = CommentBody.replace(/&/g, "[amp]");
    var CommentBody = CommentBody.replace(/\+/g, "[plus]");

    if (CommentBody.length == 0) {
        $.pnotify({pnotify_text: 'Comment required'});
    }
    else if (CommentBody.length > 200) {
        $.pnotify({pnotify_text: 'Comment too long (200 characters max)'});
    }
    else {
        $.get("/Reviews/ProcessComment.php?ReviewID=" + ReviewID + "&CommentBody=" + CommentBody + "&Rand=" + Random(), function(data) {
            $('#footer_wrapper_review').load('Community.php?ReviewCardID=' + ReviewCardID + '&ReviewPage=1&Rand=' + Random());
            $('img.reflect').reflect({
                height: 0.2,
                opacity: 0.6
            });
            $('#formcontainer').hide("slow");
        });
    }

}



/////////////////MESSAGES//////////////////////


function textCounter(field, countfield, maxlimit) {
    if (field.value.length > maxlimit) field.value = field.value.substring(0, maxlimit);
    else countfield.value = maxlimit - field.value.length;
}







function SwitchDeckCard(CardID, Deck, Switch, Page, Type, Faction, Order, Search, ShowOnlyCards) {
    $('#left_wrapper').load('Library/GetDecks.php?CardID=' + CardID + '&Deck=' + Deck + '&Switch=' + Switch + '&Page=' + Page + '&Type=' + Type + '&Faction=' + encodeURIComponent(Faction) + '&Order=' + Order + '&Search=' + Search + '&ShowOnlyCards='+ ShowOnlyCards + '&Rand=' + Random(), function() {
        RefreshCardPopUp();
        
    });

}

function ActivateDeck(Deck) {
    $('#left_wrapper').load('Library/GetDecks.php?ActivateDeck=' + Deck + '&Rand=' + Random(), function() {
        RefreshCardPopUp();
        $.pnotify({pnotify_text: 'Your primary deck has been changed'});
    });

}

function ClearDeck(Deck) {
    var answer = confirm("Are you sure you want to clear Deck " + Deck + "?")
    if (answer == true) {
        $('#left_wrapper').load('Library/GetDecks.php?ClearDeck=' + Deck + '&Rand=' + Random(), function() {
            RefreshCardPopUp();
        });

    }

}

function UpdateDeckName(DeckID) {
    var DeckName = document.getElementById(DeckID).value;

    $('#left_wrapper').load('Library/GetDecks.php?Deck=' + DeckID + '&DeckName=' + encodeURIComponent(DeckName) + '&Rand=' + Random(), function() {
        RefreshCardPopUp();
    });

}

function GetDeck(Set, Page, Type, Faction, Order, Search, Deck, ShowOnlyCards) {
    $('#left_wrapper').load('Library/GetDecks.php?Set=' + Set + '&Page=' + Page + '&Type=' + Type + '&Faction=' + encodeURIComponent(Faction) + '&Order=' + Order + '&Search=' + Search + '&Deck=' + Deck + '&ShowOnlyCards='+ ShowOnlyCards + '&Rand=' + Random(), function() {
        RefreshCardPopUp();
    });

}

function SellCard(CardID) {
    SaleValue = document.sellcard.salevalue.value;
    $('#popupform').load('Marketplace/SellCard.php?CardID=' + CardID + '&SaleValue=' + SaleValue + '&Rand=' + Random(), function() {
    	RefreshAccountSummary();
    });
}

function RecycleCard(CardID) {
    $('#popupform').load('Marketplace/RecycleCard.php?CardID=' + CardID + '&Recycle=1&Rand=' + Random(), function() {
    	RefreshAccountSummary();
    });
}

function ShoeboxCard(CardID) {
    SaleValue = document.sellcard.salevalue.value;
    $('#popupform').load('Marketplace/Shoebox.php?CardID=' + CardID + '&SaleValue=' + SaleValue + '&Rand=' + Random(), function() {
    	RefreshAccountSummary();
    });

}

function WantedCard(CardID) {
    SaleValue = document.sellcard.salevalue.value;
    $('#popupform').load('Marketplace/WantedCard.php?CardID=' + CardID + '&SaleValue=' + SaleValue + '&Rand=' + Random());
}

function TradeCard(CardID, CardName) {
    OfferCard1 = document.tradecard.offercard1.value;
    OfferCard2 = document.tradecard.offercard2.value;
    OfferCard3 = document.tradecard.offercard3.value;
    OfferCard4 = document.tradecard.offercard4.value;

    $('#popupform').load('Marketplace/TradeCard.php?CardID=' + CardID + '&OfferCard1=' + OfferCard1 + '&OfferCard2=' + OfferCard2 + '&OfferCard3=' + OfferCard3 + '&OfferCard4=' + OfferCard4 + '&Rand=' + Random(), function() {
    	RefreshAccountSummary();
    });

}

function ReclaimCard(MarketplaceLibraryID, Market) {
    $('#left_wrapper').load('Marketplace/GetUserMarketplace.php?Market=' + Market + '&MarketplaceLibraryID=' + MarketplaceLibraryID + '&Rand=' + Random(), function(){
    	RefreshAccountSummary();
    });
}

function MarketCard(Market, MarketplaceID) {
    $('#left_wrapper').load('Marketplace/GetGlobalMarketplace.php?Market=' + Market + '&MarketplaceID=' + MarketplaceID + '&Rand=' + Random());
}

function PurchaseShoebox(Market, ShoeboxID) {
    $('#left_wrapper').load('Marketplace/GetGlobalMarketplace.php?Market=' + Market + '&MarketplaceID=' + ShoeboxID + '&Rand=' + Random());
}

function SwapRoom(Room) {
    $('#chat-area').load('/Lobby/GetLobbyChat.php?Room=' + Room + '&Rand=' + Random(), function() {
        document.getElementById('chat-area').scrollTop = document.getElementById('chat-area').scrollHeight;
    });

}

function SetCountry(CountryID) {
    $('#popupform').load('Profile/GetCountryForm.php?CountryID=' + CountryID + '&Rand=' + Random(), function() {
    	$('#form_inner_wrapper').jScrollPane();
    });
}

///CHATS///
$(function() {

    $("#sendie").keydown(function(event) {

        var key = event.which;

        // all keys including return
        if (key >= 33) {

            var maxLength = $(this).attr("maxlength");
            var length = this.value.length;

            if (length >= maxLength) {
                event.preventDefault();
            }
        }
    });

    $('#sendie').keyup(function(e) {

        if (e.keyCode == 13) {

            var text = $(this).val();
            var maxLength = $(this).attr("maxlength");
            var length = text.length;

            if (length <= maxLength + 1) {

                $.ajax({
                    type: "POST",
                    url: "/Lobby/ProcessShout.php",
                    data: {
                        'MessageText': text,

                    },
                    dataType: "json",
                    success: function(data) {
                    
                        $('#chat-area').load('/Lobby/GetLobbyChat.php?Rand=' + Random(), function() {
                            document.getElementById('chat-area').scrollTop = document.getElementById('chat-area').scrollHeight;                            	
                            	
                        });

                    },
                });

                $(this).val("");
            } else {
                $(this).val(text.substring(0, maxLength));
            }

        }

    });

    $("#battlesendie").keydown(function(event) {

        var key = event.which;

        // all keys including return
        if (key >= 33) {

            var maxLength = $(this).attr("maxlength");
            var length = this.value.length;

            if (length >= maxLength) {
                event.preventDefault();
            }
        }
    });

    $('#battlesendie').keyup(function(e) {

        if (e.keyCode == 13) {

            var text = $(this).val();
            var maxLength = $(this).attr("maxlength");
            var length = text.length;

            if (length <= maxLength + 1) {

                $.ajax({
                    type: "POST",
                    url: "/Battle/ProcessChat.php",
                    data: {
                        'MessageText': text,

                    },
                    dataType: "json",
                    success: function(data) {

                        $('#battle_ticker').load('Battle/GetTicker.php?Rand=' + Random());

                    },
                });

                $(this).val("");
            } else {
                $(this).val(text.substring(0, maxLength));
            }

        }

    });


});


//FORUM
function textCounter(field, countfield, maxlimit) 
{
if (field.value.length > maxlimit)
field.value = field.value.substring(0, maxlimit);
else
countfield.value = maxlimit - field.value.length;
}


function PostNewTopic (){
TopicSubject = document.posttopic.TopicSubject.value;
TopicBody = document.posttopic.TopicBody.value;
GroupID = document.posttopic.GroupID.value;
Page = document.posttopic.Page.value;

var i = 0;
var PollOptions = '';
var x = document.getElementsByName('polloption');
for (i=0; i<x.length; i++)
	{
	var Opt = x[i].value;
	PollOptions = PollOptions + "&Opt"+i+"="+encodeURIComponent(Opt);
	}


	
var TopicBody = TopicBody.replace(new RegExp( "\\n", "g" ), " <br /> " );
var TopicBody = TopicBody.replace(/&/g, "[amp]");
var TopicBody = TopicBody.replace(/\+/g,"[plus]");


if(x.length == 1)
{
$.pnotify({pnotify_text: 'At least two options are required for a poll'});
}
else
if(document.posttopic.TopicSubject.value.length == 0)
{
$.pnotify({pnotify_text: 'Topic subject required'});
}
	else if(document.posttopic.TopicSubject.value.length > 100)
	{
	$.pnotify({pnotify_text: 'Topic subject too long (50 characters max)'});
	}
		else if(document.posttopic.TopicBody.value.length == 0)
		{
		$.pnotify({pnotify_text: 'Topic message required'});
		}
			else if(document.posttopic.TopicBody.value.length > 9999)
			{
			$.pnotify({pnotify_text: 'Topic message too long (999 characters max)'});
			}
				else
				{
				
							
				$('#left_wrapper').load("/Forum/GetTopics.php?GroupID="+GroupID+"&Page="+Page+"&NewTopic=1&TopicSubject="+encodeURIComponent(TopicSubject)+"&TopicBody="+encodeURIComponent(TopicBody)+PollOptions + "&Rand=" + Random(), function(data) {
					HideForm();
				});
				
				}
}


function PostNewReply (){

ReplyBody = document.postreply.ReplyBody.value;
GroupID = document.postreply.GroupID.value;
TopicID = document.postreply.TopicID.value;
Page = document.postreply.Page.value;
var ReplyBody = ReplyBody.replace(new RegExp( "\\n", "g" ), " <br /> " );
var ReplyBody = ReplyBody.replace(/&/g, "[amp]");
var ReplyBody = ReplyBody.replace(/\+/g,"[plus]");

	
if(document.postreply.ReplyBody.value.length == 0)
{
$.pnotify({pnotify_text: 'Reply message required'});
}
else
	{
	
	//alert ("/Forum/GetMessages.php?TopicID="+TopicID+"&GroupID="+GroupID+"&Page="+Page+"&ReplyBody="+ReplyBody+"&NewMessage=1&Rand=" + Random());
	
	$('#left_wrapper').load("Forum/GetMessages.php?TopicID="+TopicID+"&GroupID="+GroupID+"&Page="+Page+"&ReplyBody="+encodeURIComponent(ReplyBody)+"&NewMessage=1&Rand=" + Random(), function(data) {
		HideForm();
	});
	
	}
}

function PostArtistMessage (){

ReplyBody = document.artistpostreply.ArtistReplyBody.value;
GroupID = document.artistpostreply.GroupID.value;
TopicID = document.artistpostreply.TopicID.value;
CardName = document.artistpostreply.Card.value;
Page = document.artistpostreply.Page.value;
Artist = document.artistpostreply.Artist.value;
var ReplyBody = ReplyBody.replace(new RegExp( "\\n", "g" ), " <br /> " );
var ReplyBody = ReplyBody.replace(/&/g, "[amp]");
var ReplyBody = ReplyBody.replace(/\+/g,"[plus]");



if(document.artistpostreply.ArtistReplyBody.value.length == 0)
{
$.pnotify({pnotify_text: 'Reply message required'});
}
else
	{
	
	//alert ("/Forum/GetMessages.php?TopicID="+TopicID+"&GroupID="+GroupID+"&Page="+Page+"&ReplyBody="+ReplyBody+"&NewMessage=1&Rand=" + Random());
	
	$('#artist_message_wrapper').load("Artists/GetMessages.php?TopicID="+TopicID+"&GroupID="+GroupID+"&Card="+encodeURIComponent(CardName)+"&Page="+Page+"&ReplyBody="+encodeURIComponent(ReplyBody)+"&artist="+encodeURIComponent(Artist)+"&NewMessage=1&Rand=" + Random(), function(data) {
		HideForm();
	});
	
	}
}




function PostEdit (){
ReplyBody = document.postreply.ReplyBody.value;
PostID = document.postreply.PostID.value;
GroupID = document.postreply.GroupID.value;
TopicID = document.postreply.TopicID.value;
Page = document.postreply.Page.value;
var ReplyBody = ReplyBody.replace(new RegExp( "\\n", "g" ), " <br /> " );
var ReplyBody = ReplyBody.replace(/&/g, "[amp]");
var ReplyBody = ReplyBody.replace(/\+/g,"[plus]");

if(document.postreply.ReplyBody.value.length == 0)
{
$.pnotify({pnotify_text: 'Message required'});
}
else
	{
	
	$('#left_wrapper').load("/Forum/GetMessages.php?TopicID="+TopicID+"&GroupID="+GroupID+"&PostID="+PostID+"&Page="+Page+"&ReplyBody="+encodeURIComponent(ReplyBody)+"&NewEdit=1&Rand=" + Random(), function(data) {
		HideForm();
	});
	
	}
}


function SetFacebookSignupCookie(Url){

	var ChosenName = document.signup_form.newname.value;
	var ChosenEmail = document.signup_form.newemail.value;
	var ChosenDeck = document.signup_form.faction.value;
	var today = new Date();
	var expire = new Date();
	expire.setTime(today.getTime() + 3600000*24*30);
	document.cookie = "Name=" +escape( ChosenName ) + ";path=/;domain=fallenworldsonline.com" + ";expires="+expire.toGMTString();
	document.cookie = "Email=" +escape( ChosenEmail ) + ";path=/;domain=fallenworldsonline.com" + ";expires="+expire.toGMTString();
	document.cookie = "Faction=" +escape( ChosenDeck ) + ";path=/;domain=fallenworldsonline.com" + ";expires="+expire.toGMTString();
	
	$.post("/Main/ProcessSignup.php", {username: $('[name=newname]').val(), email: $('[name=newemail]').val(), agree: $('[name=agree]').val(), faction: $('[name=faction]').val()}, 
		function(data){
			$('#SignupError').html(data);

			if (data.indexOf("registering") != -1){window.location = Url};
			
	});
}

function SetFacebookMergeCookie(Url){

	var LoginName = document.login_form.loginname.value;
	var LoginPwd = document.login_form.loginpwd.value;
	var today = new Date();
	var expire = new Date();
	expire.setTime(today.getTime() + 3600000*24*30);
	document.cookie = "Name=" +escape( LoginName ) + ";path=/;domain=fallenworldsonline.com" + ";expires="+expire.toGMTString();
	document.cookie = "Pwd=" +escape( LoginPwd ) + ";path=/;domain=fallenworldsonline.com" + ";expires="+expire.toGMTString();
	
	window.location = Url;
	
//	$.post("/Main/ProcessLogin.php", {name: $('[name=loginname]').val(), pass: $('[name=loginpwd]').val()}, 
//		function(data){
//			$('#LoginError').html(data);
//			if (data.indexOf("redirecting") != -1){window.location = Url};
//	});
	
	
}

