Event.observe(window, 'load', init, false);

function init() {
    autoSubmit = getCookie("autoSubmit");
    todayPlay = getCookie("gotd");

    $('gameCount').innerHTML = 'Games played: '+numGames;

    if (getCookie("gotd") != 1) {
        todayGame();
    } else {
        randomGame();
    }

    getTotalGames();
    fncCheckCountry();
}

function newGame(x) {

    if (x != null)
    { 
        loadGame(x);

    } else if (defaultGame != "" && numGames == 1) {
        numbers = defaultGame.split(',');
        if (numbers.length != 3) {
            defaultGame == "";
            numbers = [1,2,3];
        }

        $('gameTitle').innerHTML = "Custom";

        loadGame(numbers);
      
    } else if(gameMode.substring(0,5) == 'today') {
        if (gameMode == 'today_girl') {
            numbers = [td_grl[day][0],td_grl[day][1],td_grl[day][2]];
        } else if (gameMode == 'today_guy') {
            numbers = [td_guy[day][0],td_guy[day][1],td_guy[day][2]];
        } else {
            numbers = [td_both[day][0],td_both[day][1],td_both[day][2]];
        }

        loadGame(numbers);

    } else if(gameMode == 'popular') {
        var myAjax = new Ajax.Request(
          '/server/popular.php',
          {
              method: 'get',
              parameters: 'game='+popGame,
              onComplete: getNumbers
          });        

          popGame += 1;

    } else {

        var gender = gameMode.substring(5);
        var myAjax = new Ajax.Request(
          'server/getrandom.php',
          {
              method: 'get',
              parameters: 'gametype='+gender,
              onComplete: getNumbers
          });
    }
}

function loadGame(fkm_people) {
    var myAjax = new Ajax.Request(
          'server/game.php',
          {
              method: 'get',
              parameters: 'fkm1='+fkm_people[0]+'&fkm2='+fkm_people[1]+'&fkm3='+fkm_people[2],
              onComplete: loadNumbers
          });
}

function loadNumbers(response) {
    ppl = JSON.parse(response.responseText);
    ppl.each(function(item, i) {
        AddBox2(item);
        //if (i == 2)  {Element.show($('footWrap'));}
    });
}

function getNumbers(response) {
     var s = Array();
     top_ppl = JSON.parse(response.responseText);
     top_ppl.each(function(item, i) {
         s[i] = item.id;
     });
  
     loadGame(s);
}

function clearGame() {
    $('playBox').innerHTML = '';
    genID = 0;
    numbers = Array();
    f_on = false;
    f_id = '';
    k_on = false;
    k_id = '';
    m_on = false;
    m_id = '';
    
}

function AddBox2(fkm_data) {
     pos = generateId();
     ctrl = new boxBuilder(pos,fkm_data);
     markup = ctrl.display();

     $('playBox').appendChild(markup);

     Element.hide($('pict_'+pos));
     Effect.Appear($('pict_'+pos), { duration: 1 });
}

function generateId() {
    ret = genID;
    genID += 1;
    return ret;
}


var cgBuilder = Class.create();

cgBuilder.prototype = {
    initialize: function(id,fkm_data) {
        this.id = id;
        this.fkm_id = fkm_data.id;
        this.name = fkm_data.name;
    },

    display: function() {    
        this.span = document.createElement('span');
        this.span.appendChild(
           Builder.node('span',{className:'cgSpanOut',id:'out_'+this.id },[
               Builder.node('span',{ id:'in_'+this.id, className:'cgSpanIn',onclick:'cgAddGame('+this.id+','+ this.fkm_id+')',onmouseover:'Element.addClassName(this,\'hiLite\')',onmouseout:'Element.removeClassName(this,\'hiLite\')'},[
                   Builder.node('img',{ src:'image.php?id='+ this.fkm_id +'&size=sq&bw=70',alt:this.name})
               ])
           ])
        )
        return this.span;
    }
}

