#!/usr/local/bin/perl -w
#
# Common routines for cgi pages

#------------------------------------------------------------
sub page_controls{
    my ($query) = @_;

    my %labels = ( 'raw'    => 'Show raw output',
                   'format' => 'Show formatted output');
    print "<table border=0><tr><td rowspan=3>",
    $query->radio_group(-'name'   => 'mode',
                        -'values' => [ 'format bjobs output', 'raw bjobs output' ],
                        -'label'  => \%labels),
    "</td></tr><tr><td><b>",
    $query->submit('Lookup', "Refresh page"),
    "</td></tr><tr><td>";
    print "</b></table>";
}
#------------------------------------------------------------
sub get_usercookie_and_header{
    my ($query) = @_;

    # Recover the cookie...
    my %config = cookie('config');
    $config{'c_name'} = $query->param('c_name') || $config{'c_name'};
    my @name = getpwnam($config{'c_name'});
    my $fullname = $name[6];
    my $name_error = 1 unless (@name);
    
    # Refresh cookie
    my $cookie = cookie(-name  => 'config',
                        -value => \%config,
                        -path  => '/',
                        -expires => '+3M'
                        );
    print $query->header(-'cookie' => $cookie);
    return (\%config, $fullname, $name_error);
}
#------------------------------------------------------------
sub get_usercookie_and_header_SangerWeb{
    my ($query) = @_;

    # Recover the cookie...
    my %config = cookie('config');
    $config{'c_name'} = $query->param('c_name') || $config{'c_name'};
    my @name = getpwnam($config{'c_name'});
    my $fullname = $name[6];
    my $name_error = 1 unless (@name);
    
    # Refresh cookie
    my $cookie = cookie(-name  => 'config',
                        -value => \%config,
                        -path  => '/',
                        -expires => '+3M'
                        );
    #print $query->header(-'cookie' => $cookie);
    return (\%config, $fullname, $name_error, $cookie);
}
#------------------------------------------------------------
sub Set_prefs{
    my ($query, 
        $errored_name, 
        $first_time, 
        $program, 
        $subr,
        ) = @_;
    
    print "<p><b>ERROR: '$errored_name' is not a valid Sanger Institute login name.... ".
          "<i>Please try again.</i></b>"                        if ($errored_name);
    print "<p><b>Hi, looks like you are a new $program user..." if ($first_time);
    
    print "<p>Please login by entering your Sanger Institute login/username...<p>"; 
    
    print $query->startform(-method   =>'post');
    print $query->textfield(-name     => 'c_name',
                            -default  => $$config{'name'},
                            -size     => 30,
                            -override => 1, #non sticky
                            );
    if ($subr){
        &$subr();
    }else{
        print $query->submit(-label => 'Set preferences');
    }
    print $query->endform();
    exit;
}
#------------------------------------------------------------
sub usage_log{
    my ($string, $file) = @_;
    
    if (open (FILE, ">>$file")){
        print FILE "$string";
        close FILE;
    }
}
#------------------------------------------------------------
sub frame_title{
    my ($title, $description) = @_;

    print "<center>";
    print "<table cellspacing=0 cellpadding=10 bgcolor=\"MidnightBlue\" width=90% border=0>";
    print "<tr align=\"center\"><td>";
    print "<font color=\"yellow\"><font size=5><b>$title</font>";
   
    print "<br><font color=\"white\" size=2><center>$description</tr>" if ($description);
    print "</table><br>";
}
#------------------------------------------------------------
sub Setup_tooltip{
    my ($linkURL, 
        $linkname, 
        $tip, 
        $open_link_in_remote_window, 
        $style, 
        $tipfontsize, 
        $text_colour, 
        $text_size, 
        $fontname,
        ) = @_;
    
    $style                      = "" if (! $style);
    $tipfontsize                = 3  if (! $tipfontsize);
    $open_link_in_remote_window = 0  if (! $open_link_in_remote_window);
    $text_size                  = 3  if (! $text_size);
    my $extra = "";
    if ($open_link_in_remote_window){
        if ($open_link_in_remote_window eq "1"){
            $extra = "target=\"infowin\" onClick=\"open_win()\"";
        }elsif ($open_link_in_remote_window eq "2"){
            $extra = "target=\"_blank\"";   
        }else {
            # open link in specified frame
            $extra = "target=$open_link_in_remote_window";
        }
    }
    return "<font size=$text_size face=$fontname>".
           "<a ".
           "href=$linkURL ".
           "$style $extra ".
           "onMouseOver=\"return ".
           "toolTip(event,\'$tip\',1,$tipfontsize,\'$text_colour\')\" onMouseOut=\"return toolTip()\">".
           "$linkname".
           "</a>".
           "</font>"; 
}
#------------------------------------------------------------
sub Setup_styles{
    # Setup styles for links
    print "<STYLE>";
    print "\.b_green  { color: green;        text-decoration: none; font-weight: bold;}";
    print "\.green    { color: green;        text-decoration: none; font-weight: none;}";
    
    print "\.b_orange { color: red;          text-decoration: none; font-weight: bold;}";
    print "\.orange   { color: red;          text-decoration: none; font-weight: none;}";
    
    print "\.b_yellow { color: yellow;       text-decoration: none; font-weight: bold;}";
    print "\.yellow   { color: yellow;       text-decoration: none; font-weight: none;}";
    
    print "\.b_black  { color: black;        text-decoration: none; font-weight: bold;}";
    
    print "\.b_blue   { color: MidnightBlue; text-decoration: none; font-weight: bold;}";
    print "\.blue     { color: MidnightBlue; text-decoration: none; font-weight: none;}";

    print "</STYLE>"; 
}
#------------------------------------------------------------
sub print_footer{
    my ($alternative_name,$alternative_email) = @_;

    my $name = "Bug";
    $name = $alternative_name if((scalar(@_)>1) && ($alternative_name));
   
    my $email = "bug-real";
    $email = $alternative_email if((scalar(@_)>1) && ($alternative_email));

    print "<center></font>";
    print "<hr><p><i>Contact:</i> $name (<a HREF=\"mailto\:$email\@sanger.ac.uk\">$email\@sanger.ac.uk</a>)<br>";
    my $now = scalar localtime((stat($0))[9]);
    print "<I><font size=2>Last program update: $now</I></font></center>\n";
}
#------------------------------------------------------------
sub mailBug {
    my ($subject, $message, $who_to_mail) = @_;
    
    $message .= "\n\nprogram: $0";
  Mail::sendMail( -to      => $who_to_mail,
                  -subject => $subject, 
                  -message => $message);
}
#------------------------------------------------------------
sub Setup_scrolling_list{
    my ($query, $param_name, $viewsize, $values_aref, $default, $multiple) = @_;
    my $listbox = $query->scrolling_list(-'name'      => $param_name,
                                         -'size'      => $viewsize,
                                         -'value'     => $values_aref,
                                         -'default'   => $default,
                                         -'multiple'  => $multiple
                                         );
    return $listbox;
}
#------------------------------------------------------------
sub javascript{
    
    my $JSCRIPT=<<EOJS;

IE=(document.all)?1:0;
NS=(document.layers)?1:0;
if (!IE && !NS) {
 /*
     Dummy event var for v3 browsers. 
    I use eval because IE will not allow 
    event to be assigned directly even within the if!
 */
    eval('event = ""'); 
}

function toolTip(e,msg,on,size,col) { 
    if (!IE && !NS) {
        if (!msg) msg = '';
        window.status = msg; 
        return true;
    }
    if (IE && window.event.srcElement.title == '') window.event.srcElement.title = msg;
    else if (NS) {
        if (on) {
            // This is all well and good, but for some reason
            // you cant locate toolTips within a form....
            document.layers["tooltip"].document.write(\'<table border=0><tr><td><font size=\'+size+\' color=\'+col+\'>\'+msg+\'</td></tr></font></table>\'); 
            document.layers["tooltip"].document.close(); 
            document.layers["tooltip"].top = e.pageY;
            document.layers["tooltip"].left= e.pageX+20; 
            document.layers["tooltip"].visibility="show"; 
        }
        else document.layers["tooltip"].visibility="hide"; 
    }
    return true;
} 
    
// highlight a link
function highlight(img, imgsrc) {
    document[img].src = imgsrc;
}
    
// un-highlight a link
function unhighlight(img, imgsrc) {
document[img].src = imgsrc;
}

var myWin                                                                                                             
var myWinExist = false
function open_win (w,h,winname) {
    var windowOptions = "toolbar,resizable,scrollbars,width=w,height=h"
    myWin = window.open ("", winname, windowOptions)
}    
NS6 = (!document.all && document.getElementById)? 1:0;
NS4 = (document.layers) ? 1:0;
IE4 = (document.all) ? 1:0;

var divname = "jstooldiv";
var x = 0;
var y = 0;
var ZT_XOFFSET   = 10;
var ZT_YOFFSET   = 0;
var ZT_CAPTIONBG = "#ffdf27";
var ZT_TIPBG     = "#ffffd8";
var ZT_BORDERBG  = "#000000";
var ZT_TIPFG     = "#000000";

if(NS4 || IE4 || NS6) {
    document.onmousemove = mouseMove;
    if(NS4 || NS6) document.captureEvents(Event.MOUSEMOVE);
}

function mouseMove(e) {
    e = e || window.Event || window.event;
    if(NS4) {
	x = e.pageX +ZT_XOFFSET;
	y = e.pageY +ZT_YOFFSET;
    } else if(IE4) {
	x = event.x +ZT_XOFFSET;
	y = event.y +ZT_YOFFSET;
    } else if(NS6) {
	x = e.clientX +ZT_XOFFSET + window.pageXOffset;
	y = e.clientY +ZT_YOFFSET + window.pageYOffset;
    }
}

function ztooltip() {
    
    if(arguments.length == 1) {
	txt = ztooltip_simple(arguments[0]);

    } else if(arguments.length == 2) {
	txt = ztooltip_caption (arguments[0], arguments[1]);
    }

//    createDiv();

    if(NS4) {
	document.layers[divname].document.open("text/html");
	document.layers[divname].document.writeln(txt);
	document.layers[divname].document.close();
	document.layers[divname].left          = x;// + pageXOffset;
	document.layers[divname].top           = y;// + pageYOffset;
	document.layers[divname].visibility    = "show";

    } else if(IE4) {
	document.all[divname].innerHTML        = txt;
    	document.all[divname].style.pixelLeft  = x + document.body.scrollLeft;
	document.all[divname].style.pixelTop   = y + document.body.scrollTop;
	document.all[divname].style.visibility = "visible";
//        document.all[divname].style.clip       = "rect(0 7 7 3)";
    } else if(NS6) {
	l = document.getElementById(divname);

	rng = document.createRange();
   	rng.setStartBefore(l);
    	htmlFrag = rng.createContextualFragment(txt);

	while (l.hasChildNodes()) {
      	    l.removeChild(l.lastChild);
	}
    	l.appendChild(htmlFrag);

	l.style.left       = x;// + document.body.scrollLeft;
	l.style.top        = y;// + document.body.scrollTop;
	l.style.visibility = "visible";
    }
    return true;
}

function ztipoff() {
    if(NS4) {
	document.layers[divname].visibility = "hide";
    } else if(IE4) {
	document.all[divname].style.visibility = "hidden";
    } else if(NS6) {
	document.getElementById(divname).style.visibility = "hidden";
    }
}

function ztooltip_caption(caption,str) {
    txt = '<table border="0" cellspacing="0" cellpadding="0" bgcolor="'+ZT_BORDERBG+'">'+
          '<tr bgcolor="'+ZT_BORDERBG+'">'+
          '<td bgcolor="'+ZT_BORDERBG+'" rowspan="4"><img src="/icons/blank.gif" width="1" height="1" alt=""></td>'+
          '<td bgcolor="'+ZT_BORDERBG+'"><img src="/icons/blank.gif" width="1" height="1" alt=""></td>'+
          '<td bgcolor="'+ZT_BORDERBG+'" rowspan="4"><img src="/icons/blank.gif" width="1" height="1" alt=""></td>'+
          '</tr>'+
          '<tr bgcolor="'+ZT_CAPTIONBG+'">'+
          '<th bgcolor="'+ZT_CAPTIONBG+'"nowrap style="font-size: 10pt; color: '+ZT_TIPFG+';">'+caption+'</th>'+
          '</tr>'+
          '<tr bgcolor="'+ZT_TIPBG+'">'+
          '<td style="font-size:10pt; color: '+ZT_TIPFG+';">'+str+'</td>'+
          '</tr>'+
          '<tr bgcolor="'+ZT_BORDERBG+'">'+
          '<td bgcolor="'+ZT_BORDERBG+'"><img src="/icons/blank.gif" width="1" height="1" alt=""></td>'+
          '</tr>'+
          '</table>';
    return txt;
}

function ztooltip_simple(str) {
    txt = '<table border="0" cellspacing="0" cellpadding="0" bgcolor="'+ZT_BORDERBG+'">'+
          '<tr bgcolor="'+ZT_BORDERBG+'">'+
          '<td rowspan="3"><img src="/icons/blank.gif" width="1" height="1" alt=""></td>'+
          '<td><img src="/icons/blank.gif" width="1" height="1" alt=""></td>'+
          '<td rowspan="3"><img src="/icons/blank.gif" width="1" height="1" alt=""></td>'+
          '</tr>'+
          '<tr bgcolor="'+ZT_TIPBG+'">'+
          '<td style="font-size:10pt;">'+str+'</td>'+
          '</tr>'+
          '<tr bgcolor="'+ZT_BORDERBG+'">'+
          '<td><img src="/icons/blank.gif" width="1" height="1" alt=""></td>'+
          '</tr>'+
          '</table>';
    return txt;
}
    
var myWin                                                                                                             
var myWinExist = false
function open_win (winname,w,h) {
    var windowOptions = "width=" + w + ",height=" + h + ",resizable,scrollbars,status,toolbar,menubar";
    name = 'main';
    myWin = window.open ("", winname, windowOptions);
}
    

EOJS
return ($JSCRIPT);
}

1;
__END__

sub tooltip_code{

    my $JSCRIPT=<<EOJS;



EJOS

return ($JSCRIPT);
}


1;

__END__
