<?php
$logout=0;

$debugMode=0;
if (isset($_GET['debugMode'])) {$debugMode=$_GET['debugMode'];}
//$debugMode=TRUE;
//$debugMode=true;

$filterKeys=array("M1","M3","M3X","M4","M2","CHNR","SYS_USERId","HHLSID","HHLSID20","SYS_L","M10");



$pageToShow='';
$generateDictionary=0;
$generateKolej=0;
$generateVar=0;
$generateJob=0;
$generateSaveDAT=0;
$generator=false;
$skipOpen=0;

if (isset($_GET['generateDictionary'])) {$generateDictionary=$_GET['generateDictionary']; $generator=true;}
if (isset($_GET['generateKolej'])) {$generateKolej=$_GET['generateKolej']; $generator=true;}
if (isset($_GET['generateVar'])) {$generateVar=$_GET['generateVar']; $generator=true;}
if (isset($_GET['generateJob'])) {$generateJob=$_GET['generateJob']; $generator=true;}
if (isset($_GET['generateSaveDAT'])) {$generateSaveDAT=$_GET['generateSaveDAT']; $generator=true;}
if (isset($_GET['skipOpen'])) {$skipOpen=$_GET['skipOpen'];}

require_once("../../func_pejot.php");
require_once("../../ankietaClass.php");
require_once('../../dBug.php');
require_once('../../CardClass.php');
require_once('../../AttributeClass.php');

global $data;
global $what;

ini_set('memory_limit', '-1');

if ($generator==true) {$logout=0;}

/*if (!$_POST) {
    $logout=1;
}*/
//print "Logout".$logout==0;

$new=0;
if ($_GET['new']) {$new=$_GET['new'];}



//if ($logout==0) {
    /*header("Expires: Tue, 01 Jan 2000 00:00:00 GMT");
    header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
    header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0");
    header("Cache-Control: post-check=0, pre-check=0", false);
    header("Pragma: no-cache");*/
//ini_set('session.save_path',  "/home/pejotsol/www/deployed/sessions");
ini_set('session.cookie_lifetime', 86400);
ini_set('session.gc_maxlifetime', 86400); 
session_set_cookie_params(0);
session_start();

    //session_regenerate_id(true);
    if ($debugMode==1) {print "SESSION_ID:".session_id()."<br/>";}
//}



//new dBug($_SESSION['ankieta']);
if (empty($_SESSION['ankieta']) or ($new==1)) {
    $oldSessionId=session_id();
    //session_id(createRandomVal(26));
    $newId=createRandomVal(26);
    session_commit();
    session_id($newId);
    session_start();
    $getPars=getSpecificKeys(array_change_key_case($_GET, CASE_UPPER),array_map('strtoupper',$filterKeys));
    if ($debugMode==1) {
        Print "Inicjalizacja nowego obiektu <br>";
        print "Zmiana SSID na ".session_id()."<br/>";
        //new dBug($getPars);
    }

    $getParsQuery=http_build_query($getPars);
if ($debugMode==1) {
    print "Przyjęte parametry: $getParsQuery<br/>";
}

    $ankieta=new Ankieta('PL',"OLEJE","flow.xml",$_SERVER['PHP_SELF'],'');

    $ankieta->addField("IP","IP","STRING","80");
    $ankieta->setValue("IP",getIPAdress());
    $ankieta->addField("screenout","Screenout","STRING","80");

    $ankieta->addField('USER_AGENT','Browser',"STRING","300");
    //$browser = get_browser(null, true);
    $browser=$_SERVER['HTTP_USER_AGENT'];
    $ankieta->setValue('USER_AGENT',$browser);

    /*
    $przekazanyOk=false;
    if ($getPars['CHNR']!='' and is_numeric($getPars['CHNR'])) {$choicerRnd=$getPars['CHNR']; $przekazanyOk=true;} else {$choicerRnd=rand(1,12);}
    $ankieta->addField("ChoicerRND","Wybrany design","NUMERIC","8.0");
    $ankieta->setValue("ChoicerRND",$choicerRnd);
    if ($debugMode==1) {
        if ($przekazanyOk==true) {
            print "Wybrany zestaw choicera $choicerRnd <br>";
        } else {
            print "Nie przekazano poprawnie parametru choicera. Wylosowano desing nr $choicerRnd <br>";
        }

    }*/
    //session_id(createRandomVal(27));

    $toWrite=array();
    $toWrite[]="IP";
    $toWrite[]="ChoicerRND";
    $toWrite[]="USER_AGENT";
    $ankieta->setToWrite($toWrite);
    $flow=$ankieta->readXML();
    $pageToShow=$ankieta->getNextPage();
    if ($debugMode==1) {
        print "PAGE: ";
        //$pageToShow=$ankieta->getCurrentPage();
        print $pageToShow . "<br/>";
    }

} else {
    $ankieta=unserialize($_SESSION['ankieta']);
    $flow=$ankieta->readXML();
    if ($debugMode==1) {print "Wczytanie istniejącego obieku <br>";}
    $pageToShow=$ankieta->getNextPage();
}

