// $Id: common_rosters.js 42104 2007-06-18 15:29:16Z sbattaglia $

var W3C_DOM = ((typeof document.getElementById != 'undefined') && (typeof document.createElement != 'undefined')) ? true : false;

var editInnerHTML = "";
var deleteInnerHTML = "";
var currentRow = null;

// Add events to onload event handler


/************************************** HAK PER IL PASSAGGIO DELLA VARIABILE "SERVICE" IN QUERY-STRING */
/*
//alert("start");
//alert(location.href);
var url = location.href;
//alert(url);
if(url.indexOf("login")!=-1 && (url.indexOf("?")==-1 || url.indexOf("?null")!=-1)) {
	//alert("in");
	if(url.indexOf("?null")!=-1){
		url = url.substr(0,url.indexOf("?null"));
	}
	url = url + "?service=http%3A%2F%2F"+location.host+"%2Fc%2Fportal%2Flogin";				
	//alert(url);
	location.assign(url);
}
//alert("end");
*/

/************************************** / HAK PER IL PASSAGGIO DELLA VARIABILE "SERVICE" IN QUERY-STRING */




// typeof can be "string", "number", "boolean", "object", "array", "function", or "undefined"
function addLoadEvent(fn)
{
    // Mozilla
    if (typeof window.addEventListener != 'undefined')
    {
        window.addEventListener('load', fn, false);
    }
    // Opera
    else if (typeof document.addEventListener != 'undefined')
    {
        document.addEventListener('load', fn, false);
    }
    // IE
    else if (typeof window.attachEvent != 'undefined')
    {
        window.attachEvent('onload', fn);
    }
    // IE5Mac and others that don't support the above methods
    else
    {
        var oldfn = window.onload;
        if (typeof window.onload != 'function')
        {
            window.onload = fn;
        }
        else
        {
            window.onload = function()
            {
                oldfn();
                fn();
            };
        }
    }
}

// Add className to class attribute
function addClass(target, classValue)
{
    var pattern = new RegExp("(^| )" + classValue + "( |$)");

    if (!pattern.test(target.className))
    {
        if (target.className == "")
        {
            target.className = classValue;
        }
        else
        {
            target.className += " " + classValue;
        }
    }
    
    return true;
}

// Remove className from class attribute
function removeClass(target, classValue)
{
    var removedClass = target.className;
    var pattern = new RegExp("(^| )" + classValue + "( |$)");

    removedClass = removedClass.replace(pattern, "$1");
    removedClass = removedClass.replace(/ $/, "");
    target.className = removedClass;
    
    return true;
}

// Return a reference to element
function getRef(el)
{
    if(typeof el == "string")
    {
        return document.getElementById(el);
    }
    else if(typeof el == "object")
    {
        return el;
    }
    else return null;
}

function init(){
	if(document.forms[1] != null && document.forms[1].elements[0] != null) {
		document.forms[1].elements[0].focus();
		document.forms[1].elements[0].select();
	}
}

// transition effect to fade background of element from darker to lighter color
// could use var redBackground = new initArray(12);redBackground[0]="#33CC00"; format
function setbgColor(elId, r, g, b){
    getRef(elId).style.backgroundColor = "rgb("+r+","+g+","+b+")";
}

function fade(elId, sr, sg, sb, er, eg, eb, step, current, speed){
    // printfire("----- START fade()");
    if (current <= step){
        setbgColor(elId,Math.floor(sr * ((step-current)/step) + er * (current/step)),Math.floor(sg * ((step-current)/step) + eg * (current/step)),Math.floor(sb * ((step-current)/step) + eb * (current/step)));
        current++;
        setTimeout("fade('"+elId+"',"+sr+","+sg+","+sb+","+er+","+eg+","+eb+","+step+","+current+","+speed+")",parseInt(speed));
    }
    // printfire("----- END fade()");
}

function fadeIn(){
    if(!W3C_DOM)return;
    if(getRef('msg')) fade('msg', 51,204,0, 221,255,170, 30,1,20);
    if(getRef('status')) fade('status', 187,0,0, 255,238,221, 30,1,20);
    
    var arrayElements = getElementsByAttribute("tr", "class", "added");
    
    if (arrayElements.length > 0) {
        fade(arrayElements[0].id, 255,255,51, 255,255,255, 30, 1, 70)
    }
}
addLoadEvent(fadeIn);

