var ie = /MSIE/.test(navigator.userAgent);
var crome=(navigator.appVersion.indexOf("Chrome")==-1)? false:true;
var moz = !ie && navigator.product == "Gecko"&&!crome;
var IE6=(navigator.appVersion.indexOf("MSIE 6")==-1)? false:true;
var IE7=(navigator.appVersion.indexOf("MSIE 7")==-1)? false:true;
var IE8=(navigator.appVersion.indexOf("MSIE 8")==-1)? false:true;

	
var m2ws_cW;
var m2ws_cH;
var projPath='/mtpw';
if(window.location.pathname!=projPath+'/application/admin/root/'&&window.location.pathname!=projPath+'/application/admin/root/admin.php'){
//if(window.location.host!='www.admin.home.m2ws.de'){
		
	if(moz){
		m2ws_cW=window.innerWidth;
		m2ws_cH=window.innerHeight;
	}else{
		if(document.body){
		if(document.documentElement.clientWidth||document.body.clientWidth){
		m2ws_cW=document.documentElement.clientWidth ? document.documentElement.clientWidth : document.body.clientWidth;
		m2ws_cH=document.documentElement.clientHeight ? document.documentElement.clientHeight : document.body.clientHeight;
		}
		}
	}
}
/*
function _dom_trackActiveElement(evt) {  
	//alert("--->"+evt.target);
	if (evt && evt.target) {   
		
		alert("--->"+evt.target);
		document.activeElement =         
			evt.target == document ? null : evt.target;  
		
	}
} 
function _dom_trackActiveElementLost(evt) {   
	document.activeElement = null; 
	} 

if (document.addEventListener) {  
	document.addEventListener("focus",_dom_trackActiveElement,true);  
	document.addEventListener("blur",_dom_trackActiveElementLost,true);
}
*/

/*
 * Extends the event object with srcElement, cancelBubble, returnValue,
 * fromElement and toElement
 */
function extendEventObject() {
	Event.prototype.__defineSetter__("returnValue", function (b) {
		if (!b) this.preventDefault();
		return b;
	});

	Event.prototype.__defineSetter__("cancelBubble", function (b) {
		if (b) this.stopPropagation();
		return b;
	});

	Event.prototype.__defineGetter__("srcElement", function () {
		var node = this.target;
		while (node.nodeType != 1) node = node.parentNode;
		return node;
	});

	Event.prototype.__defineGetter__("fromElement", function () {
		var node;
		if (this.type == "mouseover")
			node = this.relatedTarget;
		else if (this.type == "mouseout")
			node = this.target;
		if (!node) return;
		while (node.nodeType != 1) node = node.parentNode;
		return node;
	});

	Event.prototype.__defineGetter__("toElement", function () {
		var node;
		if (this.type == "mouseout")
			node = this.relatedTarget;
		else if (this.type == "mouseover")
			node = this.target;
		if (!node) return;
		while (node.nodeType != 1) node = node.parentNode;
		return node;
	});

	Event.prototype.__defineGetter__("offsetX", function () {
		return this.layerX;
	});
	Event.prototype.__defineGetter__("offsetY", function () {
		return this.layerY;
	});
}

/*
 * Emulates element.attachEvent as well as detachEvent
 */
function emulateAttachEvent() {
	HTMLDocument.prototype.attachEvent =
	HTMLElement.prototype.attachEvent = function (sType, fHandler) {
		var shortTypeName = sType.replace(/on/, "");
		fHandler._ieEmuEventHandler = function (e) {
			window.event = e;
			return fHandler();
		};
		this.addEventListener(shortTypeName, fHandler._ieEmuEventHandler, false);
	};

	HTMLDocument.prototype.detachEvent =
	HTMLElement.prototype.detachEvent = function (sType, fHandler) {
		var shortTypeName = sType.replace(/on/, "");
		if (typeof fHandler._ieEmuEventHandler == "function")
			this.removeEventListener(shortTypeName, fHandler._ieEmuEventHandler, false);
		else
			this.removeEventListener(shortTypeName, fHandler, true);
	};
}

/*
 * This function binds the event object passed along in an
 * event to window.event
 */
function emulateEventHandlers(eventNames) {
	for (var i = 0; i < eventNames.length; i++) {
		document.addEventListener(eventNames[i], function (e) {
			window.event = e;
		}, true);	// using capture
	}
}