if ($_GET['step']) {
    if (is_numeric($_GET['step'])) {
        $step=$_GET['step'];
        //$pageToShow=$ankieta->getNextPage($step);
        $ankieta->setCurrentStep($step);
        //$pages=$ankieta->getPagesFlow();
        //$ankieta->setNextPage($pages[$step]);
        $pageToShow=(string)$flow[$step]['mainData'];
        $ankieta->setNextPage($pageToShow);
    }
}

$curStep=$ankieta->getCurrentStep();
$stepCount=$ankieta->getStepCount();
$percComplete=round($curStep/$stepCount*100,0);

if ($debugMode==1) {
    print "CURRENT STEP: ".$curStep."<br/>";
    print "CURRENT PAGE: ".$pageToShow."<br/>";
}

$type=$flow[$ankieta->getCurrentStep()]['mainData']['type'];
//print "TYPE: ".$type;

if ($type=="choicer") { //CHOICER!!
    global $choicerScreen;
    $choicerScreen=$flow[$ankieta->getCurrentStep()]['mainData']['screen'];
    if ($debugMode==1) {print ("CHOICER SCREEN: ".$choicerScreen);}

}

$ankieta->setDebugMode($debugMode);



if ($flow[$ankieta->getCurrentStep()]['mainData']['control']=='end') {$logout=1;}