var boxBuilder = Class.create();

boxBuilder.prototype = {

    initialize: function(id,fkm_data) {
        this.id = id;
        this.fkm_id = fkm_data.id;
        this.name = fkm_data.name;
        this.imgsrc = fkm_data.file_name;
        this.dob = fkm_data.dob;
        this.hometown = fkm_data.hometown;
        this.occ = fkm_data.occ;
        this.known = fkm_data.known;
        this.total = parseInt(fkm_data.f) + parseInt(fkm_data.k) + parseInt(fkm_data.m);
        this.f = Math.floor((parseInt(fkm_data.f) / (this.total)) * 100);
        this.k = Math.floor((parseInt(fkm_data.k) / (this.total)) * 100);
        this.m = Math.floor((parseInt(fkm_data.m) / (this.total)) * 100);

        this.ltotal = parseInt(fkm_data.lf) + parseInt(fkm_data.lk) + parseInt(fkm_data.lm);
        this.lf = Math.floor((parseInt(fkm_data.lf) / (this.ltotal)) * 100);
        this.lk = Math.floor((parseInt(fkm_data.lk) / (this.ltotal)) * 100);
        this.lm = Math.floor((parseInt(fkm_data.lm) / (this.ltotal)) * 100);

    },

    display: function() {
        this.div = document.createElement('div');
        this.addMarkup();
        this.div.id = 'div_' + this.id;
        return this.div;
    },

    addMarkup: function() {
        this.div.appendChild(
             Builder.node('div',{ className:'gbOutter', id:'pic_' + this.id },[
                 Builder.node('div',{ className:'gbNS'},[
                     Builder.node('div',{ className:'gbName'},[
                         Builder.node('h4',{className:'name'},this.name)
                     ]),
                     Builder.node('div',{ className:'gbMoreInfo', style: 'cursor:pointer', onclick:'moreInfo('+this.fkm_id+')'},'')
                 ]),
                 Builder.node('div',{className:'gbMiddle'},[
                     Builder.node('img',{ id:'pict_' + this.id, src:'people/'+this.imgsrc,className:'pplIMG'}),
                     Builder.node('div',{id:'mi_'+this.fkm_id, className:'gbMiddleI', style:'display:none;'},[
                         Builder.node('div',{className:'gbMIText'},'More Info'),
                         Builder.node('p', {className:'gbMIText'}, 'Birthday: '+this.dob),
                         Builder.node('p', {className:'gbMIText'}, 'Hometown: '+this.hometown),
                         Builder.node('p', {className:'gbMIText'}, 'Occupation: '+this.occ),
                         Builder.node('p', {className:'gbMIText'}, 'Best Known For: '+this.known)
                     ])
                 ]),
                 Builder.node('div',{className:'gbBottom'},[
                     Builder.node('a',{id:'f_'+this.fkm_id, className:'fkmButton', onclick:'ff(this,'+this.fkm_id+')'}, 'F'),
                     Builder.node('a',{id:'k_'+this.fkm_id, className:'fkmButton', onclick:'fk(this,'+this.fkm_id+')'}, 'K'),
                     Builder.node('a',{id:'m_'+this.fkm_id, className:'fkmButton', onclick:'fm(this,'+this.fkm_id+')'}, 'M')
                 ]),
                 Builder.node('div',[
                     Builder.node('span',{className:'statText'},'Game Stats'),
                     Builder.node('span',{className:'statText'},'Total Stats')
                 ]),

                 Builder.node('div',{className:'stats'},[
                     Builder.node('div',{className:'fuck', title:this.lf+'% - '+this.ltotal+' Votes',style:'height:'+this.lf+'px'},''),
                     Builder.node('div',{className:'kill', title:this.lk+'% - '+this.ltotal+' Votes',style:'height:'+this.lk+'px'},''),
                     Builder.node('div',{className:'marry',title:this.lm+'% - '+this.ltotal+' Votes',style:'height:'+this.lm+'px'},''),
                     Builder.node('div',{className:'fuck', title:this.f+'% - '+this.total+' Votes',style:'height:'+this.f+'px'},''),
                     Builder.node('div',{className:'kill', title:this.k+'% - '+this.total+' Votes',style:'height:'+this.k+'px'},''),
                     Builder.node('div',{className:'marry',title:this.m+'% - '+this.total+' Votes',style:'height:'+this.m+'px'},'')
                 ])
             ]));
    }
}