/*
 * Simple emulation of document.all
 * this one is far from complete. Be cautious
 */

function emulateAllModel() {
	var allGetter = function () {
		var a = this.getElementsByTagName("*");
		var node = this;
		a.tags = function (sTagName) {
			return node.getElementsByTagName(sTagName);
		};
		return a;
	};
	HTMLDocument.prototype.__defineGetter__("all", allGetter);
	HTMLElement.prototype.__defineGetter__("all", allGetter);
}

function extendElementModel() {
	HTMLElement.prototype.__defineGetter__("parentElement", function () {
		if (this.parentNode == this.ownerDocument) return null;
		return this.parentNode;
	});

	HTMLElement.prototype.__defineGetter__("children", function () {
		var tmp = [];
		var j = 0;
		var n;
		for (var i = 0; i < this.childNodes.length; i++) {
			n = this.childNodes[i];
			if (n.nodeType == 1) {
				tmp[j++] = n;
				if (n.name) {	// named children
					if (!tmp[n.name])
						tmp[n.name] = [];
					tmp[n.name][tmp[n.name].length] = n;
				}
				if (n.id)		// child with id
					tmp[n.id] = n
			}
		}
		return tmp;
	});

	HTMLElement.prototype.contains = function (oEl) {
		if (oEl == this) return true;
		if (oEl == null) return false;
		return this.contains(oEl.parentNode);
	};
}

function emulateCurrentStyle() {
	HTMLElement.prototype.__defineGetter__("currentStyle", function () {
		return this.ownerDocument.defaultView.getComputedStyle(this, null);
		/*
		var cs = {};
		var el = this;
		for (var i = 0; i < properties.length; i++) {
			cs.__defineGetter__(properties[i], encapsulateObjects(el, properties[i]));
		}
		return cs;
		*/
	});
}

function emulateHTMLModel() {

	// This function is used to generate a html string for the text properties/methods
	// It replaces '\n' with "<BR"> as well as fixes consecutive white spaces
	// It also repalaces some special characters
	function convertTextToHTML(s) {
		s = s.replace(/\&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/\n/g, "<BR>");
		while (/\s\s/.test(s))
			s = s.replace(/\s\s/, "&nbsp; ");
		return s.replace(/\s/g, " ");
	}

	HTMLElement.prototype.insertAdjacentHTML = function (sWhere, sHTML) {
		var df;	// : DocumentFragment
		var r = this.ownerDocument.createRange();
		sWhere=sWhere.toLowerCase();
		switch (String(sWhere).toLowerCase()) {
			case "beforebegin":
				r.setStartBefore(this);
				df = r.createContextualFragment(sHTML);
				this.parentNode.insertBefore(df, this);
				break;

			case "afterbegin":
				r.selectNodeContents(this);
				r.collapse(true);
				df = r.createContextualFragment(sHTML);
				this.insertBefore(df, this.firstChild);
				break;

			case "beforeend":
				r.selectNodeContents(this);
				r.collapse(false);
				df = r.createContextualFragment(sHTML);
				this.appendChild(df);
				break;

			case "afterend":
				r.setStartAfter(this);
				df = r.createContextualFragment(sHTML);
				this.parentNode.insertBefore(df, this.nextSibling);
				break;
		}
	};

	HTMLElement.prototype.__defineSetter__("outerHTML", function (sHTML) {
	   var r = this.ownerDocument.createRange();
	   r.setStartBefore(this);
	   var df = r.createContextualFragment(sHTML);
	   this.parentNode.replaceChild(df, this);

	   return sHTML;
	});

	HTMLElement.prototype.__defineGetter__("canHaveChildren", function () {
		switch (this.tagName) {
			case "AREA":
			case "BASE":
			case "BASEFONT":
			case "COL":
			case "FRAME":
			case "HR":
			case "IMG":
			case "BR":
			case "INPUT":
			case "ISINDEX":
			case "LINK":
			case "META":
			case "PARAM":
				return false;
		}
		return true;
	});

	HTMLElement.prototype.__defineGetter__("outerHTML", function () {
		var attr, attrs = this.attributes;
		var str = "<" + this.tagName;
		for (var i = 0; i < attrs.length; i++) {
			attr = attrs[i];
			if (attr.specified)
				str += " " + attr.name + '="' + attr.value + '"';
		}
		if (!this.canHaveChildren)
			return str + ">";

		return str + ">" + this.innerHTML + "</" + this.tagName + ">";
	});


	HTMLElement.prototype.__defineSetter__("innerText", function (sText) {
		this.innerHTML = convertTextToHTML(sText);
		return sText;
	});

	var tmpGet;
	HTMLElement.prototype.__defineGetter__("innerText", tmpGet = function () {
		var r = this.ownerDocument.createRange();
		r.selectNodeContents(this);
		return r.toString();
	});

	HTMLElement.prototype.__defineSetter__("outerText", function (sText) {
		this.outerHTML = convertTextToHTML(sText);
		return sText;
	});
	HTMLElement.prototype.__defineGetter__("outerText", tmpGet);

	HTMLElement.prototype.insertAdjacentText = function (sWhere, sText) {
		this.insertAdjacentHTML(sWhere, convertTextToHTML(sText));
	};
}