?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Badanie OLEJE</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <script type="text/javascript" src="../../js/jquery-1.9.1.min.js"></script>
    <script type="text/javascript" src="../../js/jquery-ui-1.10.2.custom.min.js"></script>
    <!--<script type="text/javascript" src="http://maps.google.com/maps/api/js?v=3.exp&sensor=false&libraries=places"></script>-->

    <!-- Fancy fields js & css files -->
    <script type="text/javascript" src="../../js/fancyfields-1.2.js"></script>
    <link href="../../css/fancyfields_purple.css?<?php echo time(); ?>" rel="stylesheet" type="text/css" />

    <!--<link href="../../css/choicer_green.css?<?php echo time(); ?>" rel="stylesheet" type="text/css" />-->

    <!--<link href="css/input.css" rel="stylesheet" type="text/css" />-->

    <!--<script type="text/javascript" src="pagination2/script.js"></script>
    <link href="pagination2/styles.css" rel="stylesheet" type="text/css" />-->

    <!-- FANCYBOX -->
    <script type="text/javascript" src="../../js/jquery.mousewheel-3.0.6.pack.js"></script>
    <!-- Add fancyBox main JS and CSS files -->
    <script type="text/javascript" src="../../fancybox/jquery.fancybox.js?v=2.1.5"></script>
    <link rel="stylesheet" type="text/css" href="../../fancybox/jquery.fancybox.css?v=2.1.5" media="screen" />


    <!-- Fancy fields add-on for custom scroll bar -->
    <script type="text/javascript" src="../../js/fancyfields.csb.min.js"></script>

    <!--DatePicker -->
    <link rel="stylesheet" href="https://code.jquery.com/ui/1.10.4/themes/smoothness/jquery-ui.css">
    <script type="text/javascript" src="../../libs/image-picker/image-picker.js"></script>

    <link href="../../libs/image-picker/image-picker.css?<?php echo time(); ?>" rel="stylesheet" type="text/css" />

    <!--WYŁĄCZYŁEM!!->
    <!--<link rel="stylesheet" href="../../css/custom-theme/jquery-ui-1.9.2.css">-->


    <!--<script type="text/javascript" src="https://code.jquery.com/ui/1.10.4/jquery-ui.js"></script>-->
    <!--<script type="text/javascript" src="js/jquery-ui-1.10.2.custom.min.js"></script>-->

    <!--MaskedInput -->
    <!--<script src="../jquery.maskedinput.min.js" type="text/javascript"></script>-->
    <script type="text/javascript" src="../../js/number_format.js"></script>


    <!--custom pejot functions-->
    <script type="text/javascript" src="../../js/func_pejot.js"></script>
    <script type="text/javascript" src="../../js/jquery.limit-1.2.source.js"></script>
    <script type="text/javascript">
        <?
        //include('maps_pejot.php');
        ?>
    </script>
    <link rel="stylesheet" href="../../css/maps_pejot.css">

    <script type="text/javascript" src="../../js/jquery.validate_alt.js"></script>
    <script type="text/javascript" src="../../js/additional-methods.js"></script>

    <!-- Latest compiled and minified CSS -->
    <link rel="stylesheet" href="../../css/bootstrap.min_pejot.css?<?php echo time(); ?>">

    <!-- Optional theme -->
    <link rel="stylesheet" href="../../css/bootstrap-theme.min.css">
    <link rel="stylesheet" href="css/kantar.css?<?php echo time(); ?>">
    <link rel="stylesheet" href="../../libs/date-picker/css/bootstrap-datepicker.min.css">

    <!-- Latest compiled and minified JavaScript -->
    <script src="../../js/bootstrap.min.js" type="text/javascript"></script>
    <script src="../../libs/date-picker/js/bootstrap-datepicker.min.js" type="text/javascript"></script>
    <script src="../../libs/date-picker/locales/bootstrap-datepicker.pl.min.js" type="text/javascript"></script>

    <style type="text/css">

        label {
            display:inline-block;
            max-width:100%;
            margin-bottom:5px;
            font-weight:500;
        }


    </style>

</head>
<body id="bodyAnkieta">



<div id="main" class="fancy">
    <div class="main0">
        <div class="main1">
            <div class="main2">
                <div id="header">
                <?
                    include($ankieta->getSubFolder()."headerTop.php");
                ?>
                </div>
                <?php
                $selfPage=$ankieta->getNextSubmitPage();

                //$ank2=$ankieta;
                //$nS=$ank2->getNextStep();
                //print($flow[$ankieta->getCurrentStep()]['mainData']['type']);
                if ($flow[$ankieta->getCurrentStep()]['mainData']['type']=='external') {
                    //new dBug($ankieta->getNextSubmitParameters());
                    $url=$ankieta->getNextSubmitPage()."?".http_build_query($ankieta->getNextSubmitParameters());
                    if ($debugMode==1) {
                        print "Przekierowuję na: <a href=\"$url\">".$url."</a>;";
                        exit;
                    }
                    //$selfPage=(string)$flow[$nS]['mainData'];
                    print "<script>";
                        print "window.top.location=\"".$url."\";";
                    print "</script>";
                }

                if ($ankieta->getDebugMode()==1) {$selfPage.="?debugMode=1";}



                ?>
                <form id="ankietaForm" name="ankietaForm" method="POST" action="<?PHP echo $selfPage;?>" accept-charset="UTF-8">
                    <?
                    //$ankieta->writeGap();
                    if ($generator==false) {
                        include($pageToShow);
                        //$pages=$ankieta->getPagesFlow();
                        //if ($ankieta->getCurrentPage()==count($pages)-1) {$logout=true;}
                        //if ($ankieta->getCurrentPage()==count($flow)-1) {$logout=1;}

                        //$ankieta->writeEndSurveyCode();
                        print "<br/>";
                    }
                    if ($generator==true) {
                        print "<span style='display: none;'>";
                        //$pages=$ankieta->getPagesFlow();
                        $flow=$ankieta->readXML();
                        //foreach ($pages as $lp=>$page) {
                        //print_r($flow);
                        //die();
                        foreach ($flow as $lp=>$page) {
                            print $page['mainData']."<br/>";
                            $parameters=array();
                            $obj=$page['mainData'];
                            foreach ($obj->attributes() as $name=>$val) {
                                //print("NAME: ".$name);
                                if ($name!='type' and $name !='control') {
                                    $v=(string) $val;
                                    $v=$ankieta->formatFilter($v);
                                    $parameters[(string) $name]=$v;
                                }
                            }
                            $ankieta->setNextSubmitParameters($parameters);
                            //print_r($page);
                            include($page['mainData']);
                            //$ankieta->addField("endDatePage_".$page['mainData'],"Czas końca strony ".$page['mainData'],"STRING","80");
                        }
                        //$flow[$ankieta->getCurrentStep()]['mainData']['control']=='end'
                        //$ankieta->addField("finished","Finished","STRING",1);

                        print "</span>";
                    }
                    ?>
                    <div id="footer">
                        <?
                            include('footer.php');
                        ?>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

    <?
        include('../../control.php');

    //CONTEXT VALIDATE MESSAGING
    ?>

