#!/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";
BEGIN {
    delete $INC{"Kantelpunten/Helper.pm"};
#    delete $INC{"Kantelpunten/Process.pm"};
#    delete $INC{"Kantelpunten/MyRobots.pm"};
    delete $INC{"Kantelpunten/MyAdds.pm"};
    delete $INC{"Kantelpunten/MyBudy.pm"};
}
use Kantelpunten::Helper;
use Kantelpunten::Process;
use Kantelpunten::MyRobots;
use Kantelpunten::MyBudy;
use Kantelpunten::MyAdds;
#use Data::Dumper;

local our $stocks;
local our $param;
local our $page;
local our $data;

show_overview();
exit(0);

sub show_overview()
{
	my $q = CGI->new;

	$param->{overview}	= $q->param('overview');
	$param->{period}    = $q->param('period');
	$param->{menu}		= defined($q->param('mine')) ? 2 : 3;
	$param->{rb} 		= $q->param('rb');
	$param->{num}       = 2;
	
	my $remote_ip = init_helper();
	init_process();
	$param->{rb} = get_robot() if (!defined($param->{rb}) || $param->{rb});
	set_robot($param->{rb});
	
	$param->{period}   = "3mnd"  unless defined($param->{period});
	$param->{period}   = "3mnd"  if (($param->{period} ne "1mnd") && ($param->{period} ne "3mnd"));
	$param->{overview} = "undef" unless defined($param->{overview});
	$page = undef;
	$page = 9999 if ($param->{overview} eq 'eigen');
	$page = 9998 if ($param->{overview} eq 'aex');
	$page = 9997 if ($param->{overview} eq 'amx');
	$page = 9996 if ($param->{overview} eq 'overig');
	$page = 9996 if ($param->{overview} eq 'nl');           # same as overig
	$page = 9995 if ($param->{overview} eq 'bel20');
	$page = 9993 if ($param->{overview} eq 'bel');
	$data = undef;
	if ($param->{overview} eq 'kantel')
	{
		$page = 9994;
	    $param->{menu} = 4;
		$data = read_all_quote_data();
		if (!defined($data))
		{
    		print_error_doc("Probleem met het lezen van de kantelpunten data.");
    		exit(0);
		}
	}

	if (!defined($page))
	{
    	print_error_doc("Gekozen overview $param->{overview} wordt niet ondersteund.");
    	exit(0);
	}

	get_user_rec();
	$param->{budy} = init_budy($q->param('uitleg'));
	$stocks = get_stocks(undef, undef, "stock");
	if (!defined($stocks))
	{
    	print_error_doc "SO: Probleem met het lezen van de aandelen data.";
    	exit(0);
	}

	if (($param->{overview} eq "eigen") || ($param->{overview} eq "kantel"))
	{
		# will stop if not registered otherwise continue ...
    	only_allowed_for_registered_users();
	}

	my $sesid = get_session_cookie();   # try to get the session cookie

	add_last_page_cookie($page);

	write_access_data($remote_ip, $page);
	make_html($param->{overview});
}
    