function swapButtonsForConfirm(rowId, serviceId) {

    resetOldValue();
    var row = document.getElementById("row"+rowId);
    var editCell = document.getElementById("edit"+rowId);
    var deleteCell = document.getElementById("delete"+rowId);
    
    removeClass(row, "over");
    addClass(row, "highlightBottom");
    
    editInnerHTML = editCell.innerHTML;
    deleteInnerHTML = deleteCell.innerHTML;
    currentRow = rowId;
    
    editCell.innerHTML = "Really?";
    deleteCell.innerHTML = "<a id=\"yes\" href=\"deleteRegisteredService.html?id=" + serviceId + "\">Yes</a> <a id=\"no\" href=\"#\" onclick=\"resetOldValue();return false;\">No</a>";
}

function resetOldValue() {
    if (currentRow != null) {
        removeClass(document.getElementById("row"+currentRow), "over");
        removeClass(document.getElementById("row"+currentRow), "highlightBottom");
        var editCell = document.getElementById("edit"+currentRow);
        var deleteCell = document.getElementById("delete"+currentRow);
        var row = document.getElementById("row"+currentRow);
       
        editCell.innerHTML = editInnerHTML;
        deleteCell.innerHTML = deleteInnerHTML;
       
        editInnerHTML = null;
        deleteInnerHTML = null;
        currentRow = null;
    }
}

function getElementsByAttribute(elementType, attribute, attributeValue)
{
    // printfire("----- START getElementsByAttribute()");
    var elementArray = new Array();
    var matchedArray = new Array();
    
    
    if (elementType != null || elementType != "")
    {
        elementArray = document.getElementsByTagName(elementType);
    }
    else if (document.all)
    {
        elementArray = document.all;
    }
    else
    {
        elementArray = document.getElementsByTagName("*");
    }

    // printfire("-------- loop " + elementArray.length + " times through "+elementType+ " collection to find ones with " + attribute +" attribute of " + attributeValue);
    for (var i = 0; i < elementArray.length; i++)
    {
        // printfire("-------- loop : "+ (i+1));
       
        if (attribute == "class")
        {
            var pattern = new RegExp("(^| )" + attributeValue + "( |$)");

            if (pattern.test(elementArray[i].className))
            {
                matchedArray[matchedArray.length] = elementArray[i];
            }
        }
        else if (attribute == "for")
        {
            if (elementArray[i].getAttribute("htmlFor") || elementArray[i].getAttribute("for"))
             {
                if (elementArray[i].htmlFor == attributeValue)
                {
                    matchedArray[matchedArray.length] = elementArray[i];
                }
            }
        }
        else if (elementArray[i].getAttribute(attribute) == attributeValue)
        {
            matchedArray[matchedArray.length] = elementArray[i];
        }
    }
    // printfire("-------- found "+ matchedArray.length +" matching " + elementType + "s");
    // printfire("----- END getElementsByAttribute()");
    return matchedArray;
}

/*
Script Name: Javascript Cookie Script
Author: Public Domain, with some modifications
Script Source URI: http://techpatterns.com/downloads/javascript_cookies.php
Version 1.1.1
Last Update: 4 October 2007

Changes:
1.1.1 fixes a problem with Get_Cookie that did not correctly handle case
where cookie is initialized but it has no "=" and thus no value, the 
Get_Cookie function generates a NULL exception. This was pointed out by olivier, thanks

1.1.0 fixes a problem with Get_Cookie that did not correctly handle
cases where multiple cookies might test as the same, like: site1, site

This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  
*/

// this fixes an issue with the old method, ambiguous values 
// with this test document.cookie.indexOf( name + "=" );

// To use, simple do: Get_Cookie('cookie_name'); 
// replace cookie_name with the real cookie name, '' are required
function Get_Cookie( check_name ) {
	// first we'll split this cookie up into name/value pairs
	// note: document.cookie only returns name=value, not the other components
	var a_all_cookies = document.cookie.split( ';' );
	var a_temp_cookie = '';
	var cookie_name = '';
	var cookie_value = '';
	var b_cookie_found = false; // set boolean t/f default f
	
	for ( i = 0; i < a_all_cookies.length; i++ )
	{
		// now we'll split apart each name=value pair
		a_temp_cookie = a_all_cookies[i].split( '=' );
		
		
		// and trim left/right whitespace while we're at it
		cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');
	
		// if the extracted name matches passed check_name
		if ( cookie_name == check_name )
		{
			b_cookie_found = true;
			// we need to handle case where cookie has no value but exists (no = sign, that is):
			if ( a_temp_cookie.length > 1 )
			{
				cookie_value = unescape( a_temp_cookie[1].replace(/^\s+|\s+$/g, '') );
			}
			// note that in cases where cookie is initialized but no value, null is returned
			return cookie_value;
			break;
		}
		a_temp_cookie = null;
		cookie_name = '';
	}
	if ( !b_cookie_found ) 
	{
		return null;
	}
}