document.getElementsByClassName =function (searchClass,node,tag) {
	var classElements = new Array();
	if ( node == null ){node = document;}
	if ( tag == null ){tag = '*';}
	var els = node.getElementsByTagName(tag);
	var elsLen = els.length;
	var pattern = new RegExp("(^|\\s)"+searchClass+"(\\s|$)");
	for (i = 0, j = 0; i < elsLen; i++) {
		if ( pattern.test(els[i].className) ) {
			classElements[j] = els[i];
			j++;
		}
	}
	return classElements;
};

String.prototype.leftTrim = function () {
    return (this.replace(/^\s+/,""));
  };
  String.prototype.rightTrim = function () {
    return (this.replace(/\s+$/,""));
  };
//kombiniert "leftTrim" und "rightTrim";
  String.prototype.Trim = function () {
    return (this.replace(/\s+$/,"").replace(/^\s+/,""));
  };
//dampft leerzeichen(-sequenzen) innerhalb einer zeichenkette auf ein einzelnes "space" ein;
  String.prototype.superTrim = function () {
    return(this.replace(/\s+/g," ").replace(/\s+$/,"").replace(/^\s+/,""));
  };

//zugabe: entfernt alle leerzeichen aus einer zeichenkette;
  String.prototype.removeWhiteSpaces = function () {
    return (this.replace(/\s+/g,""));
  };



document.getElementsLikeId = function(id, node,tag) {	
	var children = new Array();
	if ( node == null ){node = document;}
	if ( tag == null ){tag = '*';}
	var els = node.getElementsByTagName(tag);
	var elsLen = els.length;
	//alert(elsLen);
	for (i = 0, j = 0; i < elsLen; i++) {

		if (els[i].getAttribute('id') && els[i].getAttribute('id').match(id)) {			
			children[j]=els[i];
			//alert(els[i].getAttribute('id'));
			j++;		
		}	
	}	
	return children;
}

document.getElementsLikeId2 = function(id, node,tag) {	
	var children = new Array();
	if ( node == null ){node = document;}
	if ( tag == null ){tag = '*';}
	var els = node.getElementsByTagName(tag);
	var elsLen = els.length;
	for (i = 0, j = 0; i < elsLen; i++) {
        if (els[i].getAttribute('id') && els[i].getAttribute('id').indexOf(id)==0) {			
			children[j]=els[i];
			j++;		
		}	
	}	
	return children;
}


function collection() {
	var collection = {};
	var order = [];

	this.add = function(property, value) {
		if (!this.exists(property)) {
			collection[property] = value;
			order.push(property);
		}
	}
	this.remove = function(property) {
		collection[property] = null;
		var ii = order.length;
		while (ii-- > 0) {
			if (order[ii] == property) {
				order[ii] = null;
				break;
			}
		}
	}
	this.toString = function() {
		var output = [];
		for (var ii = 0; ii < order.length; ++ii) {
			if (order[ii] != null) {
				output.push(collection[order[ii]]);
			}
		}
		return output;
	}
	this.getValue = function(key) {
		var output = [];
		for (var ii = 0; ii < order.length; ++ii) {
			if (order[ii] == key) {
				output.push(collection[order[ii]]);
			}
		}
		return output;
	}
	this.getKeys = function() {
		var keys = [];
		for (var ii = 0; ii < order.length; ++ii) {
			if (order[ii] != null) {
				keys.push(order[ii]);
			}
		}
		return keys;
	}
	this.update = function(property, value) {
		if (value != null) {
			collection[property] = value;
		}
		var ii = order.length;
		while (ii-- > 0) {
			if (order[ii] == property) {
				order[ii] = null;
				order.push(property);
				break;
			}
		}
	}
	this.exists = function(property) {
		return collection[property] != null;
	}
	}

