var BasePath = '/';
var win;

String.prototype.startsWith = function(str){ return (this.match("^" + str) == str) }

function IsEnterKey(e){
    if (window.event) { // IE
        if (e.keyCode == 13) {
            return true;
        }
    }
    else if(e.which == 13) { // Netscape/Firefox/Opera
        return true
    }
    
    return false;
}


function IsNumeric(sText, AddedChars)
{
   if (AddedChars == undefined) AddedChars = "";
   var ValidChars = "0123456789" + AddedChars;
   var IsNumber=true;
   var Char;
 
   for (i = 0; i < sText.length && IsNumber == true; i++) 
      { 
      Char = sText.charAt(i); 
      if (ValidChars.indexOf(Char) == -1) 
         {
         IsNumber = false;
         }
      }
   return IsNumber;  
 }
 
/* 
function isDate(sDate) {
	var scratch = new Date(sDate);
	if (scratch.toString() == "NaN" || scratch.toString() == "Invalid Date") {
		return false;
	} else {
		return true;
	}
}
*/

// Checks a string to see if it in a valid date format
// of (D)D/(M)M/(YY)YY and returns true/false
function isDate(s) {
    // format D(D)/M(M)/(YY)YY
    var dateFormat = /^\d{1,4}[\.|\/|-]\d{1,2}[\.|\/|-]\d{1,4}$/;

    if (dateFormat.test(s)) {
        // remove any leading zeros from date values
        s = s.replace(/0*(\d*)/gi, "$1");
        var dateArray = s.split(/[\.|\/|-]/);

        // correct month value
        dateArray[1] = dateArray[1] - 1;

        // correct year value
        if (dateArray[2].length < 4) {
            // correct year value
            dateArray[2] = (parseInt(dateArray[2]) < 50) ? 2000 + parseInt(dateArray[2]) : 1900 + parseInt(dateArray[2]);
        }

        var testDate = new Date(dateArray[2], dateArray[1], dateArray[0]);
        if (testDate.getDate() != dateArray[0] || testDate.getMonth() != dateArray[1] || testDate.getFullYear() != dateArray[2]) {
            return false;
        } else {
            return true;
        }
    } else {
        return false;
    }
}

function trim(str) {
	str = str.replace(/^\s+/, '');
	for (var i = str.length - 1; i >= 0; i--) {
		if (/\S/.test(str.charAt(i))) {
			str = str.substring(0, i + 1);
			break;
		}
	}
	return str;
}


function ScrollToElement(theElement) {

    var selectedPosX = 0;
    var selectedPosY = 0;

    while (theElement != null) {
        selectedPosX += theElement.offsetLeft;
        selectedPosY += theElement.offsetTop;
        theElement = theElement.offsetParent;
    }

    window.scrollTo(selectedPosX, selectedPosY);

}