var f_on = false;
var f_id = '';

function ff(el,id) {
    if (f_on == true && f_id != id) {
        alert("You can only choose one of each.");
    } else {
        if ((k_on == true && k_id == id) ) {fk($('k_'+id),id);}
        if ((m_on == true && m_id == id) ) {fm($('m_'+id),id);}
        if ($(el).style.backgroundColor == '') {
            $(el).style.backgroundColor = '#EFEFEF';
            f_on = true;
            f_id = id;
        } else {
            $(el).style.backgroundColor = '';
            f_on = false;
            f_id = '';
        }
    }
   
    showSubmit();
}

k_id = '';
k_on = false;

function fk(el,id) {
    if (k_on == true && k_id != id) {
        alert("You can only choose one of each.");
    } else {
        if ((f_on == true && f_id == id) ) {ff($('f_'+id),id);}
        if ((m_on == true && m_id == id) ) {fm($('m_'+id),id);}
        if ($(el).style.backgroundColor == '') {
            $(el).style.backgroundColor = '#EFEFEF';
            k_on = true;
            k_id = id;
        } else {
            $(el).style.backgroundColor = '';
            k_on = false;
            k_id = '';
        }
    }
    showSubmit();
}

m_id = 0;
m_on = false;

function fm(el,id) {
    if (m_on == true && m_id != id) {
        alert("You can only choose one of each.");
    } else {
        if ((f_on == true && f_id == id) ) {ff($('f_'+id),id);}
        if ((k_on == true && k_id == id) ) {fk($('k_'+id),id);}
        if ($(el).style.backgroundColor == '') {
            $(el).style.backgroundColor = '#EFEFEF';
            m_on = true;
            m_id = id;
        } else {
            $(el).style.backgroundColor = '';
            m_on = false;
            m_id = '';
        }
    }
    showSubmit();
}

function moreInfo(id) {
    Effect.toggle($('mi_'+id),'blind');
}

function showSubmit() {
    if (k_on == true && m_on == true && f_on == true) {
        if (getCookie('autoSubmit') == "true") {
            saveButton();
        } else {
            $('submitBox').style.display = 'block';
        }
    }
}

function autoSubmitB() {
    setCookie("autoSubmit", 'true',30);
//    autoSubmit = true;
}


/* Globals */

var genID = 0;
var numbers = Array();
var numGames = 1;
var currentTab = 1;
var popGame = 1;

function cancelButton() {        
    Element.hide($('submitBox'))
}

function saveButton() {

    if (getCookie("gotd") == 1 && gameMode.substring(0,5) == 'today') { 
        alert("You can only Play this game once.");
        randomGame();
    } else {

    Element.hide($('submitBox'));
    var myAjax = new Ajax.Request(
          'server/save.php',
          {
              method: 'get',
              parameters: 'f_id='+f_id+'&k_id='+k_id+'&m_id='+m_id,
              onComplete: function() 
              {
                  $('gameCount').innerHTML = 'Games played: '+numGames;
                  numGames++;

                  if (gameMode.substring(0,5) == 'today') {
                      setCookie("gotd",1,1);
                      randomGame();
                  } else if (gameMode == 'custom'){
                      randomGame();
                  } else {
                      clearGame();
                      newGame();
                  }
                  
              }
          });    
    }
}

