﻿/*  base.js
author: Alessandro Piccione 
creation: 02 Apr 2009
last update: 22 November 2011

*/


/* return a random integer from 0 to max */
function getRandomInt(max) {
    var ranNum = Math.floor(Math.random() * max);
    return ranNum;
}

/* return a random decimal number from 0 to max */
function getRandom(max) {
    var ranNum = Math.random() * max;
    return ranNum;
}


function getClientWidth() {
    var w;
    if (document.innerWidth) {
        w = document.innerWidth;
    } else if (document.documentElement.clientWidth) {
        w = document.documentElement.clientWidth;
    } else if (document.body) { w = document.body.clientWidth; }
    return w;
    //document.screen.availWidth;
}

function getClientHeight() {
    var h;
    if (document.innerHeight) {
        h = document.innerHeight;
    } else if (document.documentElement.clientHeight) {
        h = document.documentElement.clientHeight;
    } else if (document.body) { h = document.body.clientHeight; }
    return h;
    //document.screen.availHeight;
}

/*************
* messages 
*************/

var INFO = 1;
var WARNING = 2;
var ERROR = 3;

var MESSAGE_SHOW_TIMEOUT = 6; // seconds               

function showInfo(text) {
    return showMessage(INFO, text)
}

function showWarning(text) {
    return showMessage(WARNING, text)
}

function showError(text) {
    return showMessage(ERROR, text)
}

//var messages = [];
var messagesCounter = 0;
// create and show a message. Return the id to use with function for remove
function showMessage(messageType, text, isPermanent) {
    if (!isPermanent)
        isPermanent = false;

    //alert(123);
    if ($('#messagesPanel').length == 0) {
        console.log('posticipate');
        setTimeout("showMessage(" + messageType + ",'" + text + "'," + isPermanent + ");", 250);
        return;        
    }
              

    newId = 'messages_' + messagesCounter++;
    var newMessage = $('<div>').attr('id', newId).text(text);
    newMessage.data('id', newId);
    var img = $('<img>');
        
    var imageUrl;
    var styleClass;
    switch (messageType) {
        case ERROR:
            imageUrl = '/Icons/MessageError.png';
            styleClass = "messageError";
            break;
        case WARNING:
            imageUrl = '/Icons/MessageWarning.png';
            styleClass = "messageWarning";
            break;
        case INFO:
            imageUrl = '/Icons/MessageInfo.png';
            styleClass = "messageInfo";
            break;
        default:
            imageUrl = '/Icons/MessageInfo.png';
            styleClass = "messageInfo";
            break;
    }

    // create a "X" (on hover?) on the right for hide closing the message
    // create a "pin" (on hover) to "pin" the message

    img.attr('src', imageUrl).css({ 'vertical-align': 'text-bottom', 'margin-right': 15 }).height(18).width(18);

    var pinButton = $('<span style="cursor:pointer; font-weight:bolder" onclick="pinMessage(\'' + newId + '\');\">V</span>');  // use an image

    var closeImageUrl = "/Icons/Close_small.png";
    var closeButton = $('<span style="cursor:pointer; font-weight:bolder" onclick="closeMessage(\'' + newId + '\');\"><img src="'+closeImageUrl+'" /></span>')  // use an image
        .css({ /*'position': 'absolute',*/'right': 5, 'float': 'right', 'opacity': 0.3 })
        //.hover( function())
        .mouseover(function () { $(this).css('opacity', 1.0) })
        .mouseout(function () { $(this).css('opacity', 0.3) })
        ;


    newMessage.prepend(img);
    //newMessage.append(pinButton);
    newMessage.append(closeButton);
    newMessage.addClass(styleClass).css('display', 'none');

    //$('#messagesPanel').load(function () { alert('sti gran cazzi: ' + this.toString()); });
    //$('#messagesPanel').load(function () { alert('sti gran cazzi load'); });
    //$('#messagesPanel').ready(function () { $(this).append(newMessage); });


    $('#messagesPanel').append(newMessage);
    isPermanent = true;

    //messages.push(newMessage); push in array?
    newMessage.fadeIn("fast");
    if (!isPermanent) {
        setTimeout("closeMessage('" + newId + "');", MESSAGE_SHOW_TIMEOUT * 1000);
    }

    return newId;
}

// Remove message from interface
function closeMessage(id) {
    var $message = $('#' + id);
    if($message)
        $message.slideUp('slow', function () { /*$(this).remove();*/ });
    //$(messages).find(' ... it is necessary to remove from collection ???
}

function pinMessage() {
    //$('#' + id).slideUp('slow', function () { /*$(this).remove();*/ });
}
 



/***************************
* COOKIES         
* Alessandro Piccione   
* 18/01/2008 
* 16/12/2008 (Alessanadro) aggiunto parametro path
***************************/

function setCookie(c_name, value, expiredays, path) {
    var exdate = new Date();
    exdate.setDate(exdate.getDate() + expiredays);

    if (!path)
        path = "/";

    document.cookie = c_name + "=" + escape(value) + ((expiredays == null) ? "" : ";expires=" + exdate.toGMTString()) + ";path=" + path;
}

function getCookie(c_name) {
    if (document.cookie.length > 0) {
        c_start = document.cookie.indexOf(c_name + "=");
        if (c_start != -1) {
            c_start = c_start + c_name.length + 1;
            c_end = document.cookie.indexOf(";", c_start);
            if (c_end == -1)
                c_end = document.cookie.length;
            return unescape(document.cookie.substring(c_start, c_end));
        }
    }
    return "";
}



/*******************************************************************************
* EVENT ON RETURN KEY PRESS
* Alessandro Piccione (02/2008)
* key handler for textbox 
* handle the submit (return key) of a control and execute the click of a specified button
********************************************************************************/
function setButtonToClick(buttonId, event) {
    if (event.keyCode == 13) {
        event.returnValue = false;
        event.cancel = true;
        document.getElementById(buttonId).click();
    }
}

function setCodeToExecute(code, event) {
    if (event.keyCode == 13) {
        event.returnValue = false;
        event.cancel = true;

        eval(code);
    }
}


/*******************************
* DateTime
********************************/

// Timezone stuff
// tz in format [+-]HHMM
function checkTimezone(tz, msg) {
    var localclock = new Date();
    // returns negative offset from GMT in minutes
    var tzRaw = localclock.getTimezoneOffset();
    var tzHour = Math.floor(Math.abs(tzRaw) / 60);
    var tzMin = Math.abs(tzRaw) % 60;
    var tzString = ((tzRaw >= 0) ? "-" : "+") + ((tzHour < 10) ? "0" : "") + tzHour + ((tzMin < 10) ? "0" : "") + tzMin;
    if (tz != tzString) {
        var junk = msg.split('$1');
        document.write(junk[0] + "UTC" + tzString + junk[1]);
    }
}
function unhidetzbutton() {
    tzb = document.getElementById('guesstimezonebutton')
    if (tzb) tzb.style.display = 'inline';
}

// in [-]HH:MM format...
// won't yet work with non-even tzs
function fetchTimezone() {
    // FIXME: work around Safari bug
    var localclock = new Date();
    // returns negative offset from GMT in minutes
    var tzRaw = localclock.getTimezoneOffset();
    var tzHour = Math.floor(Math.abs(tzRaw) / 60);
    var tzMin = Math.abs(tzRaw) % 60;
    var tzString = ((tzRaw >= 0) ? "-" : "") + ((tzHour < 10) ? "0" : "") + tzHour +
        ":" + ((tzMin < 10) ? "0" : "") + tzMin;
    return tzString;
}