function ShowDialogWin(WinTitle, WinStatusText, ContentUrl, WinContent, FWinW, FWinH, OnCloseFun) {
    var winW = 600;
    var winH = 400;

    var width = winW;
    var height = winH;

    if (parseInt(navigator.appVersion) > 3) {
        if (navigator.appName == "Netscape") {
            width = window.innerWidth;
            height = window.innerHeight;
        }
        if (navigator.appName.indexOf("Microsoft") != -1) {
            width = document.body.offsetWidth;
            height = document.body.offsetHeight;
        }
    }

    if (FWinW != undefined) {
        if (FWinW.toString().lastIndexOf("%") > 0) {
            FWinW = FWinW.toString().replace("%", "");
            if (FWinW >= 100) FWinW = 90;
            if (FWinW <= 0) FWinW = 20;
            winW = Math.floor(width * (FWinW / 100));
        } else {
            winW = FWinW;
        }
    }
    
    if (FWinH != undefined) {
        if (FWinH.toString().lastIndexOf("%") > 0) {
            FWinH = FWinH.toString().replace("%", "");
            if (FWinH >= 100) FWinH = 80;
            if (FWinH <= 0) FWinH = 40;
            winH =  Math.floor(height * (FWinH/100));
        } else {
            winH = FWinH;
        }
    }
    
    if (ContentUrl != '') {
        win = new Window({ className: "Alphacube",
                                width: winW, height: winH, zIndex: 100,
                                showEffect: Effect.BlindDown, hideEffect: Effect.SwitchOff,
                                resizable: true, draggable: true, wiredDrag: true,
                                title: WinTitle, 
                                onClose: OnCloseFun,
                                destroyOnClose: true
                            });
         win.setAjaxContent(ContentUrl, { method: "get" }, true, true);
    } else {
        win = new Window({ className: "Alphacube",
                                width: winW, height: winH, zIndex: 100,
                                showEffect: Effect.BlindDown, hideEffect: Effect.SwitchOff,
                                resizable: true, draggable: true, wiredDrag: true,
                                title: WinTitle,
                                onClose: OnCloseFun,
                                destroyOnClose: true
                            });
        win.getContent().innerHTML = WinContent;

        win.setStatusBar(WinStatusText);
        win.showCenter();
    }

    WindowCloseKey.init();

}

function TxtBlink(IdObjToBlink, FromColor, ToColor) {
    var testo = $(IdObjToBlink);

    if (FromColor === undefined) { FromColor = "#000000" }
    if (ToColor === undefined)   { ToColor ="#ff0000" }
    
    if (testo.style.color == FromColor){
        testo.style.color = ToColor;
    }else{
        testo.style.color = FromColor;
    }
}

function InitTxtBlink(IdObjToBlink, FromColor, ToColor, Speed) {
    if (FromColor === undefined) { FromColor = "#000000" }
    if (ToColor === undefined) { ToColor = "#ff0000" }
    if (Speed === undefined) { Speed = 1000 }
    
    window.setInterval("TxtBlink('SpedDaConfermare', '" + FromColor + "', '" + ToColor + "')", Speed);
}


function ToggleBlkVis(ObjId) {
    Effect.toggle('Blk_Cnt_' + ObjId, 'appear');
    $('Blk_img_' + ObjId).src = BasePath + 'img/bullet' + ($('Blk_Cnt_' + ObjId).visible() ? '_hide' : '') + '.png';

    new Ajax.Request(BasePath + 'svc/svc_ajax_Blk.aspx', {
                                                            method: 'get',
                                                            parameters: {
                                                                FC: 'SAVECOOKIEINFO',
                                                                FP: 'IDC=' + ObjId + '~CV=' + ($('Blk_Cnt_' + ObjId).visible() ? 'display:none;visibility:hidden;' : 'display:block;visibility:visible;')
                                                              }
                                                        });
}