sub make_html(@)
{
    my ($mkt) = @_;
    my $script = make_home_script($page);
    
    my $market = $mkt;
    my $tmkt = uc($market);
	my $title = "Kantelpunten : Aandelen overzicht ($tmkt) - Alle advies grafieken voor de actieve belegger bijeen.";
	my $desc  = "Alle aandelen van $tmkt in overzichtelijke grafieken per maand of per 3 maanden." .
		" In een oogopslag ziet u als actieve belegger de lopende en de afgelopen adviezen. " .
		" Kantepunten voor beleggers die graag zelf het heft in eigen hand nemen.";

    my $pop_menu = make_pop_menu($param->{menu}, $page, $param->{overview}, undef, ($param->{period} eq "1mnd"));
    my $top_menu = make_top_menu($param->{menu}, $page, $param->{overview}, undef, ($param->{period} eq "1mnd"));

    print_header("+1m");
    print_pre_doc();
    print_head($title, undef, undef, $market, $script, "overview", $market, undef, $desc, undef, "top_scipt");
    print_body($market, undef, undef, undef, undef, undef, undef, "kader", undef, $pop_menu, $top_menu);
    
	my $ads = show_adds("overview");
	
    my $ref = "ShowOverview.pl?uitleg=" . ($param->{budy} ? '0' : '1');
    $ref .= "&overview=$param->{overview}" if (defined($param->{overview}));
    print_budy($param->{budy}, $page, $ref);

#   	print_options_for_overview();

    print_div("center");
    print "<br><br><br>\n";

    my $num = 1;
    my $n1 = 3;
    my $n2 = 5;
    $mkt = "aex" if ($market eq "kantel");
    if ($market ne 'eigen')
    {
        # first make a list with the ids what to adde depends on the type
        my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime(time());
        my $add_time = ($wday == 0) ? (72*3600) : (($wday == 6) ? (48*3600) : (33*3600));
        my @shares = sort keys %$stocks;
# currently bigchart is not working anymore :-(
#        print_aex() if ($market eq 'aex'); 
        print_overzicht_heading($market) ;
	   	print_table(0, undef, 0, 0, 0, undef, "100%");
	   	print "<thead><tr><th width=\"310px\">&nbsp;</th><th width=\"310px\">&nbsp;</th></tr></thead>\n"; 
        for (my $i = 0; $i < @shares; $i++)
        {
            next if (!defined($stocks->{@shares[$i]}));
            if ($market ne "kantel")
            {
            	next if ($stocks->{@shares[$i]}->{market} ne $market);
        	}
        	else
        	{
	        	my $id = $stocks->{@shares[$i]}->{id};
		        next if (!$data->{$id}->{follow});
	        	next if ($data->{$id}->{state} != 1);
#	        	next if ($data->{$id}->{state} == 0);
#	        	next if (($data->{$id}->{state} == 2) || ($data->{$id}->{state} == 3));
#	        	next if (($data->{$id}->{state} >= 2) && ($data->{$id}->{state} <= 6) && ($data->{$id}->{scan_time} != $data->{$id}->{kantel_time}) && 
#	        		 (($data->{$id}->{scan_time} + (24*3600)) < time()) );
#	        	next if (($data->{$id}->{state} >= 12) && (($data->{$id}->{sold_on} + $add_time) < time()));
        	}
            make_stock(@shares[$i], $mkt, $num++);
            if ($ads && (($num == $n1) || ($num == $n2)))
            {
			   	make_add($market, $num);
            }
        }
	    make_stock(undef, undef, $num) if (($num % $param->{num}) == 0);	# draw last blok if needed
	    print_table(0, "end");
    }
    else
    {
        my $favorites = set_favorites();
        # make array with stock ids;
        my @ids;
        foreach  my $i (keys %$stocks)
        {
            @ids[$stocks->{$i}->{id}] = $i;
        }
#        print_aex();
        print_overzicht_heading($market);
	   	print_table(0, undef, 0, 0, 0, undef, "100%");
        for (my $i = 0; $i < @ids; $i++)
        {
            next if (substr($favorites, $i, 1) eq "0");
            next if (!defined($stocks->{@ids[$i]}));
            make_stock(@ids[$i], $market, $num++);
            if ($ads && (($num == $n1) || ($num == $n2)))
            {
			   	make_add($market, $num);
            }
        }
	    make_stock(undef, undef, $num) if (($num % $param->{num}) == 0);	# draw last blok if needed
	    print_table(0, "end");
    }
    
#    print <<EndOfText if ($market eq "eigen");
#<span><small>
#Op méér hopen, is meestal minder hebben.<br>
#Vooral op de beurs. Maar daar was u misschien zelf al achter.<br>
#Daarnaast hebben we ondervonden dat het meestal onnodig is een aandeel<br>
#jaren in de portefeuille te houden, om van de stijging te profiteren.<br>
#Ondertussen kan je niet meeliften met andere aandelen.<br>
#<br>
#Wij zijn zeer duidelijk in ons advies :<br>
#"Winst pakken = winst hebben." Die winst staat op je rekening.<br>
#Morgen zijn er verse koopkantelpunten.<br>
#EndOfText
    print <<EndOfText if ($market eq "eigen");
<span><small>
Ik verwacht dat ... Ik denk dat ... Ik hoop dat ...<br>
<br>
Blijf vooral verwachten, denken, hopen, praten over hoe<br>
hoog de koers zou moeten zijn. De beurs heeft het helemaal fout.<br>
Ooit komt elke verwachting doorgaans uit. Houdt goede moed!<br>
<br>
Bent u nog wel baas over uw aandelen? Of zijn zij<br>
meester geworden over u? Dat is het gevaar van zich<br>
emotioneel te hechten aan favoriete fondsen.<br>
<br>
Ondertussen kan men niet meeliften met de<br>
gemakkelijke opportuniteiten die wij dagelijks voor<br>
u klaar zetten. Winst pakken = winst hebben.<br>
<br><br>
EndOfText
    print_voet();
    print_div("end");
    print_body("end_kader");
    print_post_doc();
}