function todayGame(mode) {

    var html = "&nbsp;<span id='mnu2txt' style='display:none'><a href='javascript:todayGame(\"today_girl\");'>Girls</a> | <a href='javascript:todayGame(\"today_guy\");'>Guys</a> | <a href='javascript:todayGame(\"today_both\");'>Both Guys & Girls</a></span>";

    if (mode != undefined) { 
        gameMode = mode;
    } else {
        gameMode = 'today_girl';
    }

    changeTab(1);

    $('gameTitle').innerHTML = "Today's Game"; 
    var myEffect = new fx.Height($('sndMenu') , {duration: 500, onComplete: set2Mnu(html) });
    myEffect.custom(10,24);

    clearGame();
    newGame();
}

function set2Mnu(mnu_text) {
    Element.addClassName('sndMenu','text');

    $('sndMenu').innerHTML = mnu_text
 
    Effect.Appear($('mnu2txt'));


}

function customGame(a,b,c,title) {
    changeTab(2);
    gameMode = 'custom';

    $('gameTitle').innerHTML = title;

    clearGame();
    newGame(Array(a,b,c));
}

function randomGame(mode) {
    var html = "&nbsp;<span id='mnu2txt' style='display:none'><a href='javascript:randomGame(\"free_girl\");'>Girls</a> | <a href='javascript:randomGame(\"free_guy\");'>Guys</a> | <a href='javascript:randomGame(\"free_both\");'>Both Guys & Girls</a></span>";

    if (mode != undefined) {
        gameMode = mode;
    } else {
        gameMode = 'free_girl';
    }

    switch (gameMode) {
        case "free_girl": msg = "Girls"; break;
        case "free_guy": msg = "Guys"; break;
        case "free_both": msg = "free for all"; break;
    }

    changeTab(2);

    var myEffect = new fx.Height($('sndMenu') , {duration: 500, onComplete: set2Mnu(html) });
    myEffect.custom(10,24);

    $('gameTitle').innerHTML = "Random '<i>" + msg + "</i>'";

    clearGame();
    newGame();
}

function popularGame() {

    $('mnu2txt').innerHTML = '';

    changeTab(3);
    gameMode = 'popular';

    $('gameTitle').innerHTML = "Most Popular '<i>free for all</i>'";

    clearGame();
    newGame();
}

function createGame(mode) {

    if (mode != undefined) {
        gameMode = mode;
    } else {
        gameMode = 'girl';
    }

    var html = "&nbsp;<span id='mnu2txt' style='display:none'><a href='javascript:createGame(\"girl\");'>Girls</a> | <a href='javascript:createGame(\"guy\");'>Guys</a> | <a href='javascript:createGame(\"both\");'>Both Guys & Girls</a></span>";

    var myEffect = new fx.Height($('sndMenu') , {duration: 500, onComplete: set2Mnu(html) });
    myEffect.custom(10,24);

    $('createPage').innerHTML = '';
    cgArray.clear();
    changeTab(4);

    hideContent();
    Element.show($('createPage'));

    getPeople(gameMode);
}

function widgetPage() {
    $('mnu2txt').innerHTML = '';

    changeTab(5);

    hideContent();
    Element.show($('widgetPage'));
}

function hideContent() {
    Element.hide($('contactPage'));
    Element.hide($('aboutPage'));
    Element.hide($('widgetPage'));
    Element.hide($('registerPage'));
    Element.hide($('createPage'));
    Element.hide($('field'));
    Element.hide($('spotLiteGames'));
    Element.hide($('legal'));
}

function changeTab(tab) {
    
    hideContent();
    Element.show($('field'));
    Element.show($('spotLiteGames'));

    Element.removeClassName('mnu'+currentTab+'a','current');
    Element.removeClassName('mnu'+currentTab,'active');

    Element.addClassName('mnu'+tab+'a', 'current');
    Element.addClassName('mnu'+tab, 'active');
    $('mnu'+tab+'a').blur();
  
    currentTab = tab;
}