var m2ws_dragobjekt = null;

// Position, an der das Objekt angeklickt wurde.
var m2ws_dragx = 0;
var m2ws_dragy = 0;

// Mausposition
var m2ws_posx = 0;
var m2ws_posy = 0;

function m2ws_draginit_stop(){
	document.onmousemove=null;
	document.onmouseup = null;
}


function m2ws_draginit() {
 // Initialisierung der ?berwachung der Events
  document.onmousemove = m2ws_drag;
  document.onmouseup = m2ws_dragstop;
}

function mtpw_dragstart(element) {
	   //Wird aufgerufen, wenn ein Objekt bewegt werden soll.
	  m2ws_dragobjekt = element;
	  if(m2ws_dragobjekt){
		  m2ws_dragx = m2ws_posx - m2ws_dragobjekt.offsetLeft;
		  m2ws_dragy = m2ws_posy - m2ws_dragobjekt.offsetTop;
	  }
	}


function m2ws_dragstart(element) {
   //Wird aufgerufen, wenn ein Objekt bewegt werden soll.
  m2ws_dragobjekt = document.getElementById(m2ws_LayerName);
  if(m2ws_dragobjekt){
	  m2ws_dragx = m2ws_posx - m2ws_dragobjekt.offsetLeft;
	  m2ws_dragy = m2ws_posy - m2ws_dragobjekt.offsetTop;
  }
}


function m2ws_dragstop() {
  //Wird aufgerufen, wenn ein Objekt nicht mehr bewegt werden soll.
  m2ws_dragobjekt=null;
  //document.getElementById(m2ws_LayerName).click;
}


function m2ws_drag(ereignis) {
  //Wird aufgerufen, wenn die Maus bewegt wird und bewegt bei Bedarf das Objekt.

  m2ws_posx = document.all ? window.event.clientX : ereignis.pageX;
  m2ws_posy = document.all ? window.event.clientY : ereignis.pageY;
  if(m2ws_dragobjekt != null) {

    m2ws_dragobjekt.style.left = (m2ws_posx - m2ws_dragx) + "px";
    m2ws_dragobjekt.style.top = (m2ws_posy - m2ws_dragy) + "px";
  }
}

function mtpw_insertAfter( referenceNode, newNode ){    referenceNode.parentNode.insertBefore( newNode, referenceNode.nextSibling );}

function mtpw_insertCloserAfter(referenceNodeName){
	var referenceNode=document.getElementById(referenceNodeName);
	var div=document.createElement("div");
	div.style.clear='left';
	referenceNode.parentNode.insertBefore( div, referenceNode.nextSibling );
}

function setSelectedIndex(s, v) {    
	for ( var i = 0; i < s.options.length; i++ ) {        
		if ( s.options[i].value == v ) {            
			s.options[i].selected = true;            
			return;        
		}    
	}
}