function DateAdd(objDate, strInterval, intIncrement)
    {
        if(typeof(objDate) == "string")
        {
            objDate = new Date(objDate);
 
            if (isNaN(objDate))
            {
                throw("DateAdd: Date is not a valid date");
            }
        }
        else if(typeof(objDate) != "object" || objDate.constructor.toString().indexOf("Date()") == -1)
        {
            throw("DateAdd: First parameter must be a date object");
        }
 
        if(
        strInterval != "M"
        && strInterval != "D"
        && strInterval != "Y"
        && strInterval != "h"
        && strInterval != "m"
        && strInterval != "uM"
        && strInterval != "uD"
        && strInterval != "uY"
        && strInterval != "uh"
        && strInterval != "um"
        && strInterval != "us"
        )
        {
            throw("DateAdd: Second parameter must be M, D, Y, h, m, uM, uD, uY, uh, um or us");
        }
 
        if(typeof(intIncrement) != "number")
        {
            throw("DateAdd: Third parameter must be a number");
        }
 
        switch(strInterval)
        {
            case "M":
            objDate.setMonth(parseInt(objDate.getMonth()) + parseInt(intIncrement));
            break;
 
            case "D":
            objDate.setDate(parseInt(objDate.getDate()) + parseInt(intIncrement));
            break;
 
            case "Y":
            objDate.setYear(parseInt(objDate.getYear()) + parseInt(intIncrement));
            break;
 
            case "h":
            objDate.setHours(parseInt(objDate.getHours()) + parseInt(intIncrement));
            break;
 
            case "m":
            objDate.setMinutes(parseInt(objDate.getMinutes()) + parseInt(intIncrement));
            break;
 
            case "s":
            objDate.setSeconds(parseInt(objDate.getSeconds()) + parseInt(intIncrement));
            break;
 
            case "uM":
            objDate.setUTCMonth(parseInt(objDate.getUTCMonth()) + parseInt(intIncrement));
            break;
 
            case "uD":
            objDate.setUTCDate(parseInt(objDate.getUTCDate()) + parseInt(intIncrement));
            break;
 
            case "uY":
            objDate.setUTCFullYear(parseInt(objDate.getUTCFullYear()) + parseInt(intIncrement));
            break;
 
            case "uh":
            objDate.setUTCHours(parseInt(objDate.getUTCHours()) + parseInt(intIncrement));
            break;
 
            case "um":
            objDate.setUTCMinutes(parseInt(objDate.getUTCMinutes()) + parseInt(intIncrement));
            break;
 
            case "us":
            objDate.setUTCSeconds(parseInt(objDate.getUTCSeconds()) + parseInt(intIncrement));
            break;
        }
        return objDate;
    }
//Date.prototype.dateAdd = dateAddExtention;

//function dateAddExtention(p_Interval, p_Number) {
//    var thing = new String();


//    //in the spirt of VB we'll make this function non-case sensitive
//    //and convert the charcters for the coder.
//    p_Interval = p_Interval.toLowerCase();

//    if (isNaN(p_Number)) {

//        //Only accpets numbers 
//        //throws an error so that the coder can see why he effed up    
//        throw "The second parameter must be a number. \n You passed: " + p_Number;
//        return false;
//    }
//    p_Number = new Number(p_Number);
//    switch (p_Interval.toLowerCase()) {
//        case "yyyy":
//            {// year
//                this.setFullYear(this.getFullYear() + p_Number);
//                break;
//            }
//        case "q":
//            {        // quarter
//                this.setMonth(this.getMonth() + (p_Number * 3));
//                break;
//            }
//        case "m":
//            {        // month
//                this.setMonth(this.getMonth() + p_Number);
//                break;
//            }
//        case "y":        // day of year
//        case "d":        // day
//        case "w":
//            {        // weekday
//                this.setDate(this.getDate() + p_Number);
//                break;
//            }
//        case "ww":
//            {    // week of year
//                this.setDate(this.getDate() + (p_Number * 7));
//                break;
//            }
//        case "h":
//            {        // hour
//                this.setHours(this.getHours() + p_Number);
//                break;
//            }
//        case "n":
//            {        // minute
//                this.setMinutes(this.getMinutes() + p_Number);
//                break;
//            }
//        case "s":
//            {        // second
//                this.setSeconds(this.getSeconds() + p_Number);
//                break;
//            }
//        case "ms":
//            {        // second
//                this.setMilliseconds(this.getMilliseconds() + p_Number);
//                break;
//            }
//        default:
//            {

//                //throws an error so that the coder can see why he effed up and
//                //a list of elegible letters.
//                throw "The first parameter must be a string from this list: \n" +
//                    "yyyy, q, m, y, d, w, ww, h, n, s, or ms. You passed: " + p_Interval;
//                return false;
//            }
//    }
//    return this;
//}














/*****************************
Funzioni User Interface
*****************************/
//La funzione apre una LightWin con i parametri passati
function ShowLightWin(Url, Titolo, Caption){
    myLightWindow.activateWindow({href: Url, title: Titolo, caption:Caption});
}

