#!/usr/bin/perl
# ----------------------------------------------------------------------------
#
#  (c) Copyright 2006 TradeExtender
# 
#  This software is proprietary to and embodies the confidential technology 
#  of TradeExtender. Possession, use, duplication or dissemination of the 
#  software and media is authorized only pursuant to a valid written license 
#  from TradeExtender.
#

use strict;
use lib "/var/www/vhosts/kantelpunten.com/httpdocs/pl/lib";
use lib "lib";
use lib "../../httpdocs/pl/lib";
BEGIN {
    delete $INC{"Kantelpunten/Helper.pm"};
#    delete $INC{"Kantelpunten/Process.pm"};
}
use Kantelpunten::Helper;
#use Kantelpunten::Process;
use CGI qw(:standard);
#use Data::Dumper;

local our $https;
local our $url_base;

register();
exit(0);

sub register()
{
	my $remote_ip = init_helper();

	$https = is_https_doc();
	$url_base = $https ? "https://www.kantelpunten.com/" : "http://www.kantelpunten.com/";
	
	my $url_opnieuw = $https ? "${url_base}pl/ShowHttps.pl?page=10058" : "${url_base}pl/Register.pl?action=Aanmelden";
	my $action   = param('action');
	$action = "Toon" unless defined($action);
	my $sesid;
	my $userid;
	my $email;

	$action = "Toon" if ( ($action eq "Gefaald") &&
						defined(get_user_rec(undef, undef, undef, undef, 'logged_in')));

	if ($action eq "Inloggen")
	{
    	my $password = param('password');
	    my $email    = param('email');
    	my $code     = param('code');
	    my $uid      = param('userid');
    
	    if (defined($password) && defined($email))
    	{
        	# called by pressing the button, verify login
	        $uid = login_user($email, $password);
#	        log_problem("found uid: $uid");
    	    if (defined($uid))
        	{
	            if (set_registered() ne '2')
    	        {
        	        # its ok, redirect
                	my $url = "${url_base}pl/Register.pl?action=Inloggen&userid=$uid&code=" . set_password();
	                print_redirect($url);
	               exit(0);
    	        }
	            else
        	    {
    	            $action = "Bezig";
    	            $userid = $uid;
	            }
    	    }
        	else
	        {
    	        # if we com here the verification failed
        	    print_redirect("${url_base}pl/Register.pl?action=Gefaald");
	            exit(0);
    	    }
	    }
	    elsif (defined($code) && defined($uid))
	    {
    	    # called by redirect or direct login
        	$userid = get_and_set_userid($remote_ip, undef, $uid, $code);
        	if (set_registered() ne '4')
	        {
    	        # hmm somehting failed with the login
        	    $action = "Gefaald"
	        }
    	    else
        	{
	        	if (set_lastlogin() == 0)
	    	    {
    	    	    set_lastlogin(time());
        	    	set_lastvisit(time());
	        	    write_user_rec();
	    	        $action = "Gelukt";
    	    	}
        		else
	        	{
    	        	# probably a reload of the page just show the info
	            	$action = "Toon";
    	   	 	}
	   	 	}
    	}            
	}

	if ($action ne "Gefaald")
	{
	    $sesid = get_session_cookie();   # try to get the session cookie
    	$userid = get_and_set_userid($remote_ip) if (($action ne "Gelukt") && ($action ne "Bezig"));
	    if (!defined($sesid))
	    {
    	    $sesid = get_new_id("ses");
	        # try to set session cookie
    	    add_session_cookie($sesid);
	        write_session_start($sesid, $userid, $remote_ip);
    	}
	    if (($action eq "Uitloggen") && (set_registered() eq '4'))
    	{
	    	if (is_trial_user())
	    	{
				$userid = get_and_set_userid($remote_ip, 'force');
	        	set_registered('3');
	        	# don't write the user rec !!
	    	}
	    	else
	    	{
	        	set_registered('3');
		        write_user_rec();
	        }
    	}
	# don't enforce showing know email
	#    $email = set_email();
	}

	my $script;
	my $refresh;
	my $sec = 2;
	if (($action eq "Gelukt") || ($action eq "Uitloggen") || ($action eq "Bezig"))
	{
		my $what = ($action eq "Bezig") ? "login" : "start";
	    param(-name => 'action', -value => undef);
	    if ($https == 0)
	    {
		    $script =  "<SCRIPT TYPE=\"text/javascript\">\n" .
		               "function reloadFrames()\n" .
    		           "{\n" .
        		       "parent.hoofd.location=\"http://www.kantelpunten.com/pl/ShowMain.pl?$what=1\"\n" .
            		   "parent.fondsen.location=\"http://www.kantelpunten.com/pl/NavMarket.pl\"\n" .
		               "parent.buttons.location=\"http://www.kantelpunten.com/pl/ShowButtons.pl?rand=" . rand(1000) . "\"\n" .
    		           "}\n" .
        		       "//-->\n" .
            		   "</SCRIPT>\n";
		}
		else
		{
			# no script will use a refresh statement
			$refresh = "$sec;URL=http://www.kantelpunten.com";
		}
	}
# This show a changing graphic which has been disabled. Alo use proccess.pm is required.
#	if (is_admin_user() && $action ne "Gefaald" && $action ne "Aanmelden")
#	{
#    	$script .= make_script();
#	}

	print_header("+1s");
	print_pre_doc();
	my $target = $https ? "_top" : "register";
	my $title = "Registreer gratis. Kantelpunten de beursscanner maakt beleggen eenvoudiger!";
	my $desc = "Registratie voor Kantelpunten de beursscanner is gratis. Door middel van registratie krijgt u". 
				"toegang tot al onze beleggingsadviezen en beurstips. Dagelijks nieuwe adviezen, nieuws, daghandel" .
				"en uw eigen favorieten onder handbereik voor de actieve belegger."; 
	print_head($title, $target, "register", undef, $script, undef, undef, $refresh, $desc);
	print "<body style=\"background-color: rgb(200, 225, 250);\"\n";
	print "      scroll=\"no\"\n";
	print "      onLoad=\"reloadFrames()\"\n" if (!$https && (($action eq "Gelukt") || ($action eq "Uitloggen") || ($action eq "Bezig")));
	print "      leftmargin=\"0\" topmargin=\"0\" marginheight=\"0\" marginwidth=\"0\" rightmargin=\"0\" bottommargin=\"0\"\n";
	print "      alink=\"#000099\" link=\"#000099\" vlink=\"#000099\" >\n";
	if ($https && ($action ne "Toon") && ($action ne "Aanmelden"))
	{
		print "<table style=\"height: 100%; width: 100%; text-align: left;\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\">\n";
		print " <tbody>\n";
		print "  <tr style=\"background-color: rgb(200, 225, 250);\">\n";
		print "   <td style=\"text-align: center;\">\n";
    	print "	   <a href=\"http://www.kantelpunten.com\" target=\"_top\">\n";
	    print "     <img vspace=\"0\"\n";
    	print "      hspace=\"0\"\n";
	    print "      style=\"border: 0px solid ; width: 160px; height: 95px;\"\n";
    	print "      alt=\"\"\n";
	    print "      title=\"\"\n";
    	print "      src=\"https://www.kantelpunten.com/pics/logo/logo-kantelpunten-beursscanner.jpg\"></a><br>\n";
	    print "    <small style=\"color: rgb(0, 0, 153); font-family: comic sans ms;\">U bevind zich in onze beveiligde omgeving. Klik op het logo om terug te gaan naar de website.</small>\n";
    	print "   </td>\n";
	    print "  </tr>\n";
		print "  <tr>\n";
		print "   <td style=\"height: 100%; vertical-align: top;\">\n";
	}
	print "<div style=\"text-align: center; color: rgb(0, 0, 153); font-family: comic sans ms;\">\n";
	if ($action eq "Gefaald")
	{
    	print_logo_klein();
	    print "<small><small><hr color=\"rgb(200, 225, 250)\" width=\"90%\"></small></small>\n";
    	print "<small>Login mislukt</small><br>\n";
	    print "<small class=\"l_black\"><a href=\"$url_opnieuw\">Probeer opnieuw</a></small><br>\n";
	    print "<small class=\"l_black\"><a href=\"https://www.kantelpunten.com/pl/ShowHttps.pl?page=10056\" target=\"_parent\">Reset Wachtwoord</a></small>\n";
#	    print "<small class=\"l_black\"><a href=\"http://www.kantelpunten.com/pl/ShowMain.pl?page=10027\" target=\"hoofd\">Nieuwe Registratie</a></small>\n";
	    print "<small><small><hr color=\"rgb(200, 225, 250)\" width=\"90%\"></small></small>\n";
    	print "<small>Maakt beurzen<br>eenvoudiger.</small>\n";
	    print "<small><small><hr color=\"rgb(200, 225, 250)\" width=\"90%\"></small></small>\n";
	}
	else
	{
		if ($action eq "Aanmelden")
		{
		    print "<form method=\"post\" action=\"${url_base}pl/Register.pl\" enctype=\"application/x-www-form-urlencoded\">\n";
		    print_logo_klein();
	    	print "<small><small><hr color=\"rgb(200, 225, 250)\" width=\"90%\"></small></small>\n";
		    print "<small style=\"color: rgb(0, 0, 153);\">U kunt hieronder</small><br>\n";
		    print "<small style=\"color: rgb(0, 0, 153);\">inloggen.</small><br>\n";
		    print "<small><small><hr color=\"rgb(200, 225, 250)\" width=\"90%\"></small></small>\n";
		    print "<small>Inloggen</small>\n" if ($https);
	    	my $width = $https ? "50%" : "98%";
		    print "<table align=\"center\" style=\"font-family: comic sans ms; color: rgb(0, 0, 153); width: $width;\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\" rightmargin=\"0\" topmargin=\"0\" bottommargin=\"0\">\n";
		    print "<tr><td style=\"width: 20%;\" align=\"right\"><small>Email</small></td><td><input style=\"width: 80%;\" type=\"text\" name=\"email\" value=\"$email\"/></td></tr>\n";
		    print "<tr><td style=\"width: 20%;\" align=\"right\"><small>Wachtwoord</small></td><td><input style=\"width: 80%;\" type=\"password\" name=\"password\"/></td></tr>\n";
		    print "<tr><td style=\"width: 20%;\"></td><td><input type=\"submit\" name=\"action\" value=\"Inloggen\" /></td></tr>\n";
		    print "</table>\n";
		    print "<small><small><hr color=\"rgb(200, 225, 250)\" width=\"90%\"></small></small>\n";
		    if (!$https)
	    	{
			    print "<small class=\"l_black\" style=\"color: rgb(0, 0, 153);\">\n";
		    	print "<a href=\"https://www.kantelpunten.com/pl/ShowHttps.pl?page=10058\" target=\"_top\" title=\"Via een beveiligde verbiding inloggen, klik hier\">Beveiligd&nbsp;inloggen</a></small>\n";
    		}
		    print "</form>\n";
		}
		elsif (!defined($userid) || (set_registered() ne '4'))
		{
		    print_logo_groot();
    		print "<small><small><hr color=\"rgb(200, 225, 250)\" width=\"90%\"></small></small>\n";
	    	print "<small style=\"color: rgb(0, 0, 153);\">Hallo bezoeker,</small><br>\n";
	    	print "<small style=\"color: rgb(0, 0, 153);\">U bent niet aangemeld</small><br>\n";
    		print "<small><small><hr color=\"rgb(200, 225, 250)\" width=\"90%\"></small></small>\n";
    		print "<small class=\"l_nblack bg_yellow\">\n";
		    print "<a href=\"${url_base}pl/Register.pl?action=Aanmelden\" title=\"Aanmelden\">&nbsp;Aanmelden.&nbsp;</a></small><br>\n";
    		print "<small class=\"l_nwhite\" style=\"background-color: rgb(0, 0, 153);\">\n";
#		    print "<a href=\"http://www.kantelpunten.com/pl/ShowMain.pl?page=10027\" target=\"hoofd\" title=\"Nieuwe Registratie\">&nbsp;Nieuwe&nbsp;Registratie.&nbsp;</a></small>\n";
    		print "<small><small><hr color=\"rgb(200, 225, 250)\" width=\"90%\"></small></small>\n";
		}
		else
		{
#    		print "<small><small><small><br></small></small></small>\n";
		    print_logo_groot();
    		print "<small><small><hr color=\"rgb(200, 225, 250)\" width=\"90%\"></small></small>\n";
	    	print "<small style=\"color: rgb(0, 0, 153);\">" . set_username() . ",</small><br>\n";
	    	print "<small style=\"color: rgb(0, 0, 153);\">we wensen U veel succes.</small><br>\n";
    		print "<small class=\"l_nblack bg_yellow\">\n";
		    print "<a href=\"${url_base}pl/Register.pl?action=Uitloggen\" title=\"Log uit\">&nbsp;Log uit.&nbsp;</a></small>\n";
    		print "<small><small><hr color=\"rgb(200, 225, 250)\" width=\"90%\"></small></small>\n";
    		if ($https && ($action ne "Toon"))
	    	{
    			print "<small style=\"color: rgb(0, 0, 153);\">U wordt binnen $sec seonden doorverwezen naar de kantelpunten site</small><br>\n";
	    		print "<small class=\"bg_yellow\" style=\"color: rgb(0, 0, 0);\">\n";
		    	print "<a href=\"http://www.kantelpunten.com\" title=\"Ga naar kantelpunten de beursscanner.\" target=\"_top\">&nbsp;Klik hier&nbsp;</a></small>\n";
	    		print "<small style=\"color: rgb(0, 0, 153);\">als u niet automatisch doorverwezen wordt.</small>\n";
		    	print "<small><small><hr color=\"rgb(200, 225, 250)\" width=\"90%\"></small></small>\n";
    		}
		}
	}
	print "</div>\n";
	if ($https && ($action ne "Toon"))
	{
		print "   </td>\n";
		print "  </tr>\n";
		print " </tbody>\n";
		print "</table>\n";
	}
	print "</body>\n";
	print "</html>\n";                    
}