function unserialize (data) {
    // http://kevin.vanzonneveld.net
    // +     original by: Arpad Ray (mailto:arpad@php.net)
    // +     improved by: Pedro Tainha (http://www.pedrotainha.com)
    // +     bugfixed by: dptr1988
    // +      revised by: d3x
    // +     improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +        input by: Brett Zamir (http://brett-zamir.me)
    // +     improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +     improved by: Chris
    // +     improved by: James
    // +        input by: Martin (http://www.erlenwiese.de/)
    // +     bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +     improved by: Le Torbi
    // +     input by: kilops
    // +     bugfixed by: Brett Zamir (http://brett-zamir.me)
    // -      depends on: utf8_decode
    // %            note: We feel the main purpose of this function should be to ease the transport of data between php & js
    // %            note: Aiming for PHP-compatibility, we have to translate objects to arrays
    // *       example 1: unserialize('a:3:{i:0;s:5:"Kevin";i:1;s:3:"van";i:2;s:9:"Zonneveld";}');
    // *       returns 1: ['Kevin', 'van', 'Zonneveld']
    // *       example 2: unserialize('a:3:{s:9:"firstName";s:5:"Kevin";s:7:"midName";s:3:"van";s:7:"surName";s:9:"Zonneveld";}');
    // *       returns 2: {firstName: 'Kevin', midName: 'van', surName: 'Zonneveld'}

    var that = this;
    var utf8Overhead = function(chr) {
        // http://phpjs.org/functions/unserialize:571#comment_95906
        var code = chr.charCodeAt(0);
        if (code < 0x0080) {
            return 0;
        }
        if (code < 0x0800) {
             return 1;
        }
        return 2;
    };


    var error = function (type, msg, filename, line){throw new that.window[type](msg, filename, line);};
    var read_until = function (data, offset, stopchr){
        var buf = [];
        var chr = data.slice(offset, offset + 1);
        var i = 2;
        while (chr != stopchr) {
            if ((i+offset) > data.length) {
                error('Error', 'Invalid');
            }
            buf.push(chr);
            chr = data.slice(offset + (i - 1),offset + i);
            i += 1;
        }
        return [buf.length, buf.join('')];
    };
    var read_chrs = function (data, offset, length){
        var buf;

        buf = [];
        for (var i = 0;i < length;i++){
            var chr = data.slice(offset + (i - 1),offset + i);
            buf.push(chr);
            length -= utf8Overhead(chr); 
        }
        return [buf.length, buf.join('')];
    };
    var _unserialize = function (data, offset){
        var readdata;
        var readData;
        var chrs = 0;
        var ccount;
        var stringlength;
        var keyandchrs;
        var keys;

        if (!offset) {offset = 0;}
        var dtype = (data.slice(offset, offset + 1)).toLowerCase();

        var dataoffset = offset + 2;
        var typeconvert = function(x) {return x;};

        switch (dtype){
            case 'i':
                typeconvert = function (x) {return parseInt(x, 10);};
                readData = read_until(data, dataoffset, ';');
                chrs = readData[0];
                readdata = readData[1];
                dataoffset += chrs + 1;
            break;
            case 'b':
                typeconvert = function (x) {return parseInt(x, 10) !== 0;};
                readData = read_until(data, dataoffset, ';');
                chrs = readData[0];
                readdata = readData[1];
                dataoffset += chrs + 1;
            break;
            case 'd':
                typeconvert = function (x) {return parseFloat(x);};
                readData = read_until(data, dataoffset, ';');
                chrs = readData[0];
                readdata = readData[1];
                dataoffset += chrs + 1;
            break;
            case 'n':
                readdata = null;
            break;
            case 's':
                ccount = read_until(data, dataoffset, ':');
                chrs = ccount[0];
                stringlength = ccount[1];
                dataoffset += chrs + 2;

                readData = read_chrs(data, dataoffset+1, parseInt(stringlength, 10));
                chrs = readData[0];
                readdata = readData[1];
                dataoffset += chrs + 2;
                if (chrs != parseInt(stringlength, 10) && chrs != readdata.length){
                    error('SyntaxError', 'String length mismatch');
                }

                // Length was calculated on an utf-8 encoded string
                // so wait with decoding
                //readdata = that.utf8_decode(readdata);
            break;
            case 'a':
                readdata = {};

                keyandchrs = read_until(data, dataoffset, ':');
                chrs = keyandchrs[0];
                keys = keyandchrs[1];
                dataoffset += chrs + 2;

                for (var i = 0; i < parseInt(keys, 10); i++){
                    var kprops = _unserialize(data, dataoffset);
                    var kchrs = kprops[1];
                    var key = kprops[2];
                    dataoffset += kchrs;

                    var vprops = _unserialize(data, dataoffset);
                    var vchrs = vprops[1];
                    var value = vprops[2];
                    dataoffset += vchrs;

                    readdata[key] = value;
                }

                dataoffset += 1;
            break;
            default:
                error('SyntaxError', 'Unknown / Unhandled data type(s): ' + dtype);
            break;
        }
        return [dtype, dataoffset - offset, typeconvert(readdata)];
    };
    
    return _unserialize((data+''), 0)[2];
}