sub print_overzicht_heading(@)
{
    my ($market) = @_;
    my $type = uc $market;
    
    my $title = "Overzicht \"$type\" aandelen :";
    $title = "Uw favoriete aandelen :" if ($type eq "EIGEN");
    $title = "Overzicht adviezen :" if ($type eq "KANTEL");

    print "<span><small class=\"black\"><small><b>Men ziet de bodems, en opstart van nieuwe uptrends.<br>Linksboven kan men inzoomen op 1 maand.</b><br><br></small></small></span>\n" if ($type eq "KANTEL"); 
    print  "<span style=\"font-family: verdana; color: rgb(102, 0, 204);\">\n";
    print  " <small style=\"font-weight: bold;\">\n";
#    print  "  <br><br>___________________________________________________________________<br>\n";
    print_h1($title, undef, undef, "bm0");
#    print  "  <big><big><big><br>$title<br></big></big></big>\n";
#    print_buttons(undef, $page, 'homepage');
#    print  "  <br>___________________________________________________________________";
    print  "<br><br>\n";
    print  " </small>\n";
    print  "</span>\n";
    if ($type eq "OVERIG")
    {
        print "<span style=\"font-weight: bold; font-family: verdana; color: rgb(204, 0, 0); font-style: italic;\">\n";
        print " <small style=\"font-weight: bold;\">Kijk bij deze aandelen naar de verkoopbaarheid.<br></small>\n";
        print " <small>Zie </small>\n";
        print " <small style=\"font-weight: bold;\">diepteboek</small>\n";
        print " <small> ( biedprijzen + aantal kopers + volume ) &egrave;n</small>\n";
        print " <small style=\"font-weight: bold;\">ticklijst</small>.<br>\n";
        print " <small>Schat in hoeveel men krijgt als de trend omkeert !</small>\n";
        print "</span>\n";
        print "<br><br><br>\n";
    }
}

sub print_aex()
{
    print_dual_heading("AEX");
    print "\n<!-- Big Chart AEX type 3months -->\n";
#    print "<img src=\"http://chart.bigcharts.com/custom/ft-com/big.chart?symb=1810101&amp;sid=124174&amp;time=3mo&amp;freq=1dy&amp;comp=aaaaa%7E0&amp;compidx=aaaaa%3A0&amp;ma=2&amp;maval=9&amp;uf=0&amp;lf=4&amp;lf2=0&amp;lf3=0&amp;type=4&amp;expanded=false&amp;FTSite=FTCOM&amp;colMode=three&amp;chartSize=6&amp;indName=aaaaa%7E0&amp;t=e&amp;q=1810101&amp;s2=nl&amp;subtab=1&amp;company=NEW&amp;mocktick=1&amp;style=1566&amp;size=6&amp;rand=6670\"\n";
    print "<img src=\"http://bigcharts.marketwatch.com/charts/big.chart?symb=1810101&amp;sid=124174&amp;time=3mo&amp;freq=1dy&amp;comp=aaaaa%7E0&amp;compidx=aaaaa%3A0&amp;ma=2&amp;maval=9&amp;uf=0&amp;lf=4&amp;lf2=0&amp;lf3=0&amp;type=4&amp;expanded=false&amp;FTSite=FTCOM&amp;colMode=three&amp;chartSize=6&amp;indName=aaaaa%7E0&amp;t=e&amp;q=1810101&amp;s2=nl&amp;subtab=1&amp;company=NEW&amp;mocktick=1&amp;style=1566&amp;size=6&amp;rand=6670\"\n";
    print "     border=\"0\"\n";
    print "     height=\"371\"\n"; 
    print "     width=\"468\">\n";
    print "<br>\n";;
}
    
