 //GETMOBILE JS Modules

var global = new Object();

global.doc = document;

	// returns a DOM element with the attributes, that are given in
	// a simple array, where the attribute is designated by a division
	// with 1 mod 0 and the value by 2 mod 0. You can set attributes to
	// a existing DOM node or create a new one by passing a string with
	// the accordant element type
	
	global.setElement = function setElement(domElement, attributeList) {
	   if (typeof(domElement)=='object'){
	   		var domElement = domElement;
	   } else if (typeof(domElement)=='string') {
	   		var domElement = document.createElement(domElement);
	   }
			for(var i=0; i<attributeList.length-1; i++) {
				domElement.setAttribute(attributeList[i], attributeList[i+1]);
				i++;
			}
			return domElement;
	}
	
	// substitutes a links function
	
	global.changeURL = function changeURL(select) {
		location.href = select.options[select.options.selectedIndex].value;
	}
	
	// getElementsByClass
	
	// two functions that changes layers of the same class one to another 
	// either or show/hide layers by manipulating concurrently the JS parameters

	
	global.showLayer = function showLayer(articleId, layersToChange) {
	    var layers = global.doc.getElementsByTagName("div");
	    for (var i=0;i<layers.length; i++) {
			if (layers[i].getAttribute('class')==layersToChange) {
				if (layers[i].getAttribute('id')==articleId) {
					layers[i].style.display = "block"; 
				} else {
					layers[i].style.display = "none";
				}
			}
	    }
	}
		      
	global.showMore = function showMore(articleId, show) {
		if(show=='show') {
			var display = 'display:block'; 
			var show = 'hide'; }
		else {
			var display = 'display:none';
			var show = 'show'; }
		var link = '';
		if (global.doc.getElementById('link_'+articleId)=='undefined') {
			var links = global.getElementsByTagName("a");
			for (var i=0; i<links.length; i++) {
				if(links[i].getAttribute("href")=='#'+articleId) {
					link = links[i];
				}
			}
		} else {
			link = global.doc.getElementById('link_'+articleId);
		}
		global.doc.getElementById(articleId).setAttribute('style', display);
		global.doc.getElementById('link_'+articleId).setAttribute('href',"javascript:global.showMore('"+articleId+"','"+show+"')") ;         
	}

	// recieves values of a form, runs through all values, looks for whether they are set
	// if not a message will returned, the form will be submitted otherwise while
	// all obligatory values are set. accordant functions are parseInserts(), 
	// setErrorMessages(), missingValuesMessages() and deletingErrorMessage()
	
	global.submitForm = function submitForm() {

		var inputFields = global.doc.getElementById("formFiles").getElementsByTagName("input");
		var allValuesSet = true;
		var isObligatory = '';
		var errorField = '';
		var givenRadioButtons = new Object();
		var givenButton = false;
		var inputValues = global.missingValuesMessages();
    
		for (var i=0; i<inputFields.length; i++) {  
			var fieldName = inputFields[i].name;  	
			errorField = "error_"+fieldName;
			isObligatory = /.*obligatory.*/.test(inputFields[i].getAttribute("class"));
			// if fields are not empty but contain error messages
			if(inputFields[i].value == inputValues[fieldName]) {
				allValuesSet = false;
				global.setErrorMessage(inputFields[i], inputValues[fieldName]);
			}
			if (inputFields[i].type == "text" || inputFields[i].type == "password") {
				if(global.parseInserts(inputFields[i].name, inputFields[i], inputValues[fieldName], isObligatory)==true){
					allValuesSet=allValuesSet;
				} else { allValuesSet = false; 
				}
			}
			// next two ifs contain sloppy ad hoc code
			if(global.doc.nl_sub.birthday!=undefined) {
				if (global.doc.nl_sub.birthday.selectedIndex == 0 && document.nl_sub.birthmonth.selectedIndex == 0 && document.nl_sub.birthyear.selectedIndex == 0) {
					var birthmonth = global.doc.getElementsByName('birthmonth')[0];
					birthmonth.setAttribute('style','background:#ff8c8c');
					birthmonth.onclick = function() {this.style.background="#ffffff"; }
					global.doc.getElementsByName('birthyear')[0].setAttribute('style','background:#ff8c8c');
					global.doc.getElementsByName('birthyear')[0].onclick = function() {this.style.background="#ffffff"; }
					global.doc.getElementsByName('birthday')[0].setAttribute('style','background:#ff8c8c');
					global.doc.getElementsByName('birthday')[0].onclick = function() {this.style.background="#ffffff"; }
					allValuesSet = false;
				} else {
					global.doc.getElementsByName('birthmonth')[0].setAttribute('style','background:#ffffff');
					global.doc.getElementsByName('birthday')[0].setAttribute('style','background:#ffffff');
					global.doc.getElementsByName('birthyear')[0].setAttribute('style','background:#ffffff');
				}		
			}
			if(global.doc.getElementsByName('noCard')[0]!=undefined) {		
				if(global.doc.getElementsByName('visa')[0].checked==true ||
					global.doc.getElementsByName('amex')[0].checked==true ||
					global.doc.getElementsByName('mastercard')[0].checked==true ||
					global.doc.getElementsByName('barclay')[0].checked==true) {
					global.doc.getElementsByName('noCard')[0].checked=false	
				}
			}			
			// builds an array of names of radio buttons that is finally....   	 
			if (inputFields[i].type == "radio" && isObligatory) { 
    			if (givenRadioButtons[fieldName]==undefined) {
    				if (inputFields[i].checked == false) {
    					givenRadioButtons[fieldName] = false;
    				} else {
    					givenRadioButtons[fieldName] = true;
    				}
    			} else {
					if (inputFields[i].checked == false && givenRadioButtons[fieldName] == false) {
    					givenRadioButtons[fieldName] = false;
    				} else if (inputFields[i].checked == true && givenRadioButtons[fieldName] == false) {
    					givenRadioButtons[fieldName] = true;
    				}		
    			}   
    		}   	
		}
		// ....read here
		for (var booleanRadio in givenRadioButtons ){
			if(givenRadioButtons[booleanRadio]==false) {
				global.doc.getElementById("error_"+booleanRadio).innerHTML = inputValues[booleanRadio];
				allValuesSet = false;
			}
		}
		// looking for all values are set and submits
		if(allValuesSet) {
			global.doc.nl_sub.submit(); 
		}
	}
  
	global.parseInserts = function parseInserts(fieldName, DOMNode, message, isObligatory) {
		var allValuesSet = true;
      	var parseValues = new Object ();
      	parseValues["email"] = new Array("Bitte geben Sie eine gültige Adresse ein", /\w+\@\w+\.\w+/);
      	parseValues["plz"] = new Array("Bitte geben Sie eine gültige PLZ ein", /^\d{5}$/);
      	parseValues["telefon"] = new Array("Bitte geben Sie eine gültige Telefonnummer ein",/^\+?(0){1}[\d\s\/\-]{5,20}$/);
      	parseValues["mobil"] = new Array("Bitte geben Sie eine gültige Mobilnummer ein", /^(01){1}[\d\s/\-]{5,20}$/);
      	parseValues["vorname"] = new Array("Bitte geben Sie einen gültigen Vornamen ein", /^\D{0,50}$/);
      	parseValues["nachname"] = new Array("Bitte geben Sie einen gültigen Nachnamen ein", /^\D{0,50}$/);
      	parseValues["ort"] = new Array("Bitte geben Sie einen gültigen Ortsnamen ein", /^\D{0,50}$/);	    
		for (var i in parseValues) {
	   		if (!(DOMNode.value=='') && fieldName==i) {
	   			if(!(parseValues[fieldName][1].test(DOMNode.value))) {	   			
					allValuesSet = false;
					global.setErrorMessage(DOMNode, parseValues[fieldName][0]);
	   			} 	
   			}
		}   	
		if (/[%!¤$\\]/g.test(DOMNode.value)) {   		
			allValuesSet = false;
			global.setErrorMessage(DOMNode, 'Bitte vermeiden Sie Sonderzeichen');
   		}
		if(DOMNode.value=='' && isObligatory) {	
			allValuesSet = false;
			global.setErrorMessage(DOMNode, message);
   		}		
   		return allValuesSet;   	
	}
   
	global.setErrorMessage = function setErrorMessage(DOMNode, message) {
		DOMNode.value = message;
		DOMNode.style.color = "#ff0000";
		DOMNode.onclick = function() {this.value=''; this.style.color="#000000"; this.onclick="" }
	}
	
	global.deletingErrorMessage = function deletingErrorMessage(errorText) {
		document.getElementById(errorText).innerHTML = "";
	}
	  
	global.missingValuesMessages = function missingValuesMessages() { 
	  	var inputValues = new Object ();      
	  	inputValues["vorname"] = "Bitte geben Sie Ihren Vornamen ein";
	    inputValues["nachname"] = "Bitte geben Sie Ihren Nachnamen ein";
	    inputValues["strasse"] = "Bitte geben Sie Ihre Strasse und Hausnr. ein";
	    inputValues["ort"] = "Bitte geben Sie Ihren Wohnort ein";
	    inputValues["email"] = "Bitte geben Sie Ihre Email Adresse ein";
	    inputValues["plz"] = "Bitte geben Sie Ihre Postleitzahl ein";
	    inputValues["telefon"] = "Bitte geben Sie Ihre Telefonnummer ein";
	    inputValues["mobil"] = "Bitte geben Sie Ihre Mobilnummer ein";
	    inputValues["passwort"] = "Bitte geben Sie Ihr Passwort ein";
	    inputValues["adresse"] = "Bitte geben Sie den Ort Ihrer Meldeadresse ein";
	    inputValues["meldeadresse"] = "Bitte geben Sie den Ort Ihrer Meldeadresse ein";
	    inputValues["firmenname"] = "Bitte geben Sie einen Firmennamen an";
	    inputValues["anrede"] = "Bitte geben Sie eine Anrede an";
	    // values for advanzia */
		inputValues["einkommen"] = "Bitte geben Sie Ihr j&auml;hrliches Einkommen ein";
	    inputValues["mastercard"] = "Bitte t&auml;tigen Sie eine Auswahl";
	    inputValues["visa"] = "Bitte t&auml;tigen Sie eine Auswahl";
	    inputValues["barclay"] = "Bitte t&auml;tigen Sie eine Auswahl";
	    inputValues["amex"] = "Bitte t&auml;tigen Sie eine Auswahl";
	    inputValues["creditCard"] = "Bitte t&auml;tigen Sie eine Auswahl";
	    inputValues["zeichendatum"] = "Geben Sie Datum...";
	    inputValues["zeichenort"] = "...und Ort ein";
	    inputValues["firmenname"] = "Bitte geben Sie einen Firmennamen an";
	    inputValues["rechtsform"] = "Bitte geben Sie eine Rechtsform an";
	    inputValues["ansprechpartner"] = "Bitte nennen Sie einen Ansprechpartner";  
	    return inputValues;  
  }

	// FUNCTIONS FOR SINGULAR ISSUES
	      
	// generates layer with affiliate stuff for partnerprogramme
	function showAffiliateStuff(affiliateId) {
		var affiliateLayer = $("#partnerprogramm_affiliateBanner");  	
		var newAffiliateWrapper = global.setElement('div', new Array ("id", "affiliateWrapper")); 	  		
		var cpStopper = global.setElement("div", new Array("style", "position:absolute;margin-top:0px;width:740px;height:770px;z-index:2"));
		affiliateLayer.append(cpStopper);
		imageSources = new Array("120x600", "160x600", "300x250", "234x60", "468x60", "728x90");
		for (var i=0; i<imageSources.length; i++) {
			affiliateImage = global.setElement('img', new Array(
  										"style", "margin-left:5px", 
  										"src","http://www.getmobile.de/img/banner/gp/getpartner_"+affiliateId+"_"+imageSources[i]+".jpg"));
			newAffiliateWrapper.appendChild(affiliateImage);		  				
		}
		$("#affiliateWrapper").replaceWith(newAffiliateWrapper);
	}
  
	// Freunde werben Dingsbums
	// initialised by sendRequest()
	function setDOMNodes(xhttp, funcArgs) {
		var DOMNode = xhttp.getElementsByTagName('div');
		document.getElementById('widgetFrame').appendChild(DOMNode);
	}

	// TESTBERICHTE //
	// initialised by sendRequest()
	global.parseTestdocumentationList = function parseTestdocumentationList(xhttp, funcArgs) {
		var articleNumber = funcArgs[0];
		// specifies the mode of return data if the function is
		// initialised by sendRequest, for jquery use next line
		// lines = xhttp.responseText.split("\n");
		lines = xhttp.split("\n");
		for (var i=0; i<lines.length; i++) {
			matchingArticle = (lines[i]).match(/(.*)?\|(.*)\|(.*)/g);
			if(RegExp.$1==articleNumber) {
				htmlCode = RegExp.$3;
				jScript = htmlCode.match(/(<script type\=\"text\/javascript\">.*?<\/script>)/g);
				iFrame = htmlCode.match(/(<div id\=\"tbReviewList\">.*?<\/iframe><\/div>)/g);
				iLink = htmlCode.match(/(Zusammengestellt von .*\=\"_blank\">)/g);
				global.parseIFrame(jScript, iLink);
			}
		}     
	}
   
	global.parseIFrame = function parseIFrame(jScript, iLink) {
		var jScriptString = jScript.toString();
		var jLinkString = iLink.toString();
		matchingProduct = jScriptString.match(/.*tb_p\=(.*)\&tb_partner_id\=(.*)\" \+ \"\&tb_time\=(.*)\" \+ \"\&tb_width\=\"(.*) \+/ig);
		var tb_p = RegExp.$1;
		var tb_partner = RegExp.$2;
		var tb_time = RegExp.$3;
		matchingLink = jLinkString.match(/Zusammengestellt von.*p_id\=(.*)&amp\;local\=de_DE\" title\=\"(.*)\" target/ig);
		var linkTestId = RegExp.$1;
		var linkTestDescription = RegExp.$2;
		global.helperTestberichteLink(tb_p,tb_partner,tb_time, linkTestId, linkTestDescription); 
  }
   
	global.helperTestberichteLink = function helperTestberichteLink(tb_p, tb_partner, tb_time, linkTestId, linkTestDescription ) {
    	var doc = document;
    	url = "http://www.testberichte.de/d/partner/slideshow_v1.html?tb_p="
  			+tb_p+"&tb_partner_id="+tb_partner+"&tb_time=0&tb_width=197";
  
    	var tbBadges = global.setElement("div", new Array('id', 'tbBadges'));
    	var iFrame = global.setElement('iFrame', new Array (
    		'width', '205', 'height', '100', 'name', 'tb_badges', 'frameBorder', '0', 'scrolling', 'no', 'src', url));
		var testberichteLogo = global.setElement( doc.getElementById("testberichte_logo"), new Array(
			'style', 'display:block', 
			'href', 'http://www.clickwerk.de/link.php?p_id='+linkTestId+'&amp;local=de_DE',
			'target', '_blank', 'title', linkTestDescription));					
    	var testberichteLogoWrapper = global.setElement(doc.getElementById("testberichte"), new Array(
    		'style', 'width:200px; heigth:90px; margin:20px 0 0 40px;'));
    		
		tbBadges.appendChild(iFrame);
    	testberichteLogo.appendChild(tbBadges);

    	doc.getElementById("top_h1").style.marginTop = "15px";
	}
  
	function finderCompletionList() {
  
		var productInfo = "";
		var productInfos = "";
    	var productName ="";
    	var responseLines="";
    	var xhttp = createXMLHttpRequest();    
    	xhttp.open("GET","/finder_completion.csv",false);
   		xhttp.setRequestHeader("Content-Type", "text/html");
        xhttp.send(null);   
  		responseLines = xhttp.responseText.split("\n");
		for (var i=1; i<responseLines.length; i++) {
			productInfos = responseLines[i].split(";"); 		
			productInfo = productInfo+productInfos[2]+",";
		}	
		return productInfo;
	}
  
	global.sendLTE = function sendLTE() {

      $.ajax({ 
          type: 'POST', 
          url: 'http://www.getmobile.de/__php/lteList.php',
          data: {  
            vorname:$("#vorname").val(),
            nachname:$("#nachname").val(),
            email:$("#email").val(),
            plz:$("#plz").val()
          },

         contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
         cache: false, 
 		 async: true,
		 success: function(data) {
		 
		    $("#Anmeldung").hide();
		    $("#dataRecievedMessage").text(data);
		    $("#dataRecieved").show();
		 }

    });
}

  function setRecommendation() { 
  $.ajax({
  url: '/__php/ff_recommendation_get.php',
  data: 'articleid={ART_NR1}',
  type: 'GET',
  async: false,
  success: function(data) {

  $(data).find('record').each(function(){
  	$(this).find('field').each(function(){
  		if($(this).attr('name')=='BildURL'){
  			picurl = $(this).html();
  		}
		if($(this).attr('name')=='Name'){
  			artName = $(this).html();
  		}
		if($(this).attr('name')=='Kategorie'){
			if($(this).html()=='..Mobilfunkvertrag..') {
				picWidth = 92;
				picHeigth = 37;
			} else {
				picWidth = 55;
				picHeigth = 90;
			}
  		}
		if($(this).attr('name')=='Deeplink'){
		  var regExpr = /(\<\!\-\-\[CDATA\[)(.*)(\]\]\-\->)/;
		  var dplink = $(this).html();
  		  regExpr.exec(dplink);
  		  artLink = RegExp.$2;
  		}
  	})
		document.write('<a href="'+artLink+'" class="o33" title="Android-Handys">');
		document.write('<img src="'+picurl+'" width="'+picWidth+'" height="'+picHeigth+'" border="0" alt="Android-Handys" class="b1" style="float:left;margin-right:5px;"/>');
		document.write('<h2>'+artName+'</h2></a>');
		document.write('<div class="clear"></div><br>');
})

  }
});

}

	global.checkCommentsData = function checkCommentsData(art_nr, title, content, rating, censorship, author, article_name, manufacturer) {
		if (document.getElementById('noRating').innerHTML != 'Vielleicht wollen Sie noch eine Bewertung abgeben?' && parseInt(document.getElementById('rating').value)===0) {
			document.getElementById('noRating').innerHTML = 'Vielleicht wollen Sie noch eine Bewertung abgeben?';
		} else {
		global.submitComment(art_nr, title, content, rating, censorship, author, article_name, manufacturer);
		global.showComments(art_nr, article_name);
		global.setRating();
		global.showLayer('comment_wrapper','comments');
		document.getElementById('latency_notion').innerHTML = 'Ihre Bewertung wird noch redaktionell &uuml;berpr&uuml;ft und wir so bald als m&ouml;glich erscheinen';
		}
	
	}

	global.submitComment = function submitComment(art_nr, title, content, rating, censorship, author, article_name, manufacturer) {
	if(rating=='') {
		rating = 0
	}
		$.post('/__php/CommentsHandys.php', {
			submit:true, article:art_nr, 
			content:content, 
			rating:rating, 
			author:author, 
			create:true, 
			article_name:article_name, 
			manufacturer:manufacturer},
 			function(data) {
				global.doc.getElementById("comment_wrapper").innerHTML = data;
 			}, "xml"
		);
	}
	
	global.showComments = function showComments(art_nr, article_name) {
		$.ajax({
		
		  url: '/__php/CommentsHandys.php',
		  type: 'GET',
		  async: false,
		  data: 'search=true&article='+art_nr,
		  success: function(data, art_nr, article_name) {
		  	  var previewNotion = '';
		  	  var bestRating = 0;
			  global.doc.getElementById("comment_wrapper").innerHTML = data;
			  global.setRating();
			  var notions_wrapper = global.doc.getElementById("notions_items");
			  var notions = global.doc.getElementsByName("comment_item");
			  /* var single_notions_wrapper = global.doc.getElementById("notions_link"); */
			  for (var i=0; i<notions.length; i++) {	  	
			  	var rating = parseInt(notions[i].firstChild.getAttribute("value"));
			  	if(rating>bestRating) {
			  		bestRating = rating;
			  		previewNotion = notions[i].cloneNode(true);
			  	}
			  }
			  
			  if(previewNotion == '') {
			  	var no_notions = global.doc.createElement("div");
			  	no_notions.setAttribute("id", "no_comments");
			  	no_notions.innerHTML = '<font style="color:#999999;font-size:12px">Zu diesem Produkt wurden noch keine Bewertungen abgegeben</font><br><a href="#notions">Schreiben Sie eine erste Bewertung</a>';
			  	/* single_notions_wrapper.appendChild(no_notions); */
			  } else {
			  	  if(global.doc.getElementById("no_comments")) {
			  	  	global.doc.getElementById("no_comments").setAttribute("style", "display:none");
			  	  }
			  }
		  
			  var seperator = global.doc.createElement("hr");
			  seperator.setAttribute("class", "hr");
			  seperator.setAttribute("noshade", "noshade");
			  seperator.setAttribute("style", "display:block;margin-bottom:-3px");
  
		  }
		});	
	}
	
	global.rateIt = function rateIt(rating) {
		
			var asterix = global.doc.getElementsByName("ratings");
			for(var i=0; i<asterix.length; i++) {
				if(i<rating) {
					asterix[i].src = '/__img/rating_rated.png';
				} else {
					asterix[i].src = '/__img/rating_unrated.png';
				}			
			}
			global.doc.getElementById("rating").value = rating;
	}
	
	
	global.setRating = function setRating() {

			var ratings = global.doc.getElementsByName("rating");
			for (var i=0; i<ratings.length; i++) {
				if(ratings[i].getAttribute("set")=='false') {
					var ratings_value = ratings[i].getAttribute("value");
					for(var j=0; j<5; j++) {
					if(j<ratings_value) {
						var new_img = global.doc.createElement("img");
						new_img.setAttribute("src", "/__img/rating_rated.png");
						ratings[i].appendChild(new_img);
					} else {
						var new_img = global.doc.createElement("img");
						new_img.setAttribute("src", "/__img/rating_unrated.png");
						ratings[i].appendChild(new_img);
					}
		
					}
					ratings[i].setAttribute("set", 'true');
				}
			}

	}
	
	global.averageRating = function averageRating() {
		var ratings = global.doc.getElementsByName("rating");
		var averageRating = global.doc.getElementById("averageRating");
		var ratingsLength = 0;
			if (ratings.length>1) { 
				var rating = 0;
				var halfset = false;			
				for (var i=1; i<ratings.length; i++) {
					var addrating = parseInt(ratings[i].getAttribute("value"));
					if(addrating != 0 ) {	
						rating = rating+addrating;
						ratingsLength++;
					}
				}
				
				var average = rating/ratingsLength;
				var mod = parseInt(rating%(ratingsLength));

				
				for(var j=1; j<6; j++) {
				if(j<=average) {
					var new_img = global.doc.createElement("img");
					new_img.setAttribute("src", "/__img/rating_rated.png");
					averageRating.appendChild(new_img);
				} else {
					if(rating%(ratings.length-1)!=0 && !halfset) {
						var new_img = global.doc.createElement("img");
						new_img.setAttribute("src", "/__img/rating_half.png");
						averageRating.appendChild(new_img);
						halfset = true;
					} else {
					var new_img = global.doc.createElement("img");
					new_img.setAttribute("src", "/__img/rating_unrated.png");
					averageRating.appendChild(new_img);
					}
				}
				}
		} else {
			global.doc.getElementById("ratingHint").innerHTML = "Jetzt eine erste Bewertung schreiben";
		}	
	}
  
  global.getManufacturer = function getManufacturer(manid) {
  var man = ''
  switch (manid) {
  	case "1": man = 'benq-siemens'; break;
  	case "4": man = 'motorola'; break;
  	case "5": man = 'nokia'; break;
  	case "6": man = 'panasonic'; break;    
  	case "7": man = 'blackberry'; break;
  	case "11": man = 'sagem'; break;
  	case "12": man = 'samsung'; break;  
  	case "15": man = 'lg-electronics'; break;   
  	case "17": man = 'sony-ericsson'; break; 
  	case "23": man = 'vk-mobile'; break;
    case "159": man = 'hyundai'; break;
    case "195": man = 'asus'; break;
    case "601": man = 'htc'; break;
    case "604": man = 'emporia'; break;
    case "109": man = 'garmin'; break;
    case "348": man = 'apple'; break;
    case "313": man = 'toshiba'; break;   
  }
  return man;
  }
  
  
  global.chat = new Object();
  
  global.chat.getUser = function getUser() {
  	if(doc.getElementById('session_user').innerHTML!='')  {
  		return doc.getElementById('session_user').innerHTML;
  	} else {
  		return 'no user';
  	}
  }
  
  global.chat.checkSession = function checkSession() {

	    $.ajax({
	    
		      type:    "GET",
		      async:   true,
		      url:     "/__php/ChatUser.php",
		      data:    "search=true&"+"id=",
		      success: function(data){
				global.chat.setRequest(data);
				var user = doc.getElementById('session_user').innerHTML;
			  	global.chat.checkStatus(user);
	    }
	});  	
  
  }
  
  global.chat.setChat = function setChat(user) {
		
		var doc = document;
		var chat_node = doc.getElementById('window_'+user);
		chat_node.removeChild(chat_node.firstChild);
  		chat_node.appendChild(doc.getElementById('window_'+user).firstChild);
  		
  }
  
  global.chat.setValues = function setValues(user_name, url) {

	    var action_type = '';
	    var user = '';
	    var chatline = '';
	    var talker = '';
	  	var fields = document.getElementById('form_'+user_name).childNodes;
	  	
	  	for(var i=0; i<fields.length; i++) {
	  		if(fields[i].nodeName=="INPUT") {
	  			if(fields[i].name =="submit") {
	  				action_type = 'submit';
	  			}
	  			if(fields[i].name == "user") {
	  				user_name = fields[i].getAttribute('value');
	  			}
	  			if(fields[i].name == "talker") {
	  				talker = fields[i].getAttribute('value');
	  			}
	  			if(fields[i].name == "chatline") {
	  				chatline = fields[i].value;
	  			}
	  		}
	  	}
chatline = Url.encode(chatline);
	    $.ajax({
	    
		      type:    "GET",
		      async:   true,
		      contentType: "application/x-www-form-urlencoded;charset=UTF-8",
		      url:     "/__php/"+url,
		      data:    "submit=true&"+"id="+"&user="+user_name+"&chatline="+chatline+"&session=&timestamp=&talker="+talker,
		      success: function(data){
		    /*  alert(data); */
		     var doc = document;
			  global.chat.setRequest(data);			  
			  doc.getElementById('window_'+user_name).scrollTop = document.getElementById('window_'+user_name).scrollHeight;
			  if(doc.getElementById("chat_line")) {
			  	doc.getElementById("chat_line").value ='';
			  	doc.getElementById("chat_line").focus();
			  }
			 /*  document.location.href = '#bottom'; */
	    }
	});
	
	}
	
  global.chat.setLogin = function setLogin() {

	  	var fields = document.getElementById('login_formular').childNodes;
	  	for(var i=0; i<fields.length; i++) {
	  		if(fields[i].nodeName=="INPUT") {
	  			if(fields[i].getAttribute("name")=="login") {
	  				action_type = 'login';
	  			}
	  			if(fields[i].getAttribute("name")=="user") {
	  				user = fields[i].value;
	  			}
	  			if(fields[i].getAttribute("name")=="talker") {
	  				talker = fields[i].getAttribute('value');
	  			}
	  		}
	  	}
	  	

	    $.ajax({
	   
		      type:    "GET",
		      async:   true,
		      url:     "/__php/ChatUser.php",
		      data:    "login=true&"+"id="+"&user="+user+"&session=&timestamp=",
		      success: function(data){
		      
		     /*  alert(data); */

			  global.chat.setRequest(data);
			  global.chat.checkStatus(user);
			  
			  
	    }
	});
	}
	
  global.chat.setLogout = function setLogout() {
		var doc = document;
	    $.ajax({
	    
		      type:    "GET",
		      async:   true,
		      url:     "/__php/ChatUser.php",
		      data:    "logout=true",
		      success: function(data){

			  var user = doc.getElementById('session_user').innerHTML;
			  doc.getElementById('form_'+user).setAttribute('id', 'form_');
			  doc.getElementById('window_'+user).setAttribute('id', 'window_');
			  global.chat.setRequest(data);
			  doc.getElementById('window_').innerHTML = '<div></div>';
			  global.chat.checkStatus(user);
			  global.chat.setIdentifier('');
			  
			  
	    }
	});
	}
	


  global.chat.setRequest = function setRequest(data) {

  	if($('#request_container').find('div')) { 	
		$('#request_container').find('div').remove('div');
		$('#request_container').append('<div></div>').find('div').append($(data));
	}
  }
  
  global.chat.checkStatus = function checkStatus(user) {

 	var status_message = '';

	if(document.getElementById('error_message')) {
		var status_message = document.getElementById('error_message').innerHTML;
	}
	if(document.getElementById('status')) {
		document.getElementById('status').innerHTML = status_message;
	}
	
	/* alert(document.getElementById('error_message').innerHTML); */
		
	if(status_message=='' 
				|| status_message=='Session wurde erstellt'
				|| status_message=='Session vorhanden'
				|| status_message=='no timeout') {
				global.chat.setIdentifier(user);
		global.chat.setFormular('chat');
	} else if (status_message=='Falscher Username' 
				|| status_message=='Timeout' 
				|| status_message=='Ihre Session wurde mangels Aktivität geschlossen. Bitte geben Sie erneut Ihren Nutzernamen ein'
				|| status_message=='Dieser Username ist bereits vergeben'
				|| status_message=='Sie haben sich erfolgreich abgemeldet'
				|| status_message=='Bitte geben Sie einen Nutzernamen an') {
		
		global.chat.setFormular('login');
	} 
  
  }
  
  global.chat.setIdentifier = function setIdentifier(user) {
  
  	 test = function anonymous(){setValues(user, 'ChatUser.php', user); return false;};
	 var doc = document;
		doc.getElementById('user').innerHTML = user;
		
		doc.getElementById('window_').setAttribute('id', 'window_'+user);
	    doc.getElementById('form_').setAttribute('id', 'form_'+user);
	    doc.getElementById('field_user').setAttribute('value', user);
	    doc.getElementById('field_talker').setAttribute('value', user);
	   
	    if (navigator.userAgent.indexOf("Firefox")!=-1) {
		    doc.getElementById('chat_link').setAttribute('onclick', 'javascript:global.chat.setValues(\''+user+'\',\'ChatUser.php\', \''+user+'\')');
		    doc.getElementById('form_'+user).setAttribute('onsubmit', 'javascript:global.chat.setValues(\''+user+'\',\'ChatUser.php\', \''+user+'\'); return false');
	    } else {
		    if (navigator.userAgent.indexOf("MSIE")!=-1) {
			    doc.getElementById('chat_link').setAttribute('onclick', test);
			    doc.getElementById('form_'+user).setAttribute('onsubmit', test);
			} else {
			    doc.getElementById('chat_link').setAttribute('onclick', 'javascript:global.chat.setValues(\''+user+'\',\'ChatUser.php\', \''+user+'\')');
			    doc.getElementById('form_'+user).setAttribute('onsubmit', 'javascript:global.chat.setValues(\''+user+'\',\'ChatUser.php\', \''+user+'\'); return false');			
			}    
	    }

	    doc.getElementById('form_'+user).setAttribute('action', '');

  }
	
  global.chat.setFormular = function setFormular(formular) {
  				
  	var doc = document;
  	var login_form = doc.getElementById('login_form');
  	var update_form = doc.getElementById('update_form');
  	if(update_form && login_form) {
		if(formular=='chat') {
			if(update_form.style.display == 'none') {
				update_form.style.display = 'block';
				login_form.style.display = 'none';
				doc.getElementById("chat_line").focus();
			}
		}
		if(formular=='login') {
			if(login_form.style.display == 'none') {
			
				update_form.style.display = 'none';
				login_form.style.display = 'block';
				doc.getElementById("login_line").focus();
			}
		}
  	}
  
  }
	
  global.chat.compareEntries = function compareEntries(user, url, talker) {

		$.ajax({
		    
		      type:    "GET",
		      async:   true,
		      url:     "/__php/"+url,
		      data:    "search=true&user="+user,
		      success: function(data){
		      var doc = document;
		      if(!$(data).find('#window_'+user).find('div').html() && document.getElementById('chat_'+user)) {
		      	document.getElementById('chat_'+user).style.display = 'none';
		      }
  			    /*   alert(data); */
      			      $('#window_'+user).find('div').remove('div');
      			      /* alert(user); */
      			      /* alert($(data).find('#window_'+user).find('div').html()); */
      			      $('#window_'+user).append($(data).find('#window_'+user).find('div')); 
					  
        	  }
    	});
	}
	


  global.chat.compareTimestamps = function compareTimestamps() {
		$.ajax({   
		      type:    "GET",
		      async:   true,
		      url:     "/__php/cms_db/chat_isactive_flag.xml",
		      data:    "submit=true",
		      cache: false,
		      success: function(time){
			      var timestamp = new Date().getTime();
			      var chat_presence = parseInt($(time).find('isactive').attr('timestamp'));
			      var diff = timestamp - chat_presence;
			      /* alert(timestamp+" | "+chat_presence+" | "+diff); */
			      if(timestamp-chat_presence>25000) {
			      	document.getElementById('chat_container').style.display = 'none';
			      } else {
			      	document.getElementById('chat_container').style.display = 'block';
			      }
		      }
    	});
    }
    
  global.chat.setTimestamp = function setTimestamp() {
		var timestamp = new Date().getTime();
		/* alert(timestamp); */
		$.ajax({
	      type:    "POST",
		      async:   true,
		      url:     "/__php/cms_lib/ChatIsActive.php",
		      data:    "timestamp="+timestamp,
		      success: function(data){
		      /* alert(data); */
          }
	    });
	}

var Url = {

	// public method for url encoding
	encode : function (string) {
		return escape(this._utf8_encode(string));
	},

	// public method for url decoding
	decode : function (string) {
		return this._utf8_decode(unescape(string));
	},

	// private method for UTF-8 encoding
	_utf8_encode : function (string) {
		string = string.replace(/\r\n/g,"\n");
		var utftext = "";

		for (var n = 0; n < string.length; n++) {

			var c = string.charCodeAt(n);

			if (c < 128) {
				utftext += String.fromCharCode(c);
			}
			else if((c > 127) && (c < 2048)) {
				utftext += String.fromCharCode((c >> 6) | 192);
				utftext += String.fromCharCode((c & 63) | 128);
			}
			else {
				utftext += String.fromCharCode((c >> 12) | 224);
				utftext += String.fromCharCode(((c >> 6) & 63) | 128);
				utftext += String.fromCharCode((c & 63) | 128);
			}

		}
		return utftext;
	},

	// private method for UTF-8 decoding
	_utf8_decode : function (utftext) {
		var string = "";
		var i = 0;
		var c = c1 = c2 = 0;

		while ( i < utftext.length ) {

			c = utftext.charCodeAt(i);

			if (c < 128) {
				string += String.fromCharCode(c);
				i++;
			}
			else if((c > 191) && (c < 224)) {
				c2 = utftext.charCodeAt(i+1);
				string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
				i += 2;
			}
			else {
				c2 = utftext.charCodeAt(i+1);
				c3 = utftext.charCodeAt(i+2);
				string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
				i += 3;
			}

		}

		return string;
	}

}