function registerPage() {
    initForm();
    Element.removeClassName('mnu'+currentTab+'a','current');
    Element.removeClassName('mnu'+currentTab,'active');

    hideContent();
    Element.show($('registerPage'));
}

function contactPage() {

    $('mnu2txt').innerHTML = '';

    Element.removeClassName('mnu'+currentTab+'a','current');
    Element.removeClassName('mnu'+currentTab,'active');

    hideContent();
    Element.show($('contactPage'));
}

function aboutPage() {

    $('mnu2txt').innerHTML = '';

    Element.removeClassName('mnu'+currentTab+'a','current');
    Element.removeClassName('mnu'+currentTab,'active');

    hideContent();
    Element.show($('aboutPage'));
}

function sendForm() {

    data = Form.serialize($('emailForm'));

    var myAjax = new Ajax.Request(
          'Mail/index.php',
          {
              method: 'post',
              parameters: data,
              onComplete: function() {Element.hide($('emailFS')); alert("Message Sent");}
          });
}

function getPeople(gm) {

    var myAjax = new Ajax.Request(
          'server/getpeople.php',
          {
              method: 'post',
              parameters: 'gametype='+gm,
              onComplete: renderPage
          });
}

function renderPage(response) {
    ppl = JSON.parse(response.responseText);

    ppl.each(function(item, i) {

        ctrl = new cgBuilder(i,item);
        markup = ctrl.display();

        $('createPage').appendChild(markup);
    })
}

cgArray = new Array();
function cgAddGame(el,id) {

    if (cgArray.inArray(id)) {
        $('in_'+el).style.backgroundColor = '';
        cgArray = cgArray.without(id);
    } else {
        cgArray.push(id);
        $('in_'+el).style.backgroundColor = '#f65077';
    }
    
    if (cgArray.length == 3) {
        $('cgPLAY').innerHTML = 'Play Game: Click here to <a href="#" id="cgPLAY" onclick="Element.hide($(\'msgBox\'));customGame('+cgArray.toString()+',\'New Created Game\')" >Play Game</a>';

        $('cgTXT').value = "http://www.fkmarry.com/index.php?game=" + cgArray.toString();

        xy = Position.realOffset($('msgBox'));
        $('msgBox').style.top = xy[1] + 30;

        Effect.Appear($('msgBox'));
    }
}

function getTotalGames() {
    var myAjax = new Ajax.Request(
          'server/totalGames.php',
          {
              parameters: '',
              onComplete: displayTotalGames
          });    
}

function displayTotalGames(response) {
    tp = JSON.parse(response.responseText);
    totalgames = numberformat(tp.tg);
    $('totalGamesSpan').innerHTML = totalgames;
}


function initForm() {
    var aElements = Form.getElements('signupForm');

    for(var i=0;i<aElements.length;i++)
    {   
        if (aElements[i].tagName=='INPUT') 
        {
            if (aElements[i].type == 'text' || aElements[i].type == 'password') 
            {
                Event.observe(aElements[i],'focus',fncFocusInput.bind(aElements[i]),false);
                Event.observe(aElements[i],'blur',fncBlurInput.bind(aElements[i]),false);
            }
        }
    }
}

function cancelCG() {
    cgArray = Array();
    $('createPage').innerHTML='';
    Element.hide($('msgBox'));

    if (Element.visible($('createPage'))) {
        getPeople();
    }
}

function changeModeandPlay(mode) {
    gameMode = mode;    
    clearGame();
    newGame();    
}


function loadTerms() {
    hideContent();
    Element.show($('legal'));
    var myAjax = new Ajax.Updater(
          'legal','terms.php');
}

function loadPrivacy() {
    hideContent();
    Element.show($('legal'));
    var myAjax = new Ajax.Updater(
          'legal','privacy.php');
}

function loadAdvertising() {
    hideContent();
    Element.show($('legal'));
    var myAjax = new Ajax.Updater(
          'legal','advertising.php');
}