<script>

    (function (global) {

        if(typeof (global) === "undefined")
        {
            throw new Error("window is undefined");
        }

        var _hash = "!";
        var noBackPlease = function () {
            global.location.href += "#";

            // making sure we have the fruit available for juice....
            // 50 milliseconds for just once do not cost much (^__^)
            global.setTimeout(function () {
                global.location.href += "!";
            }, 50);
        };

        // Earlier we had setInerval here....
        global.onhashchange = function () {
            if (global.location.hash !== _hash) {
                global.location.hash = _hash;
            }
        };

        global.onload = function () {

            noBackPlease();

            // disables backspace on page except on input fields and textarea..
            document.body.onkeydown = function (e) {
                var elm = e.target.nodeName.toLowerCase();
                if (e.which === 8 && (elm !== 'input' && elm  !== 'textarea')) {
                    e.preventDefault();
                }
                // stopping event bubbling up the DOM tree..
                e.stopPropagation();
            };

        };

    })(window);

    function validateForm(formName) {


        console.log('Validating form22');
        var error=false;
        var form = $( "#"+formName);
        //form.validate({ignore: ".ignore"}, {messages: {required: 'To pole jest wymagane.'}});
        form.validate({
            ignore: ".ignore",
            errorElement : 'div',
            errorPlacement: function(error, element) {
                //alert (element.parent().parent().parent().attr('class'));
                //alert(element.parent().parent().parent().parent().parent().attr('class'));
                //console.log('element',element);
                if (element.prop('nodeName').toLowerCase()=="textarea") {
                    //console.log("TEXTAREA");
                    error.appendTo(element.parent().parent().parent().parent());
                    return ;
                }
                if (element.parent().parent().parent().parent().parent().attr('data-qtype')=='table-horizontal') {
                    //console.log("TABLE HORIZONTAL");
                    error.appendTo(element.parent().parent().parent().find('td:first'));
                    return ;
                }
                if (element.prop('nodeName').toLowerCase()=="input") {
                    //console.log("INPUT BUTTON");
                    //error.appendTo(element.parent().parent().parent().parent());
                    //return ;
                    var name = $(element).attr("name").replace("[]","");
                    error.appendTo($("#" + name + "_validate"));
                    return ;
                }
                //alert (element.parent().parent().attr('id'));
                error.appendTo(element.parent().parent());
            },
            rules : {
                P4_1othern1 : { greaterThanZero : true },
                P4_2othern2 : { greaterThanZero : true },
                M6C : { greaterThanZero : true }
            }
        });
        jQuery.validator.addMethod("greaterThanZero", function(value, element) {
            return this.optional(element) || (parseFloat(value) > 0);
        }, "");

        $.validator.messages.required="<?php print $lang[$ankieta->getLanguage()]['ANSWEREQUIRED'];?>";
        if (form.valid()==true) {
            //validateFields('page'+(pagenr));
            //console.log("Jest ok");
        } else {
            error=true;
        }
        console.log('ERROR = '+error);
        return error;

    }

</script>

<?php
//print "CURRENT PAGE: ".$ankieta->getCurrentPage()."<br/>";
if ($logout==0) {
    $_SESSION['ankieta']=serialize($ankieta);
} else {
    $_SESSION=array();
}

