<?php
/**
 * Implementation of hook_menu().
 */
function kreyon_menu(){
	$items = array();

  $items['kreyo/chessform'] = array( 
    'title' => 'CHESS COMPOSITION CHALLENGE', 
    'description' => 'Chess Composition Challenge',
    'page callback' => 'drupal_get_form', 
    'page arguments' => array('kreyon_chess_form',2),
    'access callback' => TRUE,
  );
  return $items;
}

function kreyon_chess_form($form, &$form_state, $unuseful,$language) {     
    $chess_string = array(
        "ita" => array(
             "title" => "Titolo",
             "initial" => "Posizione iniziale",
             "fen" => "FEN",
             "title" => "Titolo",
             "matein" => "Matto in",
             "moves" => "Mosse",
             "name" => "Nome",
             "surname" => "Cognome",
             "email" => "Email",
             "elo" => "ELO FIDE",
             "tags" => "Parole chiave (minimo 3)",
             "idea" => "Tema",
             "solution" => "Soluzione (usare notazione inglese)",
             "comments" => "Commenti",
             "title_placeholder" => "es. Giostra di cavalieri",
             "initial_placeholder" => "es. Kf5 Bc2 Pg3 kh5 bb4 na6 nd8 pc3 pc5 pe2 ph6",
             "fen_placeholder" => "es. 4k3/8/8/8/8/8/8/4K3",
             "matein_placeholder" => "es. 9",
             "name_placeholder" => "",
             "surname_placeholder" => "",
             "email_placeholder" => "",
             "elo_placeholder" => "es. 2300",
             "tags_placeholder" => "es. sottopromozione, cavalli, alfiere forte ",
             "idea_placeholder" => "es. Per evitare il matto di alfiere, il nero deve promuovere due volte a cavallo, benché la sconfitta sia inevitabile.",
             "solution_placeholder" => "es. 1.Be4 e1=N 2.Bd5 c2 3.Bc4 c1=N 4.Bb5 Nc6 5.Bxc6 Nc7 6.Ba4 Nf3 7.Bd1 Ne2 8.Bxe2 Nb5 9.Bxf3",
             "comments_placeholder" => "es. Questo è un gemello del post precedente, che si ottiene sostituendo il cavallo con l'alfiere.",
             "chessboard_howto" => " Muovi i pezzi sulla scacchiera per generare la stringa Fen e la posizione iniziale.",
             "save" => "Salva",
             "validmail" => "Inserisci una email valida.",
             "validmate" => "Il campo Matto in deve contenere un numero.",
        ),
        "eng" => array(
             "title" => "Title",
             "initial" => "Initial Position",
             "fen" => "FEN",
             "title" => "Title",
             "matein" => "Mate in",
             "moves" => "Moves",
             "name" => "Name",
             "surname" => "Surname",
             "email" => "Email",
             "elo" => "ELO FIDE",
             "tags" => "Tags (at least 3 keywords)",
             "idea" => "Theme",
             "solution" => "Solution (use algebraic english format)",
             "comments" => "Comments",
             "title_placeholder" => "eg. Sleepless knights",
             "initial_placeholder" => "eg. Kf5 Bc2 Pg3 kh5 bb4 na6 nd8 pc3 pc5 pe2 ph6",
             "fen_placeholder" => "eg. 4k3/8/8/8/8/8/8/4K3",
             "matein_placeholder" => "eg. 9",
             "name_placeholder" => "",
             "surname_placeholder" => "",
             "email_placeholder" => "",
             "elo_placeholder" => "eg. 2300",
             "tags_placeholder" => "eg. underpromotion, knights, strong bishop",
             "idea_placeholder" => "eg. To avoid being mated by the bishop, black has to underpromote twice to knight though the defeat is unavoidable.",
             "solution_placeholder" => "es. 1.Be4 e1=N 2.Bd5 c2 3.Bc4 c1=N 4.Bb5 Nc6 5.Bxc6 Nc7 6.Ba4 Nf3 7.Bd1 Ne2 8.Bxe2 Nb5 9.Bxf3",
             "comments_placeholder" => "eg. This is a twin of previous post, by substituting a knight with a bishop.",
             "chessboard_howto" => " Move pieces on the chessboard to generate Fen string and Initial Position.",
             "save" => "Save",
             "validmail" => "Please enter a valid email.",
             "validmate" => "Field Mate in must contain a number.",
        )
    );

   $path_k_js = base_path(). drupal_get_path('module', 'kreyon') . "/js";

   $chessboard='<p><meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /></p>
<title></title>
<style type="text/css">
#edit-matein{
    float:left;
}
.black, .white{ 
  color:#000 !important;  
  display:block; 
  font-size:25px; 
  height:40px;  
  line-height:40px;
  position:relative; 
  text-decoration:none; 
  text-shadow:0 1px #fff; 
  width:40px; 
  /*background-color: #ff0000;*/
}
#drag_area{
  clear: both;
  display: inline-block;
  width:545px;
  height:362px; 
  overflow: auto;
  font-family:"Arial Unicode MS", serif !important; 
}
#drag_area a{
    font-family: "Arial Unicode MS";
    color: #000 !important;
}

