var xmlHttp = null;
var xmlHttpCustom = null;
var baseUrl = null;

function elementById(id) {
	return document.getElementById(id);
}
function loadContentToElement(url,el,javascriptAfterLoad) {
	if(typeof(javascriptAfterLoad)=="undefined") {
		customJavascript = null;	
	} else {
		customJavascript = javascriptAfterLoad;
	}
	
	elementCustom = el;
	xmlHttpCustom = getXmlHttpObject();
	xmlHttpCustom.onreadystatechange=customRequestStateChanged;
	
	if(url.indexOf("?")!=-1)
		url += "&randomnum="+Math.random();
	else
		url += "?randomnum="+Math.random();

	xmlHttpCustom.open("POST",url,true);
	xmlHttpCustom.send(null);
}

function updateElement(url,elementId,javascriptAfterLoad)
{
	elementById(elementId).style.display='block';	
	elementById(elementId).innerHTML = '<p style="text-align: center;"><img src="'+baseUrl+'/static/images/wait.gif" alt="Wait..." /></p>';
	loadContentToElement(url,elementById(elementId),javascriptAfterLoad);
	return true;
}
function silentUpdateElement(url,elementId,javascriptAfterLoad)
{
	loadContentToElement(url,elementById(elementId),javascriptAfterLoad);	
}
/* tekee xmlhttp objektin*/
function getXmlHttpObject() {
	var xmlHttpTemp;
	try {
   		// Firefox, Opera 8.0+, Safari
   		xmlHttpTemp=new XMLHttpRequest();
   	} 
	catch (e) {
		// Internet Explorer
   		try {
			xmlHttpTemp=new ActiveXObject("Msxml2.XMLHTTP");
     	} 
		catch (e) {
     		try {
       			xmlHttpTemp=new ActiveXObject("Microsoft.XMLHTTP");
       		} catch (e){
       			alert("Your browser does not support AJAX!");
       			return null;
			}
     	}
   	}
	return xmlHttpTemp;
}
function sendComment(form,mediaId,myNick) {
	var message = document.getElementById(form).v1.value;
	var url = baseUrl+"/html/mediaMgnt?a=post&v2="+mediaId;
	url = url+"&v1="+escape(Utf8.encode(message));
	if(message.length > 1){
		userAction(url);
		document.getElementById(form).v1.value = '';
		wait('1000');
		updateSparkComments(mediaId);
		updateSparkCommentCount(mediaId);
	}
} 
function updateSparkComments(mediaId) {
	var element = "sparkComments_"+mediaId;
	var url = baseUrl+"/html/getSparkChat/"+mediaId;

	silentUpdateElement(url,element,false);	
}
function sendCommentAdmin(form,mediaId,myNick) {
	var message = document.getElementById(form).v1.value;
	var url = baseUrl+"/html/mediaMgnt?a=post&v2="+mediaId;
	url = url+"&v1="+escape(Utf8.encode(message));
	if(message.length > 1){
		userAction(url);
		document.getElementById(form).v1.value = '';
		wait('1500');
		updateSparkCommentsAdmin(mediaId);
		updateSparkCommentCount(mediaId);
	}
} 
function updateSparkCommentsAdmin(mediaId) {
	var element = "sparkComments_"+mediaId;
	var url = baseUrl+"/html/getSparkChatAdmin/"+mediaId;

	silentUpdateElement(url,element,false);	
}
function updateSparkCommentCount(mediaId) {
	var element = "sparkCommentCount_"+mediaId;
	document.getElementById(element).innerHTML = parseInt(document.getElementById(element).innerHTML)+1;
} 
function openCloseChat(url,id) {
	var mode = document.getElementById(id).style.display;
	
	if(mode == 'block'){
		document.getElementById(id).style.display = 'none';
	}else{
		updateElement(url,id,'')		
	}
} 
function userAction(requestUrl) {
	xmlHttpUser = getXmlHttpObject();
	xmlHttpUser.onreadystatechange=userActionStateChanged;
	xmlHttpUser.open("POST",requestUrl,true);
	xmlHttpUser.send(null);
}
function userActionStateChanged() { 
	if (xmlHttpUser!=null && typeof(xmlHttpUser)!="undefined" && xmlHttpUser.readyState==4){ 
		pollAllowed=true;
		if(xmlHttpUser.responseText.length > 0){	
			
			if(refreshAfterUserAction) {
				refreshAfterUserAction=false;
				pollAllowed=true;
				normalPageRequest(curPage);
			}else
			if(javascriptAfterUserAction!=null) {
				if(javascriptAfterUserAction=='sparkpreview')
				{
					showSparkPreview();
				}else if(javascriptAfterUserAction=='sparkComment')
				{
					elementById(activeCommentFormId).v1.value = "";
					elementById(activeCommentFormId).v1.disabled=false;
					elementById(activeCommentFormId).v1.focus();
					//chatScrollToBottom();
				}
			}
		}
	}
}
function customRequestStateChanged() { 
	if (xmlHttpCustom!=null && typeof(xmlHttpCustom)!="undefined" && xmlHttpCustom.readyState==4){ 
		if(xmlHttpCustom.responseText.length > 1){	
		
		if(elementCustom!=null)
			elementCustom.innerHTML = xmlHttpCustom.responseText;
			if(customJavascript!=null) {
				if(customJavascript == "hideSendToList") {
					hideSendToList(true);
				
				}else if(customJavascript == "hidereignite") {
					setTimeout("hideReignite();",1000);
				}else
				if(customJavascript == "setPreviewUserList") {
	
					elementById('formTypePreview').value = elementById('formType').value;
					//this is not currently used in preview, so dont do it
					if(userListString!=null) {
						//elementById("sendUserList").innerHTML = userListString;
						
						var userListStringSmall = userListString;
						if(userListStringSmall.length > 80) {
							userListStringSmall = userListStringSmall.substring(0,80)+"..";
						}
						elementById("sendUserListPreview").innerHTML = userListStringSmall;
					}
				}
			}
		}
	}
}
function setBaseUrl(url)
{
	baseUrl=url;	
}
function wait(millis)
{
	var date = new Date();
	var curDate = null;

	do { curDate = new Date(); }
	while(curDate-date < millis);
} 
var Utf8 = {
    // public method for url encoding
    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;
    },

    // public method for url decoding
    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;
    }
}
function changeSize(type){
	var divi = document.getElementById('contentArea');
	var icon = document.getElementById('contentIcon');
	if(divi.style.height == '185px'){
		divi.style.height = 'auto';
		icon.style.visibility = 'hidden';
		if(type == 'video'){
			icon.style.display = 'none';
			video();
		}
		
	}else if (type != 'video'){
		divi.style.height = '185px';
		icon.style.visibility = 'visible';
	}	
}
function viewImage(image){
	var divi = document.getElementById('contentArea');
	if(divi.style.height == '185px'){
		divi.style.height = 'auto';
		/*divi.style.background = '';*/
		document.getElementById('contentIcon').style.visibility = 'hidden';
		
	}else{
		divi.style.height = '185px';
		divi.style.background = 'url('+image+') center center no-repeat';
		document.getElementById('contentIcon').style.visibility = 'visible';
	}
}
function display(elem,mode){
	var divi = document.getElementById(elem);
	divi.style.display = mode;
}
var player = null;
function playerReady(thePlayer) {
	player = window.document[thePlayer.id];
}
var tipId = null;
var t;
function tip(id){
	tipId = id;
	t = setTimeout("viewTip('block');",400);
}
function tipOff(){
	clearTimeout(t);
	viewTip('none');
}
function viewTip(type){
	var divi = document.getElementById(tipId);
	divi.style.display = type;
}
function focus(id){
	try{
		var divi = document.getElementById(id);
		divi.focus();
	}catch(e){}
}
function showUserInfo(url,avatarId){
	var position = findPositionWithScrolling(document.getElementById(avatarId));
	
	uic = document.getElementById('userInfoContainer');
	
	uicArrow = document.getElementById('uiArrow');
	
	uic.style.display = 'block';
	newPos = position[1] - 80;
	newPosArrow = 65;
	if(newPos > 420){		
		newPosArrow = 65 + (newPos - 420);
		uicArrow.style.top = newPosArrow+'px';
		newPos = 420;
	}else{
		uicArrow.style.top = '70px';
	}
	
	uic.style.paddingTop = newPos + 'px';
	updateElement(url,'userInfoContent','');
}
function findPositionWithScrolling( oElement ) {
  function getNextAncestor( oElement ) {
    var actualStyle;
    if( window.getComputedStyle ) {
      actualStyle = getComputedStyle(oElement,null).position;
    } else if( oElement.currentStyle ) {
      actualStyle = oElement.currentStyle.position;
    } else {
      //fallback for browsers with low support - only reliable for inline styles
      actualStyle = oElement.style.position;
    }
    if( actualStyle == 'absolute' || actualStyle == 'fixed' ) {
      //the offsetParent of a fixed position element is null so it will stop
      return oElement.offsetParent;
    }
    return oElement.parentNode;
  }
  if( typeof( oElement.offsetParent ) != 'undefined' ) {
    var originalElement = oElement;
    for( var posX = 0, posY = 0; oElement; oElement = oElement.offsetParent ) {
      posX += oElement.offsetLeft;
      posY += oElement.offsetTop;
    }
    if( !originalElement.parentNode || !originalElement.style || typeof( originalElement.scrollTop ) == 'undefined' ) {
      //older browsers cannot check element scrolling
      return [ posX, posY ];
    }
    oElement = getNextAncestor(originalElement);
    while( oElement && oElement != document.body && oElement != document.documentElement ) {
      posX -= oElement.scrollLeft;
      posY -= oElement.scrollTop;
      oElement = getNextAncestor(oElement);
    }
    return [ posX, posY ];
  } else {
    return [ oElement.x, oElement.y ];
  }
}

function flash(mode){
	if(mode == '0'){
		vis = 'hidden';
	}else{
		vis = 'visible';
	}
	var flash = document.getElementsByTagName('embed')
	for (var i = 0; i < flash.length; i++){ 
	 	flash[i].style.visibility = vis;
	}
	var flash2 = document.getElementsByTagName('object')
	for (var i = 0; i < flash2.length; i++){ 
		flash2[i].style.visibility = vis;
	}
}
function viewLogin(){
	display('loginContainer','block');
	flash('0');
	return true;
}
function sendInvitation(url){
	name = escape(document.getElementById('inviteName').value);
	email = escape(document.getElementById('inviteEmail').value);
	otsikko = escape(document.getElementById('inviteMessage').value);
	
	loadUrl = url+'&name='+name+'&maili='+email+'&otsikko='+otsikko+'&submit=1';
	updateElement(loadUrl,'inviteDiv','');
	
	return true;
}