//print session_id();

if ($generateDictionary==1) {
    print "<script>";
    //print "document.getElementById('bodyAnkieta').style.display='none;'";
    $_SESSION['ankieta']=serialize($ankieta);
    $code="try {";
    $code.="window.location('../../genDictionary.php?ID=".session_id()."');\n\r";
    $code.="} catch (ex) {";
    $code.="window.location.href='../../genDictionary.php?ID=".session_id()."';\n\r";
    $code.="}";
    //print "downloadDictionary();";
    print $code;
    print "</script>";
    $generateDictionary=0;
}

if ($generateVar==1) {
    print "<script>";
    //print "document.getElementById('bodyAnkieta').style.display='none;'";
    $_SESSION['ankieta']=serialize($ankieta);
    $code="try {";
    $code.="window.location('../../genVar.php?ID=".session_id()."&skipOpen=".$skipOpen."');\n\r";
    $code.="} catch (ex) {";
    $code.="window.location.href='../../genVar.php?ID=".session_id()."&skipOpen=".$skipOpen."';\n\r";
    $code.="}";
    //print "downloadDictionary();";
    print $code;
    print "</script>";
    $generateVar=0;
}

if ($generateJob==1) {
    print "<script>";
    //print "document.getElementById('bodyAnkieta').style.display='none;'";
    $_SESSION['ankieta']=serialize($ankieta);
    $code="try {";
    $code.="window.location('../../genJob.php?ID=".session_id()."&skipOpen=".$skipOpen."');\n\r";
    $code.="} catch (ex) {";
    $code.="window.location.href='../../genJob.php?ID=".session_id()."&skipOpen=".$skipOpen."';\n\r";
    $code.="}";
    //print "downloadDictionary();";
    print $code;
    print "</script>";
    $generateJob=0;
}


//new dBug($ankieta->getKolejnosc());

if ($generateKolej==1) {
    print "<script>";
    $_SESSION['ankieta']=serialize($ankieta);
    //$_SESSION['ankieta']=strtr(base64_encode(serialize($ankieta)),'+/=', '-_,');
    //var_dump($_SESSION['ankieta']);
    $code="try {";
    $code.="window.location('../../databaseExport.php?ID=".session_id()."');\n\r";
    $code.="} catch (ex) {";
    $code.="window.location.href='../../databaseExport.php?ID=".session_id()."';\n\r";
    $code.="}";
    //print "downloadDictionary();";
    print $code;
    print "</script>";
    $generateKolej=0;
}

//new dBug($_SESSION['ankieta']);

if ($generateSaveDAT==1) {
    print "<script>";
    $_SESSION['ankieta']=serialize($ankieta);
    //$_SESSION['ankieta']=strtr(base64_encode(serialize($ankieta)),'+/=', '-_,');
    //var_dump($_SESSION['ankieta']);
    $code="try {";
    $code.="window.location('../../genSaveDAT.php?ID=".session_id()."&skipOpen=".$skipOpen."');\n\r";
    $code.="} catch (ex) {";
    $code.="window.location.href='../../genSaveDAT.php?ID=".session_id()."&skipOpen=".$skipOpen."';\n\r";
    $code.="}";
    //print "downloadDictionary();";
    print $code;
    print "</script>";
    $generateKolej=0;
}


//new dBug($_SESSION['ankieta']);




if ($logout==1) {
    //$debugMode=1;
    if ($debugMode==1) {print "LOGOUT i niszczenie sesji <br/>";}
    //$ankieta->writeEndSurveyCode();

    /*@session_unset();
    @session_destroy();
    @session_write_close();
    @setcookie(session_name(),'',0,'/');
    @session_regenerate_id(true);*/
    //$ankieta->setAnkietaFinish(1);
    //@destroySession();
    //@session_start();
    @session_destroy();
    @session_regenerate_id(true);
    //session_start();
    //session_id(createRandomVal(27));
    if ($debugMode==1) {print "SESSION_ID=".session_id()."<br/>";}

    //$page=$_POST['page']+1;
}


//new dBug(serialize($ankieta));
?>
</body>
</html>