#drop_area{
  border:5px solid #333; 
  border-left:0px;
  margin:0px;
  background-color:#CCC; 
  height:362px; 
  width:181px; 
  float:left;
}
#chess_board { 
  border:5px solid #333; 
  margin:0px;
  height:362px; 
  width: 362px; 
  float:left;
}

#chess_board td { 
  background:#fff; 
  background:-moz-linear-gradient(top, #fff, #eee); 
  background:-webkit-gradient(linear,0 0, 0 100%, from(#fff), to(#eee)); 
  box-shadow:inset 0 0 0 1px #fff; 
  -moz-box-shadow:inset 0 0 0 1px #fff; 
  -webkit-box-shadow:inset 0 0 0 1px #fff;  
  height:40px; 
  text-align:center; 
  vertical-align:middle; 
  width:40px; 
}

#chess_board tr:nth-child(odd) td:nth-child(even),
#chess_board tr:nth-child(even) td:nth-child(odd) { 
  background:#ccc; 
  background:-moz-linear-gradient(top, #ccc, #eee); 
  background:-webkit-gradient(linear,0 0, 0 100%, from(#ccc), to(#eee)); 
  box-shadow:inset 0 0 10px rgba(0,0,0,.4); 
  -moz-box-shadow:inset 0 0 10px rgba(0,0,0,.4); 
  -webkit-box-shadow:inset 0 0 10px rgba(0,0,0,.4); 
}

#chess_board td.active { 
  /*background:#f00 !important;*/ 
}
</style>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script><script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.0/jquery-ui.min.js"></script><script type="text/javascript">
/* Set Count */
$(document).ready(function() {    
    //alert("test "+ismobile());
    if (ismobile()){
        $("#drag_area").hide();
        $(".form-item").hide(); 
        $("#k_moves").hide(); 
        $("#edit-submitform").hide(); 
        $("#chessboard_howto").hide();
        $("#edit-initial").removeAttr("readonly");
        $("#edit-fen").removeAttr("readonly");
    }else{
        $("#kreyon-mobile-deny").hide();
        $(".messages.error").css({"position":"absolute"});
        $(".messages.error").css({"top":"843px"});
        $(".messages.error").css({"left":"300px"});
        $(".messages.error").css({"width":"250px"});

        calculate_fen();
    }

    var board = $("#chess_board");
    /* Get board dimensions */
        board = {
        width : board.width(),
        height : board.height()
    }
    
    /* Make pieces draggable */
    $("#drag_area a").live("mouseup", function() {
        
        /*var object = $(this);
        var class_array = $(this).attr("class").split(" ");
        element(object,class_array);*/
        //var asx = $("#A8");
        //if(asx.text()=="♜"){ }
        /*var text = "";
        $("#chess_board").find("td").each(function() {
          if (this.innerText !== "") {
           text += this.id + " " + this.innerText;
           //console.log(this.id+" "+this.css("left"));
          }
        });*/

        return false;
        
    }).draggable({
        containment: "#drag_area",
        grid: [44, 44],
        zIndex: 1000,
        stop: function (event, ui) {
            calculate_fen();
        }
    }).each(function(i, item){
    
        /*var piece = $(item).attr("class").split(" ");
        var start_cell = $(item).parent().attr("id").split("");
        init_game(piece, start_cell);*/
    
    });
});

function calculate_fen(){
    var divName = [".rook.black.one",".knight.black.one",".bishop.black.one",".queen.black",".king.black",".bishop.black.two",".knight.black.two",".bishop.black.three",".knight.black.three",".rook.black.two",".pawn.black.one",".pawn.black.two",".pawn.black.three",".pawn.black.four",".pawn.black.five",".pawn.white.one",".pawn.white.two",".pawn.white.three",".pawn.white.four",".pawn.white.five",".rook.white.one",".knight.white.one",".bishop.white.one",".queen.white",".king.white",".bishop.white.two",".knight.white.two",".bishop.white.three",".knight.white.three",".rook.white.two"];
        var divLetter = ["r","n","b","q","k","b","n","b","n","r","p","p","p","p","p","P","P","P","P","P","R","N","B","Q","K","B","N","B","N","R"];
        var positionArray=["X","X","X","X","X","X","X","X","X","X","X","X","X","X","X","X","X","X","X","X","X","X","X","X","X","X","X","X","X","X","X","X","X","X","X","X","X","X","X","X","X","X","X","X","X","X","X","X","X","X","X","X","X","X","X","X","X","X","X","X","X","X","X","X"];
        
        var initPosition="";
        for (var i = 0; i < divName.length; i++) {
            if (divLetter[i]=="k" || divLetter[i]=="K") { offsetFirst=7; }else{ offsetFirst=12; }
            leftPosition = (((parseInt($(divName[i]).position().left))-offsetFirst)/44)+1; /* 1-8-12*/

            if ((leftPosition+65)>=74 ) { leftCoord="X" }else{
                leftCoord = String.fromCharCode(64 + leftPosition); /* A-H +X */
            }

            topPosition = (((parseInt($(divName[i]).position().top))-128)/44)+1; /* 1-8 */
            topCoord  = 9-(topPosition); /* 8-1 */
            if (leftCoord!="X") {
                initPosition=initPosition+" "+divLetter[i]+leftCoord.toLowerCase()+topCoord; 
                stringIndex= (((topPosition-1)*8)+(leftPosition))-1;
                positionArray[stringIndex]=divLetter[i];
            }
        }

        var count_fen=0;
        var fen="";
        for (var j=0; j < positionArray.length; j++) { 
            if (positionArray[j]=="X") {
                count_fen++;
                if ((j+1)%8==0) {
                   if (count_fen!=0) { fen+=count_fen; }
                   fen+="/";
                   count_fen=0;
                }
            }else{
                if (count_fen!=0) { fen+=count_fen; }
                fen+=positionArray[j];
                if ((j+1)%8==0) {
                    fen+="/";
                }
                count_fen=0;
            }
        }
        var stringLength = fen.length;
        if(fen.charAt(stringLength - 1)=="/"){
          fen = fen.substring(0, stringLength - 1);
        }

        $("#edit-initial").val (initPosition);
        $("#edit-fen").val (fen);

/*
-----------------
Chessboard logic 
-----------------
A B C D E F G H
8
7
6
5
4
3
2
1
Torre = R r
Cavallo = N n
Alfiere = B b
Regina = Q q
Re = K k
Pedone = P p

-----------------
positionArray logic
-----------------
8    7        6        5        4        3        2        1
ABCDEFGH ABCDEFGH ABCDEFGH ABCDEFGH ABCDEFGH ABCDEFGH ABCDEFGH ABCDEFGH 
XXXXXXXX XXXXXXXX XXXXXXXX XXXXXXXX XXXXXXXX XXXXXXXX XXXXXXXX XXXXXXXX
0-7      8-15     16-23    24-31    32-41    40-47    48-55    56-63*/

}
function ismobile() {
    if( /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ) {
        return true;
    } else {
        return false;
   }
}
</script>
<p>&nbsp;</p>
<div id="drag_area">
<table cellpadding="0" cellspacing="0" id="chess_board">
    <tbody>
        <tr>
            <td id="A8">&nbsp;</td>
            <td id="B8">&nbsp;</td>
            <td id="C8">&nbsp;</td>
            <td id="D8">&nbsp;</td>
            <td id="E8"><a class="king black" href="#">♚</a></td>
            <td id="F8">&nbsp;</td>
            <td id="G8">&nbsp;</td>
            <td id="H8">&nbsp;</td>
        </tr>
        <tr>
            <td id="A7">&nbsp;</td>
            <td id="B7">&nbsp;</td>
            <td id="C7">&nbsp;</td>
            <td id="D7">&nbsp;</td>
            <td id="E7">&nbsp;</td>
            <td id="F7">&nbsp;</td>
            <td id="G7">&nbsp;</td>
            <td id="H7">&nbsp;</td>
        </tr>
        <tr>
            <td id="A6">&nbsp;</td>
            <td id="B6">&nbsp;</td>
            <td id="C6">&nbsp;</td>
            <td id="D6">&nbsp;</td>
            <td id="E6">&nbsp;</td>
            <td id="F6">&nbsp;</td>
            <td id="G6">&nbsp;</td>
            <td id="H6">&nbsp;</td>
        </tr>
        <tr>
            <td id="A5">&nbsp;</td>
            <td id="B5">&nbsp;</td>
            <td id="C5">&nbsp;</td>
            <td id="D5">&nbsp;</td>
            <td id="E5">&nbsp;</td>
            <td id="F5">&nbsp;</td>
            <td id="G5">&nbsp;</td>
            <td id="H5">&nbsp;</td>
        </tr>
        <tr>
            <td id="A4">&nbsp;</td>
            <td id="B4">&nbsp;</td>
            <td id="C4">&nbsp;</td>
            <td id="D4">&nbsp;</td>
            <td id="E4">&nbsp;</td>
            <td id="F4">&nbsp;</td>
            <td id="G4">&nbsp;</td>
            <td id="H4">&nbsp;</td>
        </tr>
        <tr>
            <td id="A3">&nbsp;</td>
            <td id="B3">&nbsp;</td>
            <td id="C3">&nbsp;</td>
            <td id="D3">&nbsp;</td>
            <td id="E3">&nbsp;</td>
            <td id="F3">&nbsp;</td>
            <td id="G3">&nbsp;</td>
            <td id="H3">&nbsp;</td>
        </tr>
        <tr>
            <td id="A2">&nbsp;</td>
            <td id="B2">&nbsp;</td>
            <td id="C2">&nbsp;</td>
            <td id="D2">&nbsp;</td>
            <td id="E2">&nbsp;</td>
            <td id="F2">&nbsp;</td>
            <td id="G2">&nbsp;</td>
            <td id="H2">&nbsp;</td>
        </tr>
        <tr>
            <td id="A1">&nbsp;</td>
            <td id="B1">&nbsp;</td>
            <td id="C1">&nbsp;</td>
            <td id="D1">&nbsp;</td>
            <td id="E1"><a class="king white" href="#">♔</a></td>
            <td id="F1">&nbsp;</td>
            <td id="G1">&nbsp;</td>
            <td id="H1">&nbsp;</td>
        </tr>
    </tbody>
</table>

<table cellpadding="0" cellspacing="0" id="drop_area">
    <tbody>
        <tr>
            <td id="A8"><a class="rook black one" href="#">♜</a></td>
            <td id="H8"><a class="rook black two" href="#">♜</a></td>
            <td id="B8"><a class="knight black one" href="#">♞</a></td>
            <td id="G8"><a class="knight black two" href="#">♞</a></td>
        </tr>
        <tr>
            <td id="F7"><a class="knight black three" href="#">♞</a></td>
            <td id="C8"><a class="bishop black one" href="#">♝</a></td>
            <td id="F8"><a class="bishop black two" href="#">♝</a></td>
            <td id="G7"><a class="bishop black three" href="#">♝</a></td>
        </tr>
        <tr>
            <td id="D8"><a class="queen black" href="#">♛</a></td>
            <td id="A7"><a class="pawn black one" href="#">♟</a></td>
            <td id="B7"><a class="pawn black two" href="#">♟</a></td>
            <td id="C7"><a class="pawn black three" href="#">♟</a></td>
        </tr>
        <tr>
            <td id="D7"><a class="pawn black four" href="#">♟</a></td>
            <td id="E7"><a class="pawn black five" href="#">♟</a></td>
            <td id="E8">&nbsp;</td>
            <td id="H7">&nbsp;</td>
        </tr>
        <tr>
            <td id="A1"><a class="rook white one" href="#">♖</a></td>
            <td id="H1"><a class="rook white two" href="#">♖</a></td>
            <td id="B1"><a class="knight white one" href="#">♘</a></td> 
            <td id="G1"><a class="knight white two" href="#">♘</a></td>
        </tr>
        <tr>
            <td id="F2"><a class="knight white three" href="#">♘</a></td>
            <td id="C1"><a class="bishop white one" href="#">♗</a></td>
            <td id="F1"><a class="bishop white two" href="#">♗</a></td>
            <td id="G2"><a class="bishop white three" href="#">♗</a></td>
        </tr>
        <tr>
            <td id="D1"><a class="queen white" href="#">♕</a></td>
            <td id="A2"><a class="pawn white one" href="#">♙</a></td>
            <td id="B2"><a class="pawn white two" href="#">♙</a></td>
            <td id="C2"><a class="pawn white three" href="#">♙</a></td> 
        </tr>
        <tr>
            <td id="D2"><a class="pawn white four" href="#">♙</a></td>
            <td id="E2"><a class="pawn white five" href="#">♙</a></td>
            <td id="H2">&nbsp;</td>
            <td id="E1">&nbsp;</td>
        </tr>
    </tbody>
</table>
</div>
<label id="kreyon-mobile-deny">The chess competition submit form is not available on mobile devices. - Il form di sottomissione della Chess Competion non è disponibile su dispositivi mobili.</label>
';

    $form['html'] = array(
      '#type' => 'markup',
      '#markup' => $chessboard,
      '#tree' => true,
      '#suffix' => '<br><br><label id="chessboard_howto">* '.$chess_string[$language]['chessboard_howto'].'</label>'
    );

    $form['initial'] = array(
        '#size' => 38,
        '#title' => t($chess_string[$language]["initial"]),
        '#type' => 'textarea',
        //'#required' => TRUE,
        '#attributes' => array('readonly' => 'readonly','placeholder' => $chess_string[$language]["initial_placeholder"]),
    );  

    $form['fen'] = array(
        '#size' => 38,
        '#title' => t($chess_string[$language]["fen"]),
        '#type' => 'textarea',
        //'#required' => TRUE,
        '#attributes' => array('readonly' => 'readonly','placeholder' => $chess_string[$language]["fen_placeholder"]),
    );  

    $form['title'] = array(
        '#size' => 38,
        '#title' => t($chess_string[$language]["title"]),
        '#type' => 'textfield',
        '#required' => TRUE,
        '#attributes' =>array('placeholder' => $chess_string[$language]["title_placeholder"]),
    );

    $form['matein'] = array(
        '#title' => t($chess_string[$language]["matein"]),
        '#type' => 'textfield',
        '#required' => TRUE,
        '#size' => 10,
        '#suffix' => '<label id="k_moves">&nbsp;'.$chess_string[$language]["moves"].'</label>',
        '#attributes' =>array('placeholder' => $chess_string[$language]["matein_placeholder"]),
    );

    $form['name'] = array(
        '#size' => 38,
        '#title' => t($chess_string[$language]["name"]),
        '#type' => 'textfield',
        '#required' => TRUE,
        '#attributes' =>array('placeholder' => $chess_string[$language]["name_placeholder"]),
    );

    $form['surname'] = array(
        '#size' => 38,
        '#title' => t($chess_string[$language]["surname"]),
        '#type' => 'textfield',
        '#required' => TRUE,
        '#attributes' =>array('placeholder' => $chess_string[$language]["surname_placeholder"]),
    );

    $form['email'] = array(
        '#size' => 38,
        '#title' => t($chess_string[$language]["email"]),
        '#type' => 'textfield',
        '#required' => TRUE,
        '#attributes' =>array('placeholder' => $chess_string[$language]["email_placeholder"]),
    );

    $form['elo'] = array(
        '#size' => 38,
        '#title' => t($chess_string[$language]["elo"]),
        '#type' => 'textfield',
        '#required' => FALSE,
        '#attributes' =>array('placeholder' => $chess_string[$language]["elo_placeholder"]),
    );

    $form['tags'] = array(
        '#title' => t($chess_string[$language]["tags"]),
        '#type' => 'textarea',
        '#required' => TRUE,
        '#attributes' =>array('placeholder' => $chess_string[$language]["tags_placeholder"]),
    );    

    $form['idea'] = array(
        '#title' => t($chess_string[$language]["idea"]),
        '#type' => 'textarea',
        '#required' => TRUE,
        '#attributes' =>array('placeholder' => $chess_string[$language]["idea_placeholder"]),
    );    
    $form['solution'] = array(
        '#title' => t($chess_string[$language]["solution"]),
        '#type' => 'textarea',
        '#required' => TRUE,
        '#attributes' =>array('placeholder' => $chess_string[$language]["solution_placeholder"]),
    );
    $form['comments'] = array(
        '#title' => t($chess_string[$language]["comments"]),
        '#type' => 'textarea',
        '#required' => FALSE,
        '#attributes' =>array('placeholder' => $chess_string[$language]["comments_placeholder"]),
    );

    $form['my_captcha_element'] = array(
        '#type' => 'captcha',
        '#captcha_type' => 'recaptcha/reCAPTCHA',
    );
    $form['language'] = array(
        '#type' => 'value',
        '#value' => $language,
    );
    $form['submitform'] = array(
        '#type' => 'submit',
        '#value' => t($chess_string[$language]["save"]),
    );

    return $form;
}

function kreyon_chess_form_validate($form, &$form_state,$language) {
  $chess_validate_string = array(
        "ita" => array(
             "validmail" => "Inserisci una email valida.",
             "validmate" => "Il campo Matto in deve contenere un numero.",
        ),
        "eng" => array(
             "validmail" => "Please enter a valid email.",
             "validmate" => "Field Mate in must contain a number.",
        )
    );


  $values = $form_state['values'];
  $language = $values['language'];

  $matein = $values['matein'];
  $email = $values['email'];

  if (!is_numeric($matein)) {
    form_set_error('matein', t($chess_validate_string[$language]["validmate"]));
  }
  if (!valid_email_address($email)) {
    form_set_error('email', t($chess_validate_string[$language]["validmail"]));
  }
}

function kreyon_chess_form_submit($form, &$form_state,$language){
    $values = $form_state['values'];
    $language = $values['language'];
    
    $initial = $values['initial'];
    $fen = $values['fen'];
    $title = $values['title'];
    $matein = $values['matein'];
    $name = $values['name'];
    $surname = $values['surname'];
    $email = $values['email'];
    $elo = $values['elo'];
    $tags = $values['tags'];
    $idea = $values['idea'];
    $solution = $values['solution'];
    $comments = $values['comments'];

    $title = str_replace("'", " ", $title);
    $name = str_replace("'", " ", $name);
    $surname = str_replace("'", " ", $surname);
    $tags = str_replace("'", " ", $tags);
    $idea = str_replace("'", " ", $idea);
    $solution = str_replace("'", " ", $solution);
    $comments = str_replace("'", " ", $comments);

    db_query("INSERT INTO {ets_kreyon_chess_challenge} (initial, fen, title, matein, name, surname, email, elo, tags, idea, solution, comments) VALUES ('{$initial}','{$fen}','{$title}','{$matein}', '{$name}', '{$surname}','{$email}', '{$elo}', '{$tags}', '{$idea}', '{$solution}', '{$comments}')");

    if ($language=="eng") {
        $form_state['redirect'] = 'kreyon/238';
    }else{
        $form_state['redirect'] = 'kreyon/237';
    }
    
}
