// JavaScript Document
var last_chat_message_id = -1;
var chatupdatedelay=5000;
var chatinterval=null;
var message="";
var messagebody=null;
var lastinsert="";
var lastempf='support';
var empf='support';
var chatURL='http://support.chillergraphics.de/module/chat/';
var me="";
var chatfirstrun=true;

function getFMO(movieName)
{
	if (window.document[movieName])
	 {
	return window.document[movieName];}

	if (document.embeds && document.embeds[movieName])
		return document.embeds[movieName];

	else
	{
	return document.getElementById(movieName);
	}
}
function playSound()
{
	try{
	document.getElementById('soundplayer').playNotificationSound();
	}catch(e){};
	try{
	document.embeds['soundplayer'].playNotificationSound();
	}catch(e){};
}

function empfselect(e)
{
	empf=jQuery(this).attr("id");
	jQuery(".userselectbtn_aktiv").attr("class","userselectbtn");
	jQuery(this).attr("class","userselectbtn_aktiv");
	jQuery("#b_"+jQuery(this).attr("id")).attr("class","user_bubble");
	if(multiple)
	jQuery("#chatmessage_container").html(jQuery("#c_"+empf).html());
	if(document.getElementById("chatmessage_container").childNodes.length>1)
	document.getElementById("chatmessage_container").lastChild.scrollIntoView(true);
}
function livechat(e)
{
	if(jQuery(".chatcontainer").is(":hidden"))
	{
	jQuery(".chatcontainer").css("left",(e.pageX-200)+"px");
	jQuery(".chatcontainer").css("top",(e.pageY-200)+"px");
	if (navigator.appName == "Microsoft Internet Explorer") 
	{
		jQuery(".chatcontainer").css("display","block");
	showChat();
	}
	else
	{
		jQuery(".chatcontainer").show("scale", {origin:'right'}, 500,showChat);	
	}
	if(jQuery("#livechat_notification").length>0)
		jQuery("#livechat_notification").stop(true, true).css("display","none");
	}
	e.preventDefault();
}
function showChat()
{
	jQuery("#chat_close_btn").css("display","block");
	jQuery("#dionysos_chat").draggable();
 	jQuery("#dionysos_chat").resizable({ minHeight: 305,minWidth: 128 });
}
function hideChat()
{
 	jQuery("#chat_close_btn").css("display","none");
    if (navigator.appName == "Microsoft Internet Explorer") 
	{
		jQuery(".chatcontainer").css("display","none");
	}
	else
	{
		jQuery(".chatcontainer").hide("scale", {origin:'left'}, 500);
	}
	
}
function buildMessage(type,message,datum,uname,element)
{
	var tempempf=element.attr("id");
	if(lastinsert!=type||lastempf!=tempempf)
	{
		var newmessage=jQuery("<div class=\"message\"></div>");
		newmessage.append("<div class=\""+type+"_head\"><span class=\"datum\">"+datum+"</span><span class=\"username\">"+uname+"</span></div>");
		messagebody=jQuery("<div class=\"message_body\">"+message+"</div>");
		newmessage.append(messagebody);
		lastinsert=type;
		element.append(newmessage);
	}
	else
	{
		messagebody.append("<br>"+message);
	}
	if(document.getElementById("chatmessage_container").childNodes.length>1)
	document.getElementById("chatmessage_container").lastChild.scrollIntoView(true);
	lastempf=tempempf;
}
function postMessage()
{
	message+=jQuery('#chat_input').attr("value")+"/*BR*/";
	var datum=new Date();
	var minuten=datum.getMinutes();
	if(minuten<10)minuten="0"+minuten;
	var hours=datum.getHours();
	if(hours<10)hours="0"+hours;
	var element;
	if(!multiple)element=jQuery("#chatmessage_container");
	else element=jQuery("#c_"+empf);
	buildMessage("question",jQuery('#chat_input').attr("value"),hours+":"+minuten,username,element);
	if(multiple)
	jQuery("#chatmessage_container").html(jQuery("#c_"+empf).html());
	jQuery('#chat_input').attr("value","");
	if(chatinterval!=null)
	{
		window.clearInterval(chatinterval);
		chatinterval=null;
	}
	getChatUpdates();
	message="";
}
function getChatUpdates()
{
	 jQuery.post(chatURL+'getUpdates.php',{"message":Base64.encode(message),"empf":empf,"last_id":last_chat_message_id,"seite":seite,"username":username},updateChat);
}
function updateChat(data)
{
	var element;
	var temp;
	var updates=false;
	//eval("var data="+Base64.decode(data));
	eval("var data="+data);
	//weitermachen je nach Interval
	if(data.status=="success")
	{
	me=data.me;
	jQuery.each(data.messages, function(i,item)
 	{
	if(item.from!=me)
	{
		typ="response";
		updates=true;
	}
	else
		typ="question";
	
	if(!multiple)
	element=jQuery("#chatmessage_container");
	else
	{
		if(item.from!="support") temp=item.from;
		else temp=item.to;
		if(jQuery('#c_'+temp).length==0)
		{
			element=jQuery("<div id=\"c_"+temp+"\"></div>");
			jQuery("#c_multiple_container").append(element);
		}
		else
			element=jQuery("#c_"+temp);
	}
	buildMessage(typ,item.nachricht,item.time,item.avatar,element);
	});
	
	last_chat_message_id=data.last_id;
	if(data.newInterval)
	{
		if(chatinterval!=null)
		{
		window.clearInterval(chatinterval);
		chatinterval=null;
		}
		chatinterval=window.setInterval("getChatUpdates()",parseInt(data.newInterval)*1000);
	}
	if(updates&&!chatfirstrun)
	{
	playSound();
	if(jQuery(".chatcontainer").is(":hidden")&&jQuery("#livechat_notification").length>0)
	jQuery("#livechat_notification").effect("pulsate", { times:1000}, 2000);
	}
	if(data.dialogues!=0&&multiple)
	{
	$.each(data.dialogues,function(i,item)
	{
			if(jQuery("#"+item.ident).length==0)
			{
			var element=jQuery("<div class=\"userselectbtn\" id=\""+item.ident+"\"><span class=\"user_bubble\" id=\"b_"+item.ident+"\">"+item.avatar+"</span></div>") ;
			if(item.aktiv==1)
				element.attr("class","userselectbtn_aktiv");
			element.click(empfselect);
			jQuery(".userselection").append(element);
			jQuery(".userselection").css("display","block");
			}
			if(chatfirstrun)
			{
				empf=element.attr("id");
				jQuery("#chatmessage_container").html(jQuery("#c_"+empf).html());
				element.attr("class","userselectbtn_aktiv");
				chatfirstrun=false;
				if(document.getElementById("chatmessage_container").childNodes.length>1)
				document.getElementById("chatmessage_container").lastChild.scrollIntoView(true);
			}
			if(item.notification==1)
			{
				if(multiple)
				{
					if(empf!=item.ident)
					jQuery("#b_"+item.ident).attr("class","user_bubble_aktiv");	
				}
			}
	});
	if(multiple)
	jQuery("#chatmessage_container").html(jQuery("#c_"+empf).html());
	}
	}
	if(chatfirstrun)chatfirstrun=false;
}
function editAvatar()
{
	jQuery(".chatcontainer").draggable('disable');
	var input=jQuery("<input type=\"text\" value=\""+username+"\" id=\"avatarchanger\">");
	input.keyup(function(e) {
	if(e.keyCode == 13) changeAvatar();
	});
	jQuery("#avatar").html(input);
}
function changeAvatar()
{
	username=jQuery("#avatarchanger").attr("value");
	jQuery("#avatar").html(username);
	jQuery(".chatcontainer").draggable('enable');
}



