/*
if(parent !== self){
parent.location.replace('http://www.belugerinstudios.com');
}
*/

//VALIDASI
var VALID_ON_STRING = /[a-z]|[A-Z]+/;
var VALID_ON_EMAIL = /^([0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*@([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,9})$/;
var VALID_ON_FILL = /[a-z | A-Z | 0-9]/;
var VALID_ON_NUMBER = /[^a-zA-Z]+/;

var VALID_ON_USERNAME = /^[a-zA-Z][a-z0-9A-Z]{5,}$/
var VALID_ON_PASSWORD = /^[a-zA-Z0-9]{6,}$/

function validate(regex,component,message){
    if(!regex.test($(component).val())){
        $(component).css({border: "1px solid red", background: "url(image/layout/notavailable.png) no-repeat right #880000"});
        $(component).focus();
        return false;
    }else{
        $(component).css({border: "1px solid green", background: "url(image/layout/available.png) no-repeat #005500 right"});
        return true;
    }
}


function MM_jumpMenu(targ,selObj,restore){ //v3.0
    eval(targ+".location='"+selObj.options[selObj.selectedIndex].value+"'");
    if (restore) selObj.selectedIndex=0;
}

$(function(){

    //Js Gallery
    $("a[rel^='prettyPhoto']").prettyPhoto({
        theme: 'dark_rounded'
    });

    $("#btAddMyWebsite").click(function(){
        $("#addMyWebsitewindow").modal({
            opacity:80
        });    
    })

    $("#btSumitMyGame").click(function(){

        var tempData =  $("#addmygamecontainer").html();

        $("#addmygamecontainer").find("p").each(function(){
            $(this).hide();
        }) 

        $("#messageforaddgame").show();

        $.get("action.php",{act: "addmygametoportals", url: $("#inputurladdmygame").val()}, function(msg){       
            $("#messageforaddgame").hide(); 
            if(msg=="success"){
                $("#addmygamecontainer").html("<br/><strong style=\"color: white; padding-top: 10px;\">Thanks for your submit, we will review your game's url immediately</strong>");
            }else{
                $("#addmygamecontainer").html("<br/><strong style=\"color: red; padding-top: 10px;\">Fail to connect to our server! Please reload the page and try again.</strong>"); 
            }
        });   
    })

    //ourgames tooltip
    $(".root_ourgames_class").each(function(){
        $(this).tooltip({ 
            delay: 0,
            track: true, 
            bodyHandler: function() { 
                return "<h2>"+$(this).attr("caption")+"</h2><h3>"+$(this).attr("played")+"</h3><h3>"+$(this).attr("rating")+"</h3><p>"+$(this).attr("desc")+"</p>"; 
            }, 
            showURL: false 
        });
    });



    //hotgames tooltips
    $(".hotgames_item").each(function(){
        $(this).tooltip({ 
            delay: 0,
            track: true, 
            bodyHandler: function() { 
                return "<h2>"+$(this).attr("caption")+"</h2><h3>"+$(this).attr("played")+"</h3><h3>"+$(this).attr("rating")+"</h3><p>"+$(this).attr("desc")+"</p>"; 
            }, 
            showURL: false 
        });
    });

    /* $(".root_ourgames_class").each(function(){
    $(this).simpletip({
    content: "<h2>"+$(this).attr("caption")+"</h2><h3>"+$(this).attr("played")+"</h3><h3>"+$(this).attr("rating")+"</h3>"+$(this).attr("alt"), 
    fixed: true,
    offset: [55,-40],
    //fixed: false,
    //offset: [8,8],
    position: 'bottom',
    showEffect: 'none',
    hideEffect: 'none'
    })
    }); */

    //recent game tooltip
    $(".root_recentgames_class").each(function(){
        $(this).tooltip({ 
            delay: 0,
            track: true, 
            bodyHandler: function() { 
                return "<h2>"+$(this).attr("caption")+"</h2><h3>"+$(this).attr("played")+"</h3><h3>"+$(this).attr("rating")+"</h3><p>"+$(this).attr("desc")+"</p>"; 
            }, 
            showURL: false 
        });
    });


    /* $(".root_recentgames_class").each(function(){
    $(this).simpletip({
    content: "<h2>"+$(this).attr("caption")+"</h2><h3>"+$(this).attr("played")+"</h3><h3>"+$(this).attr("rating")+"</h3>"+$(this).attr("alt"), 
    //fixed: true,
    //offset: [52,-40],
    fixed: false,
    offset: [8,8],
    position: 'bottom',
    showEffect: 'none',
    hideEffect: 'none'
    })
    }); */

    //list challenge game tooltip
    $(".challengelist_class").each(function(){
        $(this).tooltip({ 
            delay: 0,
            track: true, 
            bodyHandler: function() { 
                return "<h3>"+$(this).attr("caption")+"</h3>"; 
            }, 
            showURL: false 
        });
    });
    /* $(".challengelist_class").each(function(){
    $(this).simpletip({
    content: "<h3>"+$(this).attr("caption")+"</h3>", 
    //fixed: true,
    //offset: [52,-40],
    baseClass: "challengelist_baseclass",
    fixed: false,
    offset: [8,8],
    position: 'bottom',
    showEffect: 'none',
    hideEffect: 'none'
    })
    }); */

    //flash game featured slider
    $("#featuredgame_slider").cycle({
        fx:     'scrollHorz',
        speed:   800,
        timeout: 10000,
        next: "#nextfeaturedgames",
        prev: "#beforefeaturedgames"
    });


    var thisPos=Math.round(parseInt($("#flashplay_width").val())/860 * 120);
    var statisPos = Math.round(parseInt($("#flashplay_width").val())/860 * 120);
    //flashgameplayer scalling
    $("#slider").slider({
        value: statisPos,
        min: 50, 
        max: 120,
        step: 1,
        slide: function(event, ui) {

            posX = ui.value;
            cWidth = posX/statisPos * $("#flashplay_width").val();
            cHight = posX/statisPos * $("#flashplay_height").val();

            $("#flashplay").attr("width", cWidth);
            $("#flashplay").attr("height", cHight);

            thisPos = $("#slider").slider('option','value');

        }
    });

    $("#minimizebutton").click(function(){
        if(thisPos > 50){
            var min = thisPos - 8;
            thisPos = min;
            $("#slider").slider('option','value',min);
            posX = min;
            cWidth = posX/statisPos * $("#flashplay_width").val();
            cHight = posX/statisPos * $("#flashplay_height").val();
            $("#flashplay").attr("width", cWidth);
            $("#flashplay").attr("height", cHight);
        }
    });

    $("#maximizebutton").click(function(){
        if(thisPos < 120){
            var max = thisPos + 8;
            thisPos = max;
            $("#slider").slider('option','value',max);
            posX = max;
            cWidth = posX/statisPos * $("#flashplay_width").val();
            cHight = posX/statisPos * $("#flashplay_height").val();
            $("#flashplay").attr("width", cWidth);
            $("#flashplay").attr("height", cHight);
        }
    });

    $("#resetbutton").click(function(){
        $("#slider").slider('option','value',100);
        posX = statisPos;
        cWidth = posX/statisPos * $("#flashplay_width").val();
        cHight = posX/statisPos * $("#flashplay_height").val();
        $("#flashplay").attr("width", cWidth);
        $("#flashplay").attr("height", cHight);
        thisPos = statisPos;
    });

    function requestRating(){
        $("#ratingcontainer").hide();
        $("#ratingsubmit").show();
        //$(".rating").rating('readOnly',true);
    }

    //jrating
    $("#ratingsubmit").css({visibility: "visible"});
    $("#ratingcontainerinterface").css({visibility: "visible"});
    $("#ratingdescription").css({visibility: "visible"});

    $("#ratingcontainerinterface").hide();
    $("#ratingdescription").hide();
    $("#ratingsubmit").hide();

    $("#ratingcontainer").hover(
    function(){
        $("#static_ratingcontainer").hide();
        $("#ratingcontainerinterface").show();
        $("input.rating").rating({			   
            callback: function(value, link){

                $.ajax({
                    type: "GET",
                    dataType: "xml",
                    url: "action.php",
                    data: "act=rate&gameid="+ $("#gameid").val() +"&point="+ value,
                    beforeSend: requestRating,
                    success: function(result){
                        //alert(result);
                        if($(result).find("result").text() == "notallowed"){
                            var note = $(result).find("note").text();
                            alert("Error - Rating. You've already voted on this game today. You'll have to wait until tomorrow before you can vote on it again!\n\nIf you believe you have not voted on this entry in the past 24 hours, it's possible someone else using your ISP shares your unique IP address and has already voted on this submission, especially if you are on a large ISP such as AOL. \n\nYou will able to vote again in "+note);

                            $("#ratingcontainer").show();
                            $("#ratingsubmit").hide();
                        }else{
                            var getRating = $(result).find("rating");
                            var getAddingRate = $(result).find("addtorating");

                            $("#ratingcaption_right").html(getRating.text() + "/5");
                            $("#static_ratingfill").width(Math.round(getRating.text()/5 * 165));
                            $("#ratingcontainer").show();
                            $("#ratingsubmit").hide();
                            $("#ratingdescription").text(getAddingRate.text());
                            $("#ratingdescription").show();
                        }
                    }
                }) 
                //alert(value);
            }
        });
    },
    function(){
        $("#ratingcontainerinterface").hide();
        $("#static_ratingcontainer").show();
    }
    )


    function requestRegister(){
        $("#registrationform").append("<div  id='registerloading' style='float: left; margin-left: 130px; width: 210px; height: 24px; border: 1px solid #CCCCCC; text-align: right'><div style='float: left; color: white; font-weight: normal;'><img src='image/layout/loading.gif' width='24' /></div><div style='float: left; padding-top: 5px; padding-left: 8px; color: #FFFFFF; font-size: 10px; '>processing your registration...</div></div>");
    }


    //Register
    //validating

    $("#registerusername").keypress(function(){
        valid = validate(VALID_ON_USERNAME,"#registerusername","");
        $("#usernameconfirm").html("");
    });

    $("#registerpassword").keypress(function(){
        valid = validate(VALID_ON_PASSWORD,"#registerpassword","");
    });

    $("#registeremail").keypress(function(){
        valid = validate(VALID_ON_EMAIL,"#registeremail","");
    });

    $("#registerusername").blur(function(){
        if(validate(VALID_ON_USERNAME,"#registerusername","")){
            $.ajax({
                type: "GET",
                url: "action.php",
                data: "act=checkuser&username="+ $("#registerusername").val(),
                beforeSend: function(){
                    $("#usernameconfirm").html("<span style=\"font-size: 11px;\">checking...</span>");
                },
                success: function(result){
                    if(result=="available"){
                        $("#usernameconfirm").html("<span style=\"color: green; font-size: 11px;\">this username is available</span>");
                    }else{
                        $("#usernameconfirm").html("<span style=\"color: red; font-size: 11px; \">not available</span>");
                    }
                }
            })
        }
    });

    $("#register").click(function(){
        $("#register").hide();
        $.ajax({
            type: "GET",
            url: "action.php",
            data: "act=register&username="+ $("#registerusername").val() +"&password="+ $("#registerpassword").val() +"&email=" + $("#registeremail").val(),
            beforeSend: requestRegister,
            success: function(result){
                if(result=="success"){    
                    $("#formregistration").html("Thank you for signing up. Now, You can upload your contents, vote the contents and more.");
                }else{
                    alert("Error - Registration. Please follow the intruction to complete registration");
                    $("#register").show();
                    $("#registerloading").remove();
                }
            }
        })
    });


    $("#registerbgbattlebutton").click(function(){
        $("#registerbgbattlebutton").hide();
        $.ajax({
            type: "GET",
            url: "action.php",
            data: "act=registerandlogin&username="+ $("#registerusername").val() +"&password="+ $("#registerpassword").val() +"&email=" + $("#registeremail").val(),
            beforeSend: requestRegister,
            success: function(result){

                if(result=="granted"){ 
                    alert('Thank For Register to BG BATTLE');
                    window.location.replace('index.php?act=profile&val=startplay');   
                    // $("#formregistration").html("Thank you for signing up, please check your email to confirm your registration.");
                }else{
                    alert("Error - Registration. Please follow the intruction to complete registration");
                    $("#register").show();
                    $("#registerloading").remove();
                }
            }
        })
    });

    //Menu Links
    $("#showlinks").click(function(){
        $("#linklist").modal({
            opacity:80
        });	
    });

    //NewsLetter
    $("#newsletter").click(function(){
        $("#newsletterwindow").modal({
            opacity:80
        });	
    });

    //gameintruction
    $("#flashplayer_intruction").hide();
    $("#gameintruction").click(
    function(){
        $("#flashplayer_intruction").css({visibility: "visible"});
        $("#flashplayer_intruction").slideDown();
    }
    );
    $("#flashplayer_intruction").click(function(){
        $("#flashplayer_intruction").slideUp();
    });

    //subscribe
    //validation
    $("#subscribe").keypress(function(){
        validate(VALID_ON_EMAIL,"#subscribe","");
    });

    //search player all
    $("#playersearchall").click(function(){
        $("#keyword").val("");
        $("#playerswindow").modal({
            opacity:80,
            containerCss:{
                height:550
            }
        });	

        $("#findplayer_body").load("include/modul/findplayer.php?findplayer=");

    });
    
     //search player all from profile page
    $("#rankchallenge").click(function(){
        
        $("#playerswindow").modal({
            opacity:80,
            containerCss:{
                height:550
            }
        });    

        $("#findplayer_body").load("include/modul/findplayer.php?findplayer=");

    });
    
    $("#findplayer").click(function(){
        $("#playerswindow").modal({
            opacity:80,
            containerCss:{
                height:550
            }
        });	

        $("#findplayer_body").load("include/modul/findplayer.php?findplayer="+$("#keyword").val());
    });

    //site search
    $("#btsearch").click(function(){
        if($("#keywordsite").val()=="Search..."){
            alert('Please, enter your keyword');
        }else{
            keyword = $("#keywordsite").val().replace(" ","+");
            $("#searchresultwindow").modal({
                opacity:80,
                containerCss:{
                    height:550
                }
            });      
            $("#searchresultwindow_body").load("include/modul/searchresult.php?keyword="+keyword+"&filter="+$("#filter").val());
        }
    });

    //Newest game navigation -----------------------------------
    var start=0;
    var show = 35;

    if($("#genre").val() !== ""){
        show = 35;
    }

    $("#ourgames"+$("#genre").val()+"_content").load("include/modul/newestgames.php?act="+$("#act").val()+"&start=0&limit="+show+"&genre="+$("#genre").val());

    var maxgames = $("#totalnewestgames"+$("#genre").val()).val();
    $("#newestgamesnavigation").text("1 - " + show);
    $("#totalofgames").text(maxgames);




    $("#nextnewestgames").click(function(){
        if(start < maxgames - show){
            $("#newestgamesnavigation").text((start+show+1) + " - " + (start+ 2*show));
            $("#ourgames"+$("#genre").val()+"_content").html("<div style=\"margin-top: 100px;\" align=\"center\"><img src=\"image/layout/loadingbar.gif\" alt=\"loading...\" /></div>");
            start = start + show;
            $("#ourgames"+$("#genre").val()+"_content").load("include/modul/newestgames.php?act="+$("#act").val()+"&start="+start+"&limit="+show+"&genre="+$("#genre").val());
        }

    });

    $("#beforenewestgames").click(function(){
        if(start > 0){
            $("#newestgamesnavigation").text((start-(show-1)) + " - " + (start));
            $("#ourgames"+$("#genre").val()+"_content").html("<div style=\"margin-top: 100px;\" align=\"center\"><img src=\"image/layout/loadingbar.gif\" alt=\"loading...\" /></div>");
            start = start - show;
            $("#ourgames"+$("#genre").val()+"_content").load("include/modul/newestgames.php?act="+$("#act").val()+"&start="+start+"&limit="+show+"&genre="+$("#genre").val());
        }

    });
    //--------------------------------

    //game not load
    function requestGameNotLoad(){
        $("#gamenotloadli").html("<span style=\"color: #FFCC00;\">Sending Report...</span>");
    }

    $("#gamenotload").click(function(){
        $.ajax({
            type: "GET",
            url: "action.php",
            data: "act=gamenotload&gameid="+ $("#gameid").val(),
            beforeSend: requestGameNotLoad,
            success: function(result){
                if(result == "success"){
                    $("#gamenotloadli").html("<span style=\"color: #FFCC00;\">Report Sent! Thanks for reporting.</span>");
                }else{
                    alert('Error - Report. Fail to conect to out server, make sure your computer is connected with internet');
                }
            }
        });

    });

    $("#gamenotloadshowme").click(function(){
        $("#gamenotload_fixit").slideDown('slow');
    });



    //cover flash player
    $("#closecover").click(function(){
        $("#flashplayer_cover").fadeOut();
    });

    //cover timer

    $("#covertimer").countdown({
        until: +20, 
        compact: true, 
        format: 'S', 
        onExpiry: function(){
            $("#flashplayer_cover").fadeOut();
        }
    });

    //report bug
    $("#reportbug").click(function(){
        $("#contactus").modal({
            opacity:80,
            containerCss:{
                height:600
            }
        });	
    });

    $("#footercontactus").click(function(){
        $("#contactus").modal({
            opacity:80,
            containerCss:{
                height:600
            }
        });	
    });

    //contact us
    function requestContactUs(){
        $("#btcontactus_container").html("<span style=\"color: white; font-weight: bold;\">Sending....</span>");
    }

    $("#btcontactus").click(function(){
        $.ajax({
            type: "GET",
            url: "action.php",
            data: "act=contactus&subject="+$("#subject").val()+"&email="+$("#email").val()+"&gameid="+$("#gameid").val()+"&description="+$("#description").val(),
            beforeSend: requestContactUs,
            success: function(result){
                if(result=="success"){
                    $("#btcontactus_container").html("<span style=\"color: #FFCC00; font-weight: bold;\">Sent! Thank you for contacting us.</span>");
                }else{
                    $("#btcontactus_container").html("<span style=\"color: red; font-weight: bold;\">Fail connect to our server, please try again latter.</span>");
                }
            }
        });
    });

    //Best Game List 
    $("#recentgames_container").html("<div style=\"padding: 15px; border: 1px solid #999999; background:#CCCCCC;\" align=\"center\"><img src=\"image/layout/loading2.gif\" alt=\"loading...\" /></div>");
    $("#recentgames_container").load("include/modul/bestgames.php?act="+$("#act").val());

    //Best Game Of The Year 
    $("#bestgameoftheyear_container").html("<div style=\"margin-top: 3px; padding: 15px; border: 1px solid #CE7B00; background:#FFEFB0;\" align=\"center\"><img src=\"image/layout/loading2.gif\" alt=\"loading...\" /></div>");
    $("#bestgameoftheyear_container").load("include/modul/bestgamesoftheyear.php?act="+$("#act").val());

    //Delete game
    $("#deletegame").click(function(){
        if(window.confirm("Are you sure to delete this game?")==true){
            window.location="admin/action.php?act=delete&val=" + $("#gameid").val();
        }else{

        }
    });

    $("#editprofile").toggle(
    function(){
        $("#fullname .row_class_right input").removeAttr("disabled");
        $("#fullname .row_class_right input").attr("class","inputenabled");

        $("#location .row_class_right input").removeAttr("disabled"); 
        $("#location .row_class_right input").attr("class","inputenabled");

        $("#ym .row_class_right input").removeAttr("disabled");
        $("#ym .row_class_right input").attr("class","inputenabled");

        $("#gt .row_class_right input").removeAttr("disabled");
        $("#gt .row_class_right input").attr("class","inputenabled");      

        $("#msn .row_class_right input").removeAttr("disabled");
        $("#msn .row_class_right input").attr("class","inputenabled");

        $("#website .row_class_right input").removeAttr("disabled");
        $("#website .row_class_right input").attr("class","inputenabled");

        $(this).html("<img border=0 src=\"image/layout/save.png\"/>");
    },
    function(){
        $(this).html("<img border=0 src=\"image/layout/edit.png\"/>");
        $.ajax({
            type: "GET",
            url: "action.php",
            data: "act=updateprofile&name="+$("#fullname_edit").val()+"&location="+$("#location_edit").val()+"&ym="+$("#ymedit").val()+"&gt="+$("#gtedit").val()+"&msn="+$("#msnedit").val()+"&website="+$("#websiteedit").val(),
            beforeSend: function(){
                $("#editprofile").html("<img border=0 src=\"image/layout/loading2.gif\"/>"); 
            },    
            success: function(result){
                // alert(result);   
                $("#editprofile").html("<img border=0 src=\"image/layout/edit.png\"/>");
                if(result=="success"){
                    $("#fullname .row_class_right input").attr("disabled","disabled");
                    $("#fullname .row_class_right input").attr("class","inputdisabled");

                    $("#location .row_class_right input").attr("disabled","disabled"); 
                    $("#location .row_class_right input").attr("class","inputdisabled");

                    $("#ym .row_class_right input").attr("disabled","disabled");
                    $("#ym .row_class_right input").attr("class","inputdisabled");

                    $("#gt .row_class_right input").attr("disabled","disabled");
                    $("#gt .row_class_right input").attr("class","inputdisabled");      

                    $("#msn .row_class_right input").attr("disabled","disabled");
                    $("#msn .row_class_right input").attr("class","inputdisabled");

                    $("#website .row_class_right input").attr("disabled","disabled");
                    $("#website .row_class_right input").attr("class","inputdisabled"); 
                }else{
                    alert("Error - Update Profil. You may enter some invalid data!");

                }
            }

        }); 


    } 

    );

    //edit foto
    $("#profilebox_generalinfo_left").hover(
    function(){

        $("#editfoto").fadeIn("fast");
    },
    function(){
        $("#editfoto").fadeOut("fast");  
    });

    $("#editfoto > a").click(function(){
        $("#fotouploadlayer").show();
        $("#fotoupload").fadeIn("fast");
    });

    $("#fotouploadlayer").click(function(){
        $("#fotouploadlayer").hide();
        $("#fotoupload").fadeOut("fast");
    });

    //fokus on avatar field
    $("#uploadfoto_field").focus(function(){
        $(this).val("");
    })
    //Change foto avatar
    $("#submitfoto").click(function(){
        if($("#uploadfoto_field").val() != "Enter URL to your avatar here" && $("#uploadfoto_field").val() != ""){

            $.ajax({
                type: "GET",
                url: "action.php", 
                data: "act=updateavatar&url="+$("#uploadfoto_field").val(),
                beforeSend: function(){
                    $("#fotouploadlayer").html("<img src='image/layout/loading.gif' alt='loading...'");
                },    
                success: function(result){

                    if(result=="success"){
                        $("#fotoupload").fadeOut("fast");
                        $("#fotoavatar img").attr("src",$("#uploadfoto_field").val());
                    }else{
                        alert("Error - Avatar. We can't contact to our server now, please try again latter!'");
                    }
                }
            });

        }else{
            alert("Error - Avatar. Invalid input for avatar or empty input!");
        }
    })

    $("#formlogin").submit(function(){
        requestLogin();
        return false;
    });

    $("#formsearch").submit(function(){
        $("#btsearch").click();
        return false; 
    });

    //Free Game For Your Site
    $("#freegameforyoursitelink").click(function(){     
        $("#freegameforyoursite").modal({
            opacity:80,
            containerCss:{
                height:550
            }
        });    
    });
    
    //Challenge About
    $(".challengeabout").click(function(){     
        $("#aboutchallenge").modal({
            opacity:80,
            containerCss:{
                height:550
            }
        });    
    });
    
     //Challenge winner
    $("#challengewinner").click(function(){     
        $("#winnerchallenge").modal({
            opacity:80,
            containerCss:{
                height:550
            }
        });    
    });

    //Comment box 
    //$("#chatbox").load("include/chatbox.php?gameid="+$("#gameid").val());
    
    $("#chatbutton").click(function(){ 
        if($("#chatinput").val()==""){
            alert("What is your comment?");
            $("#chatinput").focus();
        }else{
            $.ajax({
                type: "GET",
                url: "action.php",
                data: "act=addcomment&gameid=" + $("#gameid").val() + "&shout="+$("#chatinput").val()+ "&yourname="+$("#chatname").val(),
                beforeSend: function(){
                    $("#chatbuttonsender").show();
                    $("#chatbuttoncontainer").hide();
                },
                success: function(msg){
                    if(msg=="success"){
                        $("#chatbox").load("include/chatbox.php?gameid="+$("#gameid").val());
                    }else{
                        alert("Error - Chatbox. We can't contact our server now, please try again latter!'");
                    } 

                    $("#chatinput").val("");
                    $("#chatinput").focus();
                    $("#chatbuttonsender").hide();
                    $("#chatbuttoncontainer").show();
                }
            })
        }
    })

    //page tab for gamestatistic and chat

    $("#chatting_body").load("include/chat.php?val="+$("#gameid").val()); 

    $("#gamestatisticbutton").click(function(){
        $("#chatroom_body").hide();
        $("#chatting_body").hide();
        $("#gamestatistic").show();
        $("#chatcon").hide();
    })
    $("#chatroombutton").click(function(){
        $("#chatroom_body").show();
        $("#gamestatistic").hide();
        $("#chatting_body").hide();
        $("#chatcon").hide();
    })

    $("#chatboxbutton").click(function(){
        $("#chatroom_body").hide();
        $("#chatting_body").show();
        $("#gamestatistic").hide();
        $("#chatcon").show();
    })



    $("#chatname").click(function(){
        //$(this).val("");
    })


    //chat sender
    //make auto load every 5 minute
    //ChatBox.autoReload(55000);

    $("#btChatbox").click(function(){

        $.get("action.php",{act: "sendChat", author: $("#chatboxname").val(), comment: $("#chatboxinput").val(), gameid: $("#gameid").val()}, function(msg){

            if(msg=="success"){
                $("#chatting_body").load("include/chat.php");
                $("#chatboxinput").val('');
                $("#chatboxinput").focus();
            }else{
                if(msg=="halt"){
                    alert('You must wait until another people post their message.');
                }
            }
        })
    })

    $("#chatboxinput").bind("keydown",function(e){
        if(e.which == 13){
            $("#btChatbox").click();     
        }
    })

    $("#chatboxname").focus(function(){
        $(this).val('');
    })

    //add to favorite game
    function requestAddToFav(){
        $("#addtofav").attr("class","addtofav");
        $("#addtofav").html("Adding..");
    }

    $("#addtofav").click(function(){
        $.ajax({
            type: "GET",
            url: "action.php",
            data: "act=addtofav&gameid="+ $("#gameid").val(),
            beforeSend: requestAddToFav,
            success: function(result){
                if(result == "notlogged"){
                    alert('Error - Add To Fav. You must loggin first!');
                    $("#addtofav").attr("class","property_text");
                    $("#addtofav").html("Add To Favorite");
                }else{
                    if(result == "success"){
                        $("#addtofav").html("Added!");
                    }else{
                        alert('Error - Add To Fav. Fail to conect to out server, make sure your computer is connected with internet');
                        $("#addtofav").attr("class","property_text");
                        $("#addtofav").html("Add To Favorite");
                    }
                }
            }
        });
    }) 

    //Timer for Challenge
    $(".cTimer").each(function(){
        $(this).countdown({
            until: $(this).attr("value"),
            compact: true,
            expiryUrl: 'index.php',
        })   
    });
    
    //confirm challenge shower
    $("#showchallengeconfirm").slideDown();
    
    //user upload
    $("#upload_navigation").change(function(){
        if($(this).val() !== ""){
            window.location = "index.php?act=upload&val="+$(this).val();
        }
        
    })
});
//===================== END OF JQUERY ======================================


var ChatBox = {
    reload: function(){
        $("#chatting_body").load("include/chat.php"); 
        console.log("chat reload");
    },
    autoReload: function(timeInterval){
        setInterval("ChatBox.reload()",timeInterval);
    }
}
//Login 
function loginLoading(){
    $("#loginloading").html("<div style='float: right; background: white; width: 170px; height: 24px; border: 1px solid #CCCCCC; text-align: right'><div style='float: right'><img src='image/layout/loading.gif' width='24' /></div><div style='float: right; padding-top: 5px;'>login to your account...</div></div>");
}

function requestLogin(){
    $(function(){

        var username = $("#username").val();
        var password = $("#password").val();

        $.ajax({
            type: "GET",
            url: "action.php",
            data: "act=login&username="+ username +"&password="+ password,
            beforeSend: loginLoading,
            success: function(result){
                //alert("act=login&username=" + username + "&password=" + password );
                //window.location = 'index.php'

                if(result == "denied"){
                    alert('Error Login - "' + username + '" is not exist in our database');
                    $("#loginbaritem").html("Login <input type='text' name='username' value='enter username' id='username' /> <input name='password' type='password' id='password' value='enter password' /> <input type='button' name='login' value='Login' id='btlogin' class='button' onclick='requestLogin();'  /> <input type='button' name='login' value='Register' id='btregister'  onClick='register();' class='button'  />");
                }else{
                    $("form")[1].submit();
                    //window.location.replace('index.php');
                    // submitLogin();
                }

            }
        })
    });   
}

//simple modal register
function register(){
    $(function(){
        $("#registration").modal({
            opacity:80
        });
    });
}

function registerbgbattle(){
    $(function(){
        $("#registrationbgbattle").modal({
            opacity:80
        });
    });
}

//subscribe
function subscribe(){
    $.ajax({
        type: "GET",
        url: "action.php",
        data: "act=subscribe&email=" + $("#subscribe").val(),
        beforeSend: function(){
            $("#subscribeform").html("<p style=\"color: white; font-size: 12px; padding: 10px; font-weight: bold\">Processing your subscription...</p>");
        },
        success: function(msg){
            if(msg=="success"){
                $("#subscribeform").html("<p style=\"color: green; font-size: 12px; padding: 10px; font-weight: bold\">You have successfully subscribed</p>");
            }
        }
    });
}


function submitLogin(){
    document.forms["formlogin"].submit();
}