sub print_logo_groot()
{
	return if $https;
	
	print "<a id=\"logo_ref\" href=\"http://www.kantelpunten.com/pl/ShowMain.pl?page=10000\" target=\"hoofd\">\n";
    print "<img id=\"logo_groot\"\n";
    print "      vspace=\"0\"\n";
    print "      hspace=\"0\"\n";
    print "      style=\"border: 0px solid ; width: 160px; height: 95px;\"\n";
    print "      alt=\"\"\n";
    print "      title=\"\"\n";
    print "      src=\"${url_base}pics/logo/logo-kantelpunten-beursscanner.jpg\">\n";
    print "</a>\n";
    if (0)
    {
    print "<small><small><small><br></small></small></small>\n";
    print "<small style=\"font-weight: bold;\">KANTELPUNTEN</small>\n";
    print "<small><small><hr color=\"rgb(200, 225, 250)\" width=\"90%\"></small></small>\n";
    print "<small>Maakt beurzen<br>eenvoudiger.</small>\n";
    }
}

sub print_logo_klein()
{
	return if $https;

	print "<img vspace=\"0\"\n";
    print "      hspace=\"0\"\n";
    print "      style=\"border: 0px solid ; width: 160px; height: 45px;\"\n";
    print "      alt=\"\"\n";
    print "      title=\"\"\n";
    print "      src=\"${url_base}pics/logo/logo-kantelpunten-klein.jpg\">\n";
    if (0)
    {
    print "<small><small><small><br></small></small></small>\n";
    print "<small style=\"font-weight: bold;\">KANTELPUNTEN</small>\n";
    print "<small><small><hr color=\"rgb(200, 225, 250)\" width=\"90%\"></small></small>\n";
    print "<small>Maakt beurzen<br>eenvoudiger.</small>\n";
    }
}