///KLASSE BASE 64
 var Base64 = {
    // private property
    _keyStr : "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",

    // public method for encoding
    encode : function (input) {
        var output = "";
        var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
        var i = 0;

        input = Base64._utf8_encode(input);

        while (i < input.length) {

            chr1 = input.charCodeAt(i++);
            chr2 = input.charCodeAt(i++);
            chr3 = input.charCodeAt(i++);

            enc1 = chr1 >> 2;
            enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
            enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
            enc4 = chr3 & 63;

            if (isNaN(chr2)) {
                enc3 = enc4 = 64;
            } else if (isNaN(chr3)) {
                enc4 = 64;
            }

            output = output +
            this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) +
            this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4);

        }

        return output;
    },

    // public method for decoding
    decode : function (input) {
        var output = "";
        var chr1, chr2, chr3;
        var enc1, enc2, enc3, enc4;
        var i = 0;

        input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");

        while (i < input.length) {

            enc1 = this._keyStr.indexOf(input.charAt(i++));
            enc2 = this._keyStr.indexOf(input.charAt(i++));
            enc3 = this._keyStr.indexOf(input.charAt(i++));
            enc4 = this._keyStr.indexOf(input.charAt(i++));

            chr1 = (enc1 << 2) | (enc2 >> 4);
            chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
            chr3 = ((enc3 & 3) << 6) | enc4;

            output = output + String.fromCharCode(chr1);

            if (enc3 != 64) {
                output = output + String.fromCharCode(chr2);
            }
            if (enc4 != 64) {
                output = output + String.fromCharCode(chr3);
            }

        }

        output = Base64._utf8_decode(output);

        return output;

    },

    // 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;
	}
}
