/**
 * opens a popup window
 */
var popUps = new Array();
function openPopup(source, popupname, attributes) {
	if(!source) {
		 return;
	}
	if (!popUps[popupname] || popUps[popupname].closed==true) {
		window.open(source,popupname,attributes);
	} else {
		popUps[popupname].close();
		popUps[popupname] = window.open(source,popupname,attributes);
	}
}


/**
* set events, w3c-compatible and ie
*/
function addEvent(obj, eventType, func, useCaption)
{
	try {
		if(location.href.indexOf(".print.") != -1) {
			return;
		}
		if (!obj || !eventType || !func) {
			return false;
		} else if (obj.addEventListener) {
			obj.addEventListener(eventType, func, useCaption);
			return true;
		} else if (obj.attachEvent) {
			var retVal = obj.attachEvent("on"+eventType, func);
			return retVal;
		} else {
			return false;
		}
	} catch(exc){}
}

/**
 * set a css class for a html element
 */
function setClass(element, className) {
	if(element == null || className == null) {
		return;
	}

	if(document.all && !window.opera) {
		element.className = className;
	} else{
		element.setAttribute("class", className);
	}
}

/**
 * remove a css class from a html element
 */
function removeClass(element) {
	if(element == null) {
		return;
	}

	if(document.all && !window.opera) {
		element.className = "";
	} else{
		element.removeAttribute("class");
	}
}

/**
 * get the name of a css class from a html element
 */
function getClassName(element) {
	if(element == null) {
		return "";
	}
	var className = document.all && !window.opera ? element.className : element.getAttribute("class");
	return className == null ? "" : className;
}

// avoid flicker in ie
try {
	if(document.execCommand) {
		document.execCommand( 'BackgroundImageCache', false, true ) ;
	}
}
catch (exception) {}

/**************************************************************/
/******* EXTENSION FOR MYPERSONAL / EXTFORMS ******************/



function setCookie(n, value) {
	$.cookie(n, value, { expires: 7, path: '/'});
}

function getCookie(n) {
	return $.cookie(n);
}

var userprot = function() {
	this.sessionid = getCookie("gensessionid");
	this.email = "";
	this.datanames = new Array();
	this.datavalues = new Array();
	this.adddata = function(name, value) {
		this.datanames[this.datanames.length] = name;
		this.datavalues[this.datavalues.length] = value;
	}
	this.getdata = function(name) {
		for (var i = 0; i<this.datanames.length; i++) {
			if (name==this.datanames[i]) return this.datavalues[i];
		}
		return "";
	}
	this.getuserconfigdata = function(name) {
		for (var i = 0; i<this.datanames.length; i++) {
			if ("UserLinkConfig_"+name==this.datanames[i]) return this.datavalues[i];
		}
		return "";
	}
	
	this.loggedin = false;
	this.setloggedin = function() {
		 this.loggedin = true;
	}
	this.setloggedout = function() {
		 this.loggedin = false;
	}
	this.isloggedin = function() {
		return this.loggedin;
	}
	
	this.userready = false;
	this.setuserready = function() {
		this.userready = true;
		for (var i = 0; i<this.onuserreadyactions.length; i++) {
			this.onuserreadyactions[i]();
		}
	}
	this.isuserready = function() {
		return this.userready;
	}
	
	this.onuserreadyactions = new Array();
	this.onuserready = function(callback) {
		if (this.userready) {
			callback();
		}
		else this.onuserreadyactions[this.onuserreadyactions.length] = callback;
	}
	
	this.getsessionid = function() {
		return this.sessionid;
	}
};



function getUserData(target) {
	var gensessionid = myuser.getsessionid();
	if (gensessionid!="" && gensessionid!=null) {
		var data = 'xmlrequest='+
			'<req>'+
			  '<task>getuserdata</task>'+
			  '<taskdata><sessionid>'+gensessionid+'</sessionid>'+
			  '</taskdata>'+
		'</req>';
		// security check:
		if (target.indexOf(window.location.host)>0) $.post(target, data, function(data) {
			if ($(data).find("isanonym").text()=="false") {
				myuser.setloggedin();
				$(data).find('userdata').each(function(){
                    
                    var dataname = $(this).find('dataname').text();
                    var datavalue = $(this).find('datavalue').text();
                    myuser.adddata(dataname,datavalue);   
                });
				
				myuser.adddata("email", $(data).find('user').find('email').text());
				myuser.adddata("awdcustomer", $(data).find('user').find('awdcustomer').text());
				myuser.adddata("awdconsultant", $(data).find('user').find('awdconsultant').text());
				
			}
			else {
			}	
			myuser.setuserready();
		}, "xml");
	}
}

function prefillForm(formname) {
	myuser.onuserready(function() {
		if (myuser.isloggedin()) {
			for (var i = 0; i < document.forms[formname].elements.length; i++) {
				try {
					if (document.forms[formname].elements[i].attributes.getNamedItem("useradd")) {
						if (myuser.getuserconfigdata(document.forms[formname].elements[i].attributes.getNamedItem("useradd").value)!="") {
							document.forms[formname].elements[i].value = myuser.getuserconfigdata(document.forms[formname].elements[i].attributes.getNamedItem("useradd").value);
						}
						else {
							document.forms[formname].elements[i].value = myuser.getdata(document.forms[formname].elements[i].attributes.getNamedItem("useradd").value);
						}
					}
				}
				catch (except) {
				}		
			}
		}
	});
}


/***********************************************************************************
 * Cookie plugin
 *
 * Copyright (c) 2006 Klaus Hartl (stilbuero.de)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 */

/**
 * Create a cookie with the given name and value and other optional parameters.
 *
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Set the value of a cookie.
 * @example $.cookie('the_cookie', 'the_value', { expires: 7, path: '/', domain: 'jquery.com', secure: true });
 * @desc Create a cookie with all available options.
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Create a session cookie.
 * @example $.cookie('the_cookie', null);
 * @desc Delete a cookie by passing null as value. Keep in mind that you have to use the same path and domain
 *       used when the cookie was set.
 *
 * @param String name The name of the cookie.
 * @param String value The value of the cookie.
 * @param Object options An object literal containing key/value pairs to provide optional cookie attributes.
 * @option Number|Date expires Either an integer specifying the expiration date from now on in days or a Date object.
 *                             If a negative value is specified (e.g. a date in the past), the cookie will be deleted.
 *                             If set to null or omitted, the cookie will be a session cookie and will not be retained
 *                             when the the browser exits.
 * @option String path The value of the path atribute of the cookie (default: path of page that created the cookie).
 * @option String domain The value of the domain attribute of the cookie (default: domain of page that created the cookie).
 * @option Boolean secure If true, the secure attribute of the cookie will be set and the cookie transmission will
 *                        require a secure protocol (like HTTPS).
 * @type undefined
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */

/**
 * Get the value of a cookie with the given name.
 *
 * @example $.cookie('the_cookie');
 * @desc Get the value of a cookie.
 *
 * @param String name The name of the cookie.
 * @return The value of the cookie.
 * @type String
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */
jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options = $.extend({}, options); // clone object since it's unexpected behavior if the expired property were changed
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        // NOTE Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};

/** INIT ACTIONS: ********************/

var myuser = new userprot();