/********************************
Funzione helper per recuperare un seed univoco per ovviare al problema del caching
********************************/
function GetSeed(){
    return new Date().getTime();
}




function addScriptTag(id, src) {
    var head = document.getElementsByTagName('head')[0];
    if ($(id) == null) {
        var script = document.createElement('script');
        script.id = id;
        script.type = 'text/javascript';
        script.src = src;
        head.appendChild(script);
//        (function(){id==1;}).delay(1);
    }
}




function GetPortalStatus(PortalBaseUrl, ContainerID) {
    if (PortalBaseUrl.toString().substring(PortalBaseUrl.toString().length - 1) != '/') { PortalBaseUrl += '/'; }
    
    var Url = BasePath + 'svc/svc_ajax_proxy.aspx?SEED=' + GetSeed();
    var ReqUrl = PortalBaseUrl + 'svc/svc_status.aspx?SEED=' + GetSeed();
    
    $(ContainerID).innerHTML = '<img src="' + BasePath + 'img/indicator.gif" alt="" border="0" align="absmiddle">' + Url;
    new Ajax.Updater(ContainerID, Url, {
                                            method: 'get',
                                            asynchronous: true,
                                            evalScripts: false,
                                            parameters: {U:ReqUrl},
                                            onException: function(r, exc) {
                                                                           $(ContainerID).innerHTML = 'Status <b>' + PortalBaseUrl + '</b> ' + 
                                                                                                      '<img src="' + BasePath + 'img/status_ko.png" align="absmiddle"> ' + 
                                                                                                      'Server down o non accessibile !!!<br>' +
                                                                                                      '<a href="javascript:void(0);" onclick="GetPortalStatus(\'' + PortalBaseUrl + '\', \'' + ContainerID + '\');"><img src="' + BasePath + 'img/reload.png" width="16" border="0" align="absmiddle"></a>';
                                                                            $(ContainerID).innerHTML += '<br><br>' + exc;
                                                                          },
                                            onComplete: function(r) { $(ContainerID).innerHTML += '<br><a href="javascript:void(0);" onclick="GetPortalStatus(\'' + PortalBaseUrl + '\', \'' + ContainerID + '\');"><img src="' + BasePath + 'img/reload.png" width="16" border="0" >'; }
                                        }
					);
    return false;
}






//function SetBgStyle(StyleStr) {
//    document.body.style.cssText = StyleStr;
//	if (StyleStr.lastIndexOf('segesta') > 0) { $('CntTopTable').style.background = 'none'; }
//}

function SetBgStyle(StyleStr, HideLogo) {
    document.body.style.cssText = StyleStr;
    if (HideLogo) { $('CntTopTable').style.background = 'none'; }
}






function CheckDisclaimer() {
    if (readCookie("LGP_DISCLAIMER") != "1") {
        Dialog.confirm({ url: BasePath + "html/informativa.htm", options: { method: 'get'} },
                         { className: "Alphacube", width: 540,
                           okLabel: "Accetto",
                           cancelLabel: "Non accetto", 
                           ok: function(win) { SetDisclaimer(true); win.close(); },
                           cancel: function(win) { SetDisclaimer(false); document.location = BasePath + "html/NoAccept.htm"; } 
                       });
    } else {
        SetDisclaimer(true);
    }
}

function SetDisclaimer(IsOk) {
    if (IsOk) {
        createCookie("LGP_DISCLAIMER", "1", 30);
    } else {
        eraseCookie("LGP_DISCLAIMER");
    }
}




function createCookie(name, value, days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        var expires = "; expires=" + date.toGMTString();
    }
    else var expires = "";
    document.cookie = name + "=" + value + expires + "; path=/";
}

function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') c = c.substring(1, c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
    }
    return null;
}

function eraseCookie(name) {
    createCookie(name, "", -1);
}