sub make_script()
{    
    # I could make it uikcer to make the list of stocks by writing them into to a file on a day by day basis
    my $stocks = get_stocks_market(0xff);
    if (!defined($stocks))
	{
  		print_error_doc("SKO: Probleem met het lezen van de aandelen data.");
        return "";
    }
    init_process();
	my $data = read_all_quote_data();
	if (!defined($data))
	{
    	print_error_doc("Probleem met het lezen van de advies data.");
        return "";
	}

	my $s_arr = "";
	my $s_lab = "";	
	my $in;
    foreach my $i (keys %$data)
    {
        next if ($i == 0);
        next if (!defined($stocks->{$i}));
        next if ($data->{$i}->{state} <= 1);	# never bought
		next if (($data->{$i}->{state} < 7) || ($data->{$i}->{state} > 11));        # only in market onces
        next if ($data->{$i}->{max_dif} < 3);   # at least 3 percent
        # for now do not sort further we could sort on max_dif
        $in = $stocks->{$i}->{index_name};
        $in =~ s/ /%20/g;
        $s_arr .= "\t\t\"$stocks->{$i}->{stock}\",";
        $s_lab .= "\t\t\"$in\",";
    }
    return "" if ($s_arr eq "");

	my $script = <<EndOfText;
<script language="JavaScript1.2">
	// show urls ?
	var display_url=0;
		
	// todo make list of stock + labels
	var stock_array =
	[
	    $s_arr
	    ""
	];
	var label_array =
	[
	    $s_lab
	    ""
	];
	
    var current_index = 0;
    window.setTimeout(ShowNextGraph, 5000);
    
    function ShowNextGraph()
    {
        var logoRef = document.getElementById("logo_ref");
        var logoId  = document.getElementById("logo_groot");
        if (logoId)
        {
            if (stock_array[current_index] != "") {
    		    logoId.setAttribute("src", "http://www.kantelpunten.com/php/ShowKantel.php?type=scans&stock=" + stock_array[current_index] + "&label=" + label_array[current_index]);
    		    logoRef.setAttribute("href", "/pl/ShowStock.pl?stock=" + stock_array[current_index]);
    	    } else {
    		    logoId.setAttribute("src", "${url_base}pics/logo/logo-kantelpunten-beursscanner.jpg");
    		    logoRef.setAttribute("href", "http://www.kantelpunten.com/pl/ShowMain.pl?page=10000");
    	    }
            current_index = (current_index + 1) % stock_array.length;
            window.setTimeout(ShowNextGraph, 5000);  
        }
    }
</script>
EndOfText

	return $script;    
}