sub make_stock(@)
{
    my ($stock, $market, $num) = @_;

    if (1)
    {
		if (($num % $param->{num}) == 1)
		{
			print "<tr>\n";
		}
		print "<td align=\"center\">\n";
		if (defined($stock))
		{
	        print "<table class=\"over bg_d$market\">\n";
    	    print "<tr><td valign=\"top\" align=\"center\">\n";
    	    print_dual_heading($stocks->{$stock}->{html_name}, undef);
    	    print "</td></tr>\n";
        	print "<tr><td valign=\"top\" align=\"center\">\n";
	        print_our_graph($stocks->{$stock}, ($param->{period} eq "1mnd") ? "kantelk" : "kantelm", "/pl/ShowStock.pl?stock=$stocks->{$stock}->{stock}", "Toon grafieken voor dit aandeel");
    	    print "</td></tr>\n";
	        print "<tr><td valign=\"top\" align=\"center\">\n";
    	    print_div("center");
	        print_buttons($stock, undef, ($market ne 'eigen') ? 'mfav_add' : 'mfav_del');
    	    print_buttons($stock, undef, 'mkantel');
	        print_buttons($stock, undef, 'maandeel');
	        print_buttons($stock, undef, 'mquotes');
	        print_div("end");
	        print "</td></tr>\n";
	        print "</table>\n";
	    }
	    else
	    {
		    print "&nbsp;";
	    }
        print "</td>\n";
        if (($num % $param->{num}) == 0)
        {
	        print "</tr>\n";
	      	print "<tr><td colspan=\"$param->{num}\"><br><br></td></tr>\n";
	    }
    }
    else
    {
	    return if (!defined($stock));

        print_dual_heading($stocks->{$stock}->{html_name}, undef);
        print_table(0, undef, 0, 0, 0, undef, "100%");
        print "<tr>\n";
        # left buttons  
        print " <td width=\"50%\" valign=\"top\" align=\"center\">\n";
        print_div("center");
        print_buttons($stock, undef, ($market ne 'eigen') ? 'fav_add' : 'fav_del');
        print_div("end");
        print " </td>\n";

        # center graphic
       	print "<td valign=\"top\" align=\"center\">\n";
        print_our_graph($stocks->{$stock}, "kantelg");
  	    print "</td>\n";
        
        # right buttons  
        print " <td width=\"50%\" valign=\"top\" align=\"center\">\n";
        print_div("center");
        print_buttons($stock, undef, 'kantel', 'aandeel', 'quotes');
        print_div("end");
        print " </td>\n";
        print_table(0, "end");
    }
    

    return;

    # this is the old code left in in for historical purpose    
    if ($stocks->{$stock}->{overview} == 1)
    {
        print_dual_heading($stocks->{$stock}->{html_name}, "3 Maanden");
        print_table(0, undef, 0, 0, 0, undef, "100%");
        print "<tr>\n";
        # left buttons  
        print " <td width=\"50%\" valign=\"top\" align=\"center\">\n";
        print_div("center");
        print_buttons($stock, undef, ($market ne 'eigen') ? 'fav_add' : 'fav_del');
        print_div("end");
        print " </td>\n";

        # center graphic
        print " <td width=\"468px\">\n";
        print_div("center");
        print_big_graph($stocks->{$stock}, $stocks->{$stock}->{bchart_symb}, $stocks->{$stock}->{bchart_sid}, undef, "month", 1);
        print_div("end");
        print " </td>\n";  
        
        # right buttons  
        print " <td width=\"50%\" valign=\"top\" align=\"center\">\n";
        print_div("center");
        print_buttons($stock, undef, 'kantel', 'aandeel', 'quotes');
        print_div("end");
        print " </td>\n";
        print_table(0, "end");
    }
    else
    {
        print_dual_heading($stocks->{$stock}->{html_name}, "geen grafiek beschikbaar");
    }
    print "<small><br><br></small>\n";
}

sub make_add(@)
{
    my ($market, $num) = @_;

	print "<tr><td valign=\"center\" align=\"center\"colspan=\"$param->{num}\">\n";
  	print_banner_ads("main_banner", $market, undef, 1) if ($num == 3);
   	print_banner_ads("overview_midden", $market, undef, 2);
    print "</td></tr>\n";
}

sub print_options_for_overview()
{
	my $ref  = "/pl/ShowOverview.pl?overview=$param->{overview}";
    my $ref1;
    $ref1 = "$ref&period=1mnd" if ($param->{period} ne "1mnd");
    $ref1 = "$ref&period=3mnd" if ($param->{period} eq "1mnd");

    print "&nbsp;";
    print_option_table("left");
    print_option_table("3mnd", $ref1, "Grafieken laatste maand worden getoond. Klik hier voor 3 maanden overzichten.") if ($param->{period} ne "1mnd");
    print_option_table("1mnd", $ref1, "Grafieken laatste 3 maanden worden getoond. Klik hier voor laatste maand overzichten.") if ($param->{period} eq "1mnd");
	print_option_table("help",  "/pl/ShowMain.pl?page=20172", "Toelichting iconen.");
    print_option_table("end");
	print "<br><br>\n";
}