/*
only the first 2 parameters are required, the cookie name, the cookie
value. Cookie time is in milliseconds, so the below expires will make the 
number you pass in the Set_Cookie function call the number of days the cookie
lasts, if you want it to be hours or minutes, just get rid of 24 and 60.

Generally you don't need to worry about domain, path or secure for most applications
so unless you need that, leave those parameters blank in the function call.
*/
function Set_Cookie( name, value, expires, path, domain, secure ) {
	// set time, it's in milliseconds
	var today = new Date();
	today.setTime( today.getTime() );
	// if the expires variable is set, make the correct expires time, the
	// current script below will set it for x number of days, to make it
	// for hours, delete * 24, for minutes, delete * 60 * 24
	if ( expires )
	{
		expires = expires * 1000 * 60 * 60 * 24;
	}
	//alert( 'today ' + today.toGMTString() );// this is for testing purpose only
	var expires_date = new Date( today.getTime() + (expires) );
	//alert('expires ' + expires_date.toGMTString());// this is for testing purposes only

	document.cookie = name + "=" +escape( value ) +
		( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) + //expires.toGMTString()
		( ( path ) ? ";path=" + path : "" ) + 
		( ( domain ) ? ";domain=" + domain : "" ) +
		( ( secure ) ? ";secure" : "" );
}

// this deletes the cookie when called
function Delete_Cookie( name, path, domain ) {
	if ( Get_Cookie( name ) ) document.cookie = name + "=" +
			( ( path ) ? ";path=" + path : "") +
			( ( domain ) ? ";domain=" + domain : "" ) +
			";expires=Thu, 01-Jan-1970 00:00:01 GMT";
}

//BROWSER DETECT
var BrowserDetect = {
	init: function () {
		this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
		this.version = this.searchVersion(navigator.userAgent)
			|| this.searchVersion(navigator.appVersion)
			|| "an unknown version";
		this.OS = this.searchString(this.dataOS) || "an unknown OS";
	},
	searchString: function (data) {
		for (var i=0;i<data.length;i++)	{
			var dataString = data[i].string;
			var dataProp = data[i].prop;
			this.versionSearchString = data[i].versionSearch || data[i].identity;
			if (dataString) {
				if (dataString.indexOf(data[i].subString) != -1)
					return data[i].identity;
			}
			else if (dataProp)
				return data[i].identity;
		}
	},
	searchVersion: function (dataString) {
		var index = dataString.indexOf(this.versionSearchString);
		if (index == -1) return;
		return parseFloat(dataString.substring(index+this.versionSearchString.length+1));
	},
	dataBrowser: [
		{
			string: navigator.userAgent,
			subString: "Chrome",
			identity: "Chrome"
		},
		{ 	string: navigator.userAgent,
			subString: "OmniWeb",
			versionSearch: "OmniWeb/",
			identity: "OmniWeb"
		},
		{
			string: navigator.vendor,
			subString: "Apple",
			identity: "Safari"
		},
		{
			prop: window.opera,
			identity: "Opera"
		},
		{
			string: navigator.vendor,
			subString: "iCab",
			identity: "iCab"
		},
		{
			string: navigator.vendor,
			subString: "KDE",
			identity: "Konqueror"
		},
		{
			string: navigator.userAgent,
			subString: "Firefox",
			identity: "Firefox"
		},
		{
			string: navigator.vendor,
			subString: "Camino",
			identity: "Camino"
		},
		{		// for newer Netscapes (6+)
			string: navigator.userAgent,
			subString: "Netscape",
			identity: "Netscape"
		},
		{
			string: navigator.userAgent,
			subString: "MSIE",
			identity: "Explorer",
			versionSearch: "MSIE"
		},
		{
			string: navigator.userAgent,
			subString: "Gecko",
			identity: "Mozilla",
			versionSearch: "rv"
		},
		{ 		// for older Netscapes (4-)
			string: navigator.userAgent,
			subString: "Mozilla",
			identity: "Netscape",
			versionSearch: "Mozilla"
		}
	],
	dataOS : [
		{
			string: navigator.platform,
			subString: "Win",
			identity: "Windows"
		},
		{
			string: navigator.platform,
			subString: "Mac",
			identity: "Mac"
		},
		{
			string: navigator.platform,
			subString: "Linux",
			identity: "Linux"
		}
	]

};
BrowserDetect.init();
