var clientPC = navigator.userAgent.toLowerCase(); // Get client info
var clientVer = parseInt(navigator.appVersion); // Get browser versio
var is_ie = ((clientPC.indexOf('msie') != -1) && (clientPC.indexOf('opera') == -1));
var is_opera = ((clientPC.indexOf('msie') == -1) && (clientPC.indexOf('opera') != -1));
var is_win = ((clientPC.indexOf('win') != -1) || (clientPC.indexOf('16bit') != -1));
var imgInterval = null;


function openRulesWindow(href) {
	leftVal = (screen.width - 440) / 2;
	topVal = (screen.height - 650) / 2;
	popupWin = window.open(href, 'rulesWindow', "'" + "location=0,width=440px,height=650px,channelmode=0,dependent=0,directories=0,fullscreen=0,menubar=0,resizable=0,scrollbars=0,status=0,toolbar=0,left="+leftVal+",top="+topVal + "'"); 
	popupWin.focus(); 
	return false;
}

function openWindowWithSize(href, name, w, h) {
	leftVal = (screen.width - w) / 2;
	topVal = (screen.height - h) / 2;
	popupWin = window.open(href, name, "'" + "location=0,width=" + w + "px,height="+ h+ "px,channelmode=0,dependent=0,directories=0,fullscreen=0,menubar=0,resizable=1,scrollbars=1,status=0,toolbar=0,left="+leftVal+",top="+topVal + "'"); 
	popupWin.focus(); 
	return false;
}

function removeUserFromFriends() {
	if (confirm(dwr.util.getValue('confirm.removefriend'))) {
		document.getElementsByName('delete')[0].submit(); 
	}
}

function removeAjaxUserFromFriend(friend) {
	if (confirm(dwr.util.getValue('confirm.removefriend'))) {
		RemoteNicknameFacade.removeUserFromFriends(friend, function(data) {
			if (data == 0) {
				window.location.reload(true);
			} else {
				alert('ERROR');
			}
		});
	}
}

function openVoteWindow(href) {
	leftVal = (screen.width - 440) / 2;
	topVal = (screen.height - 500) / 2;
	popupWin = window.open(href, 'voteWindow', "'" + "location=0,width=440px,height=500px,channelmode=0,dependent=0,directories=0,fullscreen=0,menubar=0,resizable=0,scrollbars=0,status=0,toolbar=0,left="+leftVal+",top="+topVal + "'"); 
	popupWin.focus(); 
	return false;
}

function openForgotPasswordWindow(href) {
	leftVal = (screen.width - 300) / 2;
	topVal = (screen.height - 180) / 2;
	popupWin = window.open(href, 'voteWindow', "'" + "location=0,width=330px,height=225px,channelmode=0,dependent=0,directories=0,fullscreen=0,menubar=0,resizable=0,scrollbars=0,status=0,toolbar=0,left="+leftVal+",top="+topVal + "'"); 
	popupWin.focus(); 
	return false;
}

function openStatusIndicatorWindow(href){
	leftVal = (screen.width - 380) / 2;
	topVal = (screen.height - 450) / 2;
	popupWin = window.open(href, 'rulesWindow', "'" + "location=0,width=380px,height=450px,channelmode=0,dependent=0,directories=0,fullscreen=0,menubar=0,resizable=0,scrollbars=0,status=0,toolbar=0,left="+leftVal+",top="+topVal + "'"); 
	popupWin.focus(); 
	return false;
}


function setClassName(classElement, classNameToSet) {	
	if (is_ie) {
		classElement.setAttribute('className', classNameToSet);
	} else {
		classElement.setAttribute('class', classNameToSet);
	}
}

function enableComponent(elName, value) {
	toHide = document.getElementById(elName);
	toHide.disabled = !value;
}

function disableEnableForm(xForm,xHow){
  objElems = xForm.elements;
  for(i=0;i<objElems.length;i++){
    objElems[i].disabled = !xHow;
  }
  
  
}

function rotateImages() {
	
	var count = document.getElementById("stmimgcount").value;
	var list = getElemList(count);
	
	for (var i=0;i<count;i++) {
		if (list[i].getAttribute("style").toLowerCase().indexOf("display: block")>=0) {
			if (i==(--count)) {
				list[i].setAttribute("style", "display: none");
				list[0].setAttribute("style", "display: block");
				break;
			} else {
				list[i].setAttribute("style", "display: none");
				list[++i].setAttribute("style", "display: block");
				break;
			}
		}
	}
}

function getElemList(count) {
	var list = new Array();
	
	for (var i=0;i<count;i++) {
		list[i] = document.getElementById("stmvid"+i);
	}
	return list;
}

function submitAndDisableForm(form) {
	form.submit(); 
	disableEnableForm(form,false);
	
}

function inviteFriend(key, confirmMessage, successVoteMessage) {
	if (confirm(confirmMessage)) {
		RemoteMessageFacade.sendInviteToFriendsMessage(key, function(data) {
			alert(data);
		});
	}
} 



function reloadImage(path) {
	var time=new Date().getTime();
	document.getElementById('captcha').src = path + '/captcha-image.html?key=' + time;
}

function enlargePhoto(href) {
	leftVal = (screen.width - 600) / 2;
	topVal = (screen.height - 600) / 2;
	popupWin = window.open(href, 'enlargePhotoWindow', "'" + "location=0,width=600px,height=600px,channelmode=0,dependent=0,directories=0,fullscreen=0,menubar=0,resizable=0,scrollbars=0,status=0,toolbar=0,left="+leftVal+",top="+topVal + "'"); 
	popupWin.focus(); 
	return false;
}

function removeStarFromFavorites(question, starSN) {
	if (confirm(question)) {
		RemoteUserStarFavoritesFacade.removeStarFromFavoritesForCurrentUser(starSN, function(data) {
			alert(data);
			window.location.href=window.location.href;		
		}); 
	}
}

function addStarToFavorites(question, starSN) {
	if (confirm(question)) {
		RemoteUserStarFavoritesFacade.addStarToFavoritesForCurrentUser(starSN, function(data) {
			alert(data);
			window.location.href=window.location.href;		
		}); 
	}
}

function changePage(index, name, doSubmit) {  
   	dwr.util.setValue(name + 'Page', index);
   	if ((doSubmit==undefined || doSubmit==true) && document.getElementsByName(name)[0] != null) {
   		document.getElementsByName(name)[0].submit();
   	}
} 

function openAddPhotoWindow(href, w, h) {
	leftVal = (screen.width - w) / 2;
	topVal = (screen.height - h) / 2;
	popupWin = window.open(href, 'AddPhotoWindow', "'" + "location=0,width=" + w + "px,height="+h+"px,channelmode=0,dependent=0,directories=0,fullscreen=0,menubar=0,resizable=1,scrollbars=0,status=0,toolbar=0,left="+leftVal+",top="+topVal + "'"); 
	popupWin.focus(); 
	return false;
}


function openUserDetailsChangeWindow(href){
	leftVal = (screen.width - 665) / 2;
	topVal = (screen.height - 400) / 2;
	popupWin = window.open(href, 'rulesWindow', "'" + "location=0,width=665px,height=400px,channelmode=0,dependent=0,directories=0,fullscreen=0,menubar=0,resizable=0,scrollbars=0,status=0,toolbar=0,left="+leftVal+",top="+topVal + "'"); 
	popupWin.focus(); 
	return false;
}


function setWindowSize(width,height) {
	if (window.outerWidth) {
		window.outerWidth = width;
		window.outerHeight = height;
	}
	else if (window.resizeTo) {
		window.resizeTo(width,height);
	}
	else {
		alert("Not supported.");
	}
}


// copyright 1999 Idocs, Inc. http://www.idocs.com
// Distribute this script freely but keep this notice in place
function numbersonly(myfield, e, dec)
{
var key;
var keychar;

if (window.event)
   key = window.event.keyCode;
else if (e)
   key = e.which;
else
   return true;
keychar = String.fromCharCode(key);

// control keys
if ((key==null) || (key==0) || (key==8) || 
    (key==9) || (key==13) || (key==27) )
   return true;

// numbers
else if ((("0123456789").indexOf(keychar) > -1))
   return true;

// decimal point jump
else if (dec && (keychar == "."))
   {
   myfield.form.elements[dec].focus();
   return false;
   }
else
   return false;
}

function hideOrShowElement(elName, value) {
	var styleName = 'none';
	var toHide = null;
	if (value) {
		styleName = 'block';
	}
	toHide = document.getElementById(elName);
	if (document.layers){
		toHide.display = styleName;
	} else {
		toHide.style.display =styleName;
	}
}

	function getFunctionName(func) {
	if ( typeof func == "function" || typeof func == "object" )
			var fName = (""+func).match(/function\s*([\w\$]*)\s*\(/); 
	if ( fName !== null ) return fName[1];
	}
	function getObjectName(obj) {
		for(var key in window) {
			if(window[key] == obj) {
				return key;		
			}
		}
	}
 function Event() {}
 	Event.registerEvent = function(eventType, callback, object) {
   		if (object.addEventListener) {
   			object.addEventListener (eventType,callback,false);
   			} else if (object.attachEvent) {
   				object.attachEvent ("on"+eventType,callback);
   			} else {
   				eval(getObjectName(object)+".on"+eventType+"="+getFunctionName(callback)+";");
   			}		 
 	}
 	UTF8 = {
 			encode: function(s){
 				for(var c, i = -1, l = (s = s.split("")).length, o = String.fromCharCode; ++i < l;
 					s[i] = (c = s[i].charCodeAt(0)) >= 127 ? o(0xc0 | (c >>> 6)) + o(0x80 | (c & 0x3f)) : s[i]
 				);
 				return s.join("");
 			},
 			decode: function(s){
 				for(var a, b, i = -1, l = (s = s.split("")).length, o = String.fromCharCode, c = "charCodeAt"; ++i < l;
 					((a = s[i][c](0)) & 0x80) &&
 					(s[i] = (a & 0xfc) == 0xc0 && ((b = s[i + 1][c](0)) & 0xc0) == 0x80 ?
 					o(((a & 0x03) << 6) + (b & 0x3f)) : o(128), s[++i] = "")
 				);
 				return s.join("");
 			}
 		};

var ARR_ACTIVEX = ["MSXML4.DOMDocument", 
                   "MSXML3.DOMDocument",
                   "MSXML2.DOMDocument", 
                   "MSXML.DOMDocument",
                   "Microsoft.XmlDom"];
var STR_ACTIVEX = "";
if (is_ie) {
   var bFound = false;
   for (var i=0; i < ARR_ACTIVEX.length && !bFound; i++) {
      try {
         var objXML = new ActiveXObject(ARR_ACTIVEX[i]);
         STR_ACTIVEX = ARR_ACTIVEX[i];
         bFound = true

      } catch (objException) {
      }
   }
   if (!bFound)
      throw "MSXML not found on your computer."
}
var jsXML = new Object();
	jsXML.createDOMDocument = function() {
	   var objDOM = null;

	   if (document.implementation && 
	       document.implementation.createDocument) {
	      objDOM = document.implementation.createDocument("","", null);
	
	   } else if (is_ie) {	
	      objDOM = new ActiveXObject(STR_ACTIVEX);	   
	   }
	   return objDOM;
	} 	
var user2userMessageHeaderTimeout = null;
var user2userMessageContentTimeout = null; 

var pendingAjaxBlockLoaders = [];

function pendingAjaxBlockContentLoad() {
	loaderCount = 0;
	var newpendingAjaxBlockLoaders = null;
	if (pendingAjaxBlockLoaders.length>1) {
		newpendingAjaxBlockLoaders  = pendingAjaxBlockLoaders.slice(0, 1);
	} else {
		newpendingAjaxBlockLoaders = pendingAjaxBlockLoaders;
	}
	jQuery.each(newpendingAjaxBlockLoaders, function(intIndex, objValue) {
		loadAjaxBlockContent(objValue);
	});	
	pendingAjaxBlockLoaders.splice(0, 1);
	setTimeout('pendingAjaxBlockContentLoad()', 10);
}
function appendImage(blockName, contextPath) {
	   document.getElementById(blockName+"Content").innerHTML = "";
	   var block = document.getElementById(blockName+"Content");
	   var centeredContainer = document.createElement('center');
	   centeredContainer.style.paddingTop='50px';
	   centeredContainer.style.paddingBottom='50px';
	   var imageLoader = document.createElement('IMG');
	   imageLoader.src = contextPath+"/img/loaders/loader_grey.gif";
	   centeredContainer.appendChild(imageLoader);
	   block.appendChild(centeredContainer);	
}

function getIsFolder(name) {
	var isFolded = false;
	var propertiesObject = document.getElementById(name+"Properties");
	if (propertiesObject!=null) isFolded = propertiesObject.getElementsByTagName("INPUT")[1].value;
	return isFolded;
}
var loaderCount = 0;
var serverSideAttempt = 0;
function loadAjaxBlockContent(properties) {	
		
		// the callback is going here
		
		loaderCount++;
		if (loaderCount>1) {
			pendingAjaxBlockLoaders.push(properties);
			appendImage(properties.name, properties.contextPath);
			return false;
		}
		
		if (properties.hasOwnProperty("callbackFunction")) {
			window.eval.call(window, properties.callbackFunction);
		}
	   
	   var xmlHttp = XMLHTTPConnector.getRequestObject();
	   xmlHttp.onreadystatechange = executedCallBack;	
	   
	   var isFolded = getIsFolder(properties.name);
	   var params = "scale="+properties.scale+"&isFolded="+isFolded;
	   params+="&locationPath="+escape(document.location.href);
	   var parameterString = document.location.search;
	   params+="&paramString="+escape(parameterString.substring(parameterString.indexOf("?")+1));
	   params+="&blockName="+properties.name;
	   
	   if (properties.hasOwnProperty("paramsWrap")) {
		   var i=0;
		   for (key in properties.paramsWrap) {
			   if (i==0) params+="&";
			   var paramString = key+"="+properties.paramsWrap[key];
			   params+=paramString;
			   params+="&";i++;
		   }
		   params = params.slice(0, params.lastIndexOf("&", 0)); 
	   }
	   if (stmCache.contains('starKey') && params.indexOf(stmCache.load('starKey'))==-1) {
		   params+="&starKey="+stmCache.load('starKey');
	   }
	   
	   if (properties.hasOwnProperty('refreshParameters')) {
		  var refreshParameters = properties['refreshParameters']; 
		  var i=0;
		  for (key in refreshParameters) {
			   if (i==0) params+="&";
			   var paramString = key+"="+refreshParameters[key];
			   params+=paramString;
			   params+="&";i++;			  
		  }
		  params = params.slice(0, params.lastIndexOf("&", 0));
	   }
	   // no cache for all blocks added.
	   params+='&noCache='+new Date().getTime();
	   try {
		   xmlHttp.open("POST", properties.contextPath+'/block/'+properties.name+'.html', true);
		   xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded; charset=utf8");
		   xmlHttp.setRequestHeader("Accept-Charset","UTF-8");
		   xmlHttp.setRequestHeader("Content-length", params.length);
		   xmlHttp.setRequestHeader("Connection", "close");
		   xmlHttp.send(params);	
	   } catch(e) {
		  // alert("Can't connect to server"+e.toString());
		   alert("Can't connect to server "+e.description);
	   }
	   
	   // Image prepend implementation
	   if (!properties.hasOwnProperty("noImagePrepend") || !properties.noImagePrepend) {
		   appendImage(properties.name, properties.contextPath);
	   }
		
	   function executedCallBack() {	
		    if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
		    	var headerInfo = xmlHttp.getResponseHeader('headerInfo');
		    	if (headerInfo!=null && headerInfo.length>0) {
		    		document.getElementById(properties.name+'headerInfo').innerHTML = "&nbsp;("+headerInfo+")";
		    	}
		    	var block = document.getElementById(properties.name+"Content");
		    	var errorInfo = xmlHttp.getResponseHeader('errorInfo');
		    	if (errorInfo!=null && errorInfo.length>0) {
		    		block.innerHTML = "";
		    		var centeredContainer = document.createElement('center');
		    		centeredContainer.style.paddingTop='50px';
		    		centeredContainer.style.paddingBottom='50px';
		    		var errorSpan = document.createElement('SPAN');
		    		with (errorSpan.style) {
			    		color = "red";
			    		fontSize = "12px";
			    		fontWeight = "bold";
		    		}
		    		errorSpan.innerHTML = errorInfo;
		    		centeredContainer.appendChild(errorSpan);
		    		block.appendChild(centeredContainer);
		    	} else {
		    		if (xmlHttp.responseText!=null && xmlHttp.responseText.length!=0) {		
		    			// IE silly workaround
		    			try {
		    				jQuery(block).html(xmlHttp.responseText); 	
		    			} catch(e) {
		    				alert(e.description);
		    			}
		    			
		    			// if there is some js scripts to be executed
						var scriptCollector = new ScriptCollector(xmlHttp.responseText);
						while(scriptCollector.hasNext()) {
							try {
								window.eval.call(window, scriptCollector.nextScript());
							} catch(e) {}
						}	
						
		    			var javascriptContent = xmlHttp.getResponseHeader("jsContent");
		    			if (javascriptContent!=null && javascriptContent.length!=0) {
		    				try {
		    					window.eval.call(window, javascriptContent);
		    				} catch(e) {}	    				
		    			}
	    			
/*		    			var starProfileHeader = xmlHttp.getResponseHeader("starProfileHeader");
		    			if (starProfileHeader!=null && starProfileHeader.length!=0 && document.getElementById('myprofile-links')==null) {
		    				 var blockElement = document.getElementById(properties.name);
		    				 jQuery(blockElement).children('.block-header:first').append(starProfileHeader);
		    					jQuery('.myprofile').hover(
		    							function() {
		    									clearTimeout(jQuery(this).data('timeout'));
		    									jQuery('#myprofile-links').slideDown(100);
		    								},
		    							function() {
		    									var jqueryObject = jQuery(this);
		    								    var t = setTimeout(function() {
		    								    	jQuery('#myprofile-links').slideUp(100); 
		    								    }, 250);
		    								    jqueryObject.data('timeout', t);		    									
		    							}
		    						);		    				 
		    			}*/
		    			
		    			
		    		} else {
		    			block.innerHTML='';
		    		}
		    		if (properties.name=="blockNewMessage" && (xmlHttp.responseText==null || xmlHttp.responseText.length==0)) {	
		    			jQuery('#blockNewMessage').fadeIn('fast');
						if (xmlHttp.getResponseHeader('sessionTerminated')!=null && eval(xmlHttp.getResponseHeader('sessionTerminated'))) {
							jQuery('#blockNewMessageheaderInfo').html("&nbsp;(1)");														
					    	var labelElement = document.createElement('label');
					    	labelElement.style.fontWeight = 'bold';
					    	labelElement.innerHTML = "Разрыв связи";
				    		jQuery('#blockNewMessageContent').empty().append(labelElement);	
				    		jQuery('#blockNewMessageContent').append("<div style='text-align: center; margin: 10px 0;'>"+
								"<span class='btn'>"+
									"<a id='submitButton' href='#' onClick='document.location.reload(true); return false;'>Восстановить</a>"+
								"</span>&#160;&#160;"+
								"<span class='btn'>"+
									"<a id='cancelButton' href='#' onClick='hideMessageBlock(); return false;'>Отменить</a>"+
								"</span>"+
							"</div>");			
				    		Message.clearMessageTimeouts();
						} else {	    			
							user2userMessageHeaderTimeout = setTimeout("refreshHeaderMessageBlockController('"+properties.contextPath+"');", 10000);								
						}
						stmTitlebar.stopHighlight();
						stmTitlebar.startHighlight();
						Message.registered = true;
		    		}
		    	}		    	
		    } 
		    else if (xmlHttp.readyState==4 && (xmlHttp.status==0 || xmlHttp.status!=200)) {
					if (serverSideAttempt<3) {
						user2userMessageContentTimeout = setTimeout("refreshMessageBlockController('"+properties.contextPath+"');", 10000);
						serverSideAttempt++;
					}		    		
				   if (properties.name=="blockNewMessage" && serverSideAttempt==3) {
					   	jQuery('#blockNewMessageheaderInfo').html("&nbsp;(1)");
			   			jQuery('#blockNewMessage').fadeIn('fast');
				    	var labelElement = document.createElement('label');
				    	labelElement.style.fontWeight = 'bold';
				    	labelElement.innerHTML = "Разрыв связи";
			    		jQuery('#blockNewMessageContent').empty().append(labelElement);	
			    		jQuery('#blockNewMessageContent').append("<div style='text-align: center; margin: 10px 0;'>"+
							"<span class='btn'>"+
								"<a id='submitButton' href='#' onClick='document.location.reload(true); return false;'>Восстановить</a>"+
							"</span>&#160;&#160;"+
							"<span class='btn'>"+
								"<a id='cancelButton' href='#' onClick='hideMessageBlock(); return false;'>Отменить</a>"+
							"</span>"+
						"</div>");		    		
			    		Message.clearMessageTimeouts();
			    		stmTitlebar.stopHighlight();
						stmTitlebar.startHighlight();
						Message.registered = true;	
				   }	else {
					   // notify user another way.
				   }
		    }
		}  	
}

function hideMessageBlock() {
	jQuery(document.getElementById('blockNewMessage')).fadeOut('fast');
	stmTitlebar.stopHighlight();
	Message.registered = false;
	serverSideAttempt = 0;
}

// this method is needed for user message implementation
function refreshMessageBlockController(contextPath) {	  
	  loadAjaxBlockContent({name:'blockNewMessage', scale:'1', contextPath:contextPath, callbackFunction:'Message.clearMessageTimeouts();'});
}
function refreshHeaderMessageBlockController(contextPath) {
	  loadAjaxBlockHeader({name:'blockNewMessage', scale:'1', contextPath:contextPath});
}		
function loadAjaxBlockHeader(properties) {	
	   
	Message.clearMessageTimeouts();
	   var xmlHttp = XMLHTTPConnector.getRequestObject();
	   xmlHttp.onreadystatechange = executedCallBack;	
	   
	   var isFolded = "true";
	   var params = "scale="+properties.scale+"&isFolded="+isFolded;	   
	   xmlHttp.open("POST", properties.contextPath+'/block/'+properties.name+'.html', true);
	   xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	   xmlHttp.setRequestHeader("Content-length", params.length);
	   xmlHttp.setRequestHeader("Connection", "close");
	   xmlHttp.send(params);	
	   function executedCallBack() {
		    if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
		    	var headerInfo = xmlHttp.getResponseHeader('headerInfo');
		    	if (headerInfo!=null && headerInfo.length>0) {
		    		document.getElementById(properties.name+'headerInfo').innerHTML = "&nbsp;("+headerInfo+")";
		    	}
		    	user2userMessageHeaderTimeout = setTimeout("refreshHeaderMessageBlockController('"+properties.contextPath+"');", 10000);
		    } 																		    
		}  	
}

function getBlockName(element) {
	return jQuery(element).closest('.block').attr('id');
}

function reloadBlocksByName(blockNames) {
	if (typeof (blockNames)==='object' && blockNames instanceof Array) {
		for (var i=0; i<blockNames.length;i++) {
			if (document.getElementById(blockNames[i])!=null) {
				var contextPath = jQuery.data(document, "currentContext").contextPath;
				var scale = jQuery("#"+blockNames[i]+"Properties").children("INPUT").eq(0).val();
				var jsonArray = {name:blockNames[i], scale:scale, contextPath:contextPath, paramsWrap:stm.block.blockParams[blockNames[i]], noImagePrepend:false};
				loadAjaxBlockContent(jsonArray);
			}
		}
	} else {
		alert('supplied parameter is not an instance of Array type');
	}
}

function reloadBlockByName(element, parameters) {
	var blockName = getBlockName(element);
	if (blockName!=null) {
		var contextPath = jQuery.data(document, "currentContext").contextPath;
		var scale = jQuery("#"+blockName+"Properties").children("INPUT").eq(0).val();
		var jsonArray = {name:blockName, scale:scale, contextPath:contextPath, paramsWrap:stm.block.blockParams[blockName], noImagePrepend:false};
		
		if (parameters!=undefined && parameters!=null) {
			jsonArray.refreshParameters = parameters;
		}
		loadAjaxBlockContent(jsonArray);
	}
}



var Message = new Object();

Message.clearMessageTimeouts = function() {
	   // clear all associated timeouts with the message blocks
	if (user2userMessageHeaderTimeout!=null) clearTimeout(user2userMessageHeaderTimeout);
	if (user2userMessageContentTimeout!=null) clearTimeout(user2userMessageContentTimeout);	
}
Message.executeAction = function(properties) {
	   var xmlHttp = XMLHTTPConnector.getRequestObject();
	   xmlHttp.onreadystatechange = executedCallBack;	
	   
		var params = "messageSN="+properties.messageSN;
		if (properties.hasOwnProperty("messageText")) {
			params+="&messageText="+properties.messageText.replace(/^\s+|\s+$/g,"");
		}
		   xmlHttp.open("POST", properties.contextPath+'/messageBlock/messageAction/'+properties.actionName+'.html', true);
		   xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
		   xmlHttp.setRequestHeader("Content-length", params.length);
		   xmlHttp.setRequestHeader("Connection", "close");	
		   xmlHttp.send(params);
		   function executedCallBack() {
			   if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
				   
				   var reloadBlocks =  xmlHttp.getResponseHeader("reloadBlocks")
				   if (reloadBlocks!=null && reloadBlocks!=undefined) {
					   window.eval.call(window, reloadBlocks);
				   }
				   
				   var hasErrors = xmlHttp.getResponseHeader("hasErrors");
				   if (hasErrors!=null && hasErrors!=undefined && hasErrors) {
					   var responseText = xmlHttp.responseText;
					   var jsonErrorObject = eval("(" + responseText+ ")"); 
					   for (key in jsonErrorObject) {
						   var element =  document.getElementById(key);
						   element.style.display="block";
						   element.innerHTML = jsonErrorObject[key];
					   }
				   } 
				   else {
					  var unreadMessageCount =  xmlHttp.getResponseHeader("unreadMessageCount");
					  if (parseInt(unreadMessageCount)==0) document.getElementById("blockNewMessage").style.display="none";
					  loadAjaxBlockContent({name:'blockNewMessage', scale:'1', contextPath:properties.contextPath, callbackFunction:'Message.clearMessageTimeouts();'});
				   }
			   }
			}  	   
};

Message.showResource = function(properties) {
		var centerElementWrapper = document.createElement('center');
		var hashMediaType = properties.resourceType;
		var mediaSize = new MediaSizes().getHeight(hashMediaType);                                                                                                                                                                                                                                                                                                                                                                                                              
		var playerDiv = document.getElementById('playerContainer');
		playerDiv.style.display = "";
		var broadcastDiv = document.createElement('div');
		var resourceKey = properties.resourceKey;
		broadcastDivId = "mediaspace"+randomUUID();
		broadcastDiv.id = broadcastDivId;
		playerDiv.appendChild(broadcastDiv);
		
		var playerBuilder = new PlayerBuilder(properties.ticket+".flv", properties.contextPath);
		playerBuilder.setAutoplay(false);
		playerBuilder.setFullscreen(true);
		playerBuilder.setNetConnection(dwr.util.getValue('mmsStreamURL'));
		playerBuilder.setProvider('rtmp');
		playerBuilder.adjust(broadcastDivId,310,mediaSize);
		playerBuilder.writeTo(broadcastDivId);	
				
		// here we fix the sizes.
		if (properties.copied=='false') {
			var linkToCopy = document.createElement('a');
			linkToCopy.href = 'javascript:void(0);';
			linkToCopy.innerHTML = 'Сохранить сообщение';
			linkToCopy.onclick = function() {
				var title = prompt("Enter title", "undefined");
				if (title=='' || title==null) {
					alert('Title must be specified');
					return;
				}
				var xmlHttp = XMLHTTPConnector.getRequestObject();
				var uriBuffer = new StringBuffer();
				uriBuffer.append('resourceKey='+resourceKey);
				uriBuffer.append('&title='+title);
				xmlHttp.onreadystatechange = mediaCallBack;
				xmlHttp.open("POST", properties.contextPath+"/user/copyMms.html", true);
				xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");	
				xmlHttp.setRequestHeader("Content-length", uriBuffer.toString().length);
				xmlHttp.setRequestHeader("Connection", "close");			
				xmlHttp.send(uriBuffer.toString());		
				function mediaCallBack() {
					if (xmlHttp.readyState==4 && xmlHttp.status==200) {
							var copied = new String(xmlHttp.getResponseHeader('copied')).booleanValue();
							if (copied) {
								var copied = document.createElement('a');
								var response = xmlHttp.responseXML;		
								var xmlParser = new XMLParser(response);
								copied.innerHTML = xmlParser.parseResponseXML('title');
								copied.href = properties.contextPath+"/user/video/video.html?resourceKey="+xmlParser.parseResponseXML('key');
	  						} else {
	  							var copied = document.createElement('span');
	  							copied.innerHTML = xmlHttp.responseText;
	  							copied.style.color = "red";
	  						}
							for(var i=0;broadcastDiv.childNodes.length;i++) {
								if(broadcastDiv.childNodes[i].nodeName.toLowerCase()=='center'){
									broadcastDiv.removeChild(broadcastDiv.childNodes[i]);
									break;
								}
							}
							var centerWrapper = document.createElement('center');
							centerWrapper.appendChild(copied); 
							broadcastDiv.appendChild(centerWrapper);	
						}
				}
			}
			centerElementWrapper.appendChild(linkToCopy); 
			broadcastDiv.appendChild(centerElementWrapper);
		} else {
			var copied = document.createElement('a');
			copied.innerHTML = properties.copiedResourceTitle;
			copied.href = properties.contextPath+"/user/video/video.html?resourceKey="+properties.copiedResourceKey;
			centerElementWrapper.appendChild(copied); 
			broadcastDiv.appendChild(centerElementWrapper);				
		}
}
Message.openUserToUserMessageWindow = function(properties) {
	openUserMsgWindow(properties.contextPath + "/user/account/message/send.html?recipient=" 
			+ properties.userKey + "&replyTo=" + properties.messageSN, properties.userKey)
}

Message.registered = false;

var User = new Object();
User.removeUserFromFriend = function(friend, confirmMessage, elementToHideID, elementToShowID) {
	if (confirm(confirmMessage)) {
		RemoteNicknameFacade.removeUserFromFriends(friend, function(data) {
			if (data == 0) {
				reloadBlocksByName(["blockMyProfile", "blockUserFriends"]);
			} else {
				alert('ERROR');
			}
		});
	}
}
User.inviteFriend = function(key, confirmMessage, elementToHideID) {
	if (confirm(confirmMessage)) {
		RemoteMessageFacade.sendInviteToFriendsMessage(key, function(data) {
			alert(data);
			RemoteMessageFacade.getUnreadInvitation(key, function(data){
				document.getElementById(elementToHideID).style.display="none";
				var withdrawInviteContainer = document.createElement("DIV");
				withdrawInviteContainer.setAttribute("id", 'withdrawInviteMessage');
				var anchorElement = document.createElement("A");
				anchorElement.setAttribute("href", "");
				var onclickActionString = "User.withdrawInvitation('"+data+"', '"+key+"', 'Ты действительно хочешь отменить приглашение?', 'withdrawInviteMessage', 'inviteMyFriend'); return false";
				anchorElement.setAttribute("onclick", onclickActionString);
				var spanElement = document.createElement("SPAN");
				spanElement.innerHTML = "Отменить приглашение";
				anchorElement.appendChild(spanElement);
				withdrawInviteContainer.appendChild(anchorElement);
				document.getElementById('rightProfilePanel').appendChild(withdrawInviteContainer);
			});			
		});
	}
} 
User.withdrawInvitation = function(messageID, friend, confirmMessage, elementToHideID, elementToShowID) {
	if (confirm(confirmMessage)) {
		RemoteMessageFacade.withdrawInvitation(messageID, friend, function(data) {
			if (data) {
				var elementToRemove = document.getElementById(elementToHideID);
				elementToRemove.parentNode.removeChild(elementToRemove);
				document.getElementById(elementToShowID).style.display="block";
			} else {
				reloadBlocksByName(["blockMyProfile","blockUserFriends"]);
			}
		});		
	}
}

function loadUpperPanelData(contextPath) {
	   var xmlHttp = XMLHTTPConnector.getRequestObject();
	   xmlHttp.onreadystatechange = executedCallBack;	   
	   xmlHttp.open("POST", contextPath+'/header/getLatestEvents.html', true);
	   xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	   xmlHttp.setRequestHeader("Content-length", 0);
	   xmlHttp.setRequestHeader("Connection", "close");
	   xmlHttp.send(null);
	   function executedCallBack() {
		    if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
			   var responseText = xmlHttp.responseText;
			   if (responseText!=null && responseText!="") {
				   var jsonObject = eval("(" + responseText+ ")");	
				   for (key in jsonObject) {
					   if (key!='upperWallet') {
						   if (jsonObject[key]!='0') {
							   document.getElementById(key).innerHTML = '(+'+jsonObject[key]+')';
						   } else {
							   document.getElementById(key).innerHTML = '(0)';   
						   }
					   } else {
						   document.getElementById(key).innerHTML = jsonObject[key];
					   }
				   }
				   setTimeout(function() {
					   loadUpperPanelData(contextPath);
				   }, 60000);
			   }
		    } 																		    
		}  		   
	   
}
function sendMultipleMessageUser(contextPath) {
	var href = contextPath+'/user/account/message/sendMultiple.html';
	leftVal = 500;
	topVal = 700;
	popupWin = window.open(href, 'multipleMessageWindow', "'" + "location=0,width=500px,height=650px,channelmode=0,dependent=0,directories=0,fullscreen=0,menubar=0,resizable=0,scrollbars=0,status=0,toolbar=0,left="+leftVal+",top="+topVal + "'"); 
	popupWin.focus();
	popupWin = null;
	return false; 	
}
function sendMultipleMessageStar(contextPath, starKey) {
	var href = contextPath+'/user/account/message/sendMultiple.html?star='+starKey;
	leftVal = 500;
	topVal = 700;
	popupWin = window.open(href, 'multipleMessageWindow', "'" + "location=0,width=500px,height=650px,channelmode=0,dependent=0,directories=0,fullscreen=0,menubar=0,resizable=0,scrollbars=0,status=0,toolbar=0,left="+leftVal+",top="+topVal + "'"); 
	popupWin.focus();
	popupWin = null;
	return false; 	
}
function ParamWrapper() {
	this.params = {};
	this.addParams = function(parameters) {
		for (key in parameters) {
			this.params[key] = parameters[key];
		}
	}
	this.getParams = function() {
		return this.params;
	}
}

var Trigger = new Object();
Trigger.triggerEvent = function(element, event) {
	if (document.createEventObject){
		// dispatch for IE
		var evt = document.createEventObject();
		return element.fireEvent('on'+event,evt)
		}
		else{
		// dispatch for firefox + others
		var evt = document.createEvent("HTMLEvents");
		evt.initEvent(event, true, true );
		return !element.dispatchEvent(evt);
		}	
}

function loadContextMenu(contextPath, holderType, key, popupID) {
	   var xmlHttp = XMLHTTPConnector.getRequestObject();
	   var params = "holderType="+holderType.toUpperCase()+"&key="+key;
	   xmlHttp.onreadystatechange = executedCallBack;	   
	   xmlHttp.open("POST", contextPath+'/user/popupmenu.html', true);
	   xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	   xmlHttp.setRequestHeader("Content-length", params.length);
	   xmlHttp.setRequestHeader("Connection", "close");	   
	   xmlHttp.send(params);
	   function executedCallBack() {
		    if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
			   var responseText = xmlHttp.responseText;
			   	document.getElementById(popupID).innerHTML = responseText;
			   	positionAndShowMenu(popupID);
		    } 
		    else if (xmlHttp.readyState == 4 && (xmlHttp.status == 0 || xmlHttp.status!=200)) {
		    	document.getElementById(popupID).innerHTML = "Connection has been lost. Try to reconnect";
		    	positionAndShowMenu(popupID);
		    }
		}  		
}
// options
var MenuContextOptions = new Object();
MenuContextOptions.distance = 10;
MenuContextOptions.time = 250;
MenuContextOptions.hideDelay = 250;
MenuContextOptions.showDelay = 700;

MenuContextOptions.hideDelayTimer = null;
MenuContextOptions.showDelayTimer = null;
var onMenu = null;
var shownMenuID = null;

if (opener==null) { 
	jQuery(document).ready(function() {
		jQuery(this).mousemove(function(event) {
			mouseMoveEvent = event;
		});
	});
}

// tracker
MenuContextOptions.beingShown = false;
MenuContextOptions.shown = false;
MenuContextOptions.showID = null;
function showContextMenu(contextPath, holderType, key, popupID, event) {
    // stops the hide event if we move from the trigger to the popup element
    if (MenuContextOptions.hideDelayTimer) clearTimeout(MenuContextOptions.hideDelayTimer);

    // don't trigger the animation again if we're being shown, or already visible
    if ((MenuContextOptions.beingShown || MenuContextOptions.shown) && MenuContextOptions.showID!=null && MenuContextOptions.showID==popupID) {
      return;
    } else if ((MenuContextOptions.beingShown || MenuContextOptions.shown) && MenuContextOptions.showID!=null && MenuContextOptions.showID!=popupID) {
    	hideContextMenu(contextPath, holderType, key, MenuContextOptions.showID);
    	forcedShow(contextPath, holderType, key, popupID, event);
    	return;
    }
    else {
    	forcedShow(contextPath, holderType, key, popupID, event);
    	return;
    }
}

function setMenu(key, to) {
	if (to) {
		onMenu=key;
	} else {
		onMenu=null;
	}
}

function forcedShow(contextPath, holderType, key, popupID, event) {
	MenuContextOptions.showDelayTimer = setTimeout( function() {
		if (!onMenu || onMenu!=key) {
			setMenu(key,true);
	    	MenuContextOptions.beingShown = true;
	    	var elementID = key+'bubbleMenu';
	    	var bubbleContainer = document.getElementById('bubbleContainer');
	    	bubbleContainer.innerHTML='';
	    	if (document.getElementById(elementID)==null) {
		    	var absolutecontainerForMenu = document.createElement('DIV');
		    	absolutecontainerForMenu.innerHTML = '&amp;nbsp;';
		    	absolutecontainerForMenu.className = 'bubbleMenu';
		    	absolutecontainerForMenu.id = key+'bubbleMenu';
		    	if (navigator.userAgent.toLowerCase().indexOf('msie')!=-1) {
		    		absolutecontainerForMenu.onmouseover = new Function('evt', "setMenu("+key+",true);");
		    		absolutecontainerForMenu.onmouseout = new Function('evt', "setMenu("+key+",false);hideContextMenu('"+contextPath+"', '"+holderType+"', '"+key+"', '"+key+"bubbleMenu',event);");
		    	} else {
		    		absolutecontainerForMenu.setAttribute('onmouseover', "setMenu("+key+",true);");
		    		absolutecontainerForMenu.setAttribute('onmouseout', "setMenu("+key+",false);hideContextMenu('"+contextPath+"', '"+holderType+"', '"+key+"', '"+key+"bubbleMenu',event);");
		    	}
		    	absolutecontainerForMenu.setAttribute('style', 'opacity:0;');
		    	bubbleContainer.appendChild(absolutecontainerForMenu);
	    	}
	    	loadContextMenu(contextPath, holderType, key, popupID);
		}
	}, MenuContextOptions.showDelay); 	
}

function positionAndShowMenu(popupID) {
	jQuery("#"+popupID).css({
    	display: 'block' // brings the popup back in to view
  	});
  	var bubbleContainer=document.getElementById('bubbleContainer');
  	clientX = mouseMoveEvent.clientX;
	clientY = mouseMoveEvent.clientY;
	popupW = bubbleContainer.clientWidth;
	popupH = bubbleContainer.clientHeight;
	winW = window.innerWidth;
	winH = window.innerHeight;
	var xPos = mouseMoveEvent.pageX+1;
	var yPos = mouseMoveEvent.pageY+1;
	if((clientX+popupW)>winW) {
		xPos = mouseMoveEvent.pageX-popupW+5;
	}
	if((clientY+popupH)>winH) {
		yPos = mouseMoveEvent.pageY-popupH+5;
	}
	
    jQuery("#bubbleContainer").css({
        left: xPos,
        top: yPos
    });
     // reset position of popup box
      jQuery("#"+popupID)
      // (we're using chaining on the popup) now animate it's opacity and position
      .animate({
        opacity: 1
      }, MenuContextOptions.time, 'swing', function() {
        // once the animation is complete, set the tracker variables
    	  MenuContextOptions.beingShown = false;
    	  MenuContextOptions.shown = true;	
    	  MenuContextOptions.showID = popupID;
      });
      shownMenuID = popupID;
}

function hideContextMenu(contextPath, holderType, key, popupID) {
    // reset the timer if we get fired again - avoids double animations
    if (MenuContextOptions.hideDelayTimer) clearTimeout(MenuContextOptions.hideDelayTimer);
    if (MenuContextOptions.showDelayTimer) clearTimeout(MenuContextOptions.showDelayTimer);
	setMenu(key,false);
    // store the timer so that it can be cleared in the mouseover if required
	    MenuContextOptions.hideDelayTimer = setTimeout(function () {
		    if (!onMenu || onMenu!=key) {
		    	MenuContextOptions.hideDelayTimer = null;
		    jQuery("#"+shownMenuID).animate({
		        opacity: 0
		      }, MenuContextOptions.time, 'swing', function () {
		        // once the animate is complete, set the tracker variables
		    	  MenuContextOptions.shown = false;
		        // hide the popup entirely after the effect (opacity alone doesn't do the job)
		    	  jQuery("#"+shownMenuID).css('display', 'none');
		//    	  jQuery("#"+popupID).empty();
		    	  jQuery("#"+shownMenuID).remove();
		    	  MenuContextOptions.showID = null;
		      });
		    }
	    }, MenuContextOptions.hideDelay);
	
}

function getQueryParameter(param) {
	param = param.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
	var regexS = "[\\?&]"+param+"=([^&#]*)";
	var regex = new RegExp(regexS);
	var results = regex.exec(window.location.href);
	if (results==null) return "";
	else return results[1];
}

function toogleElementVisibility(elementID, speed) {
	if (speed=='undefined' || !speed) speed='fast';
	if (jQuery('#'+elementID).css('display')=='block') {
		jQuery('#'+elementID).slideUp(speed);
	} else {
		jQuery('#'+elementID).slideDown(speed);
	}
}

if (typeof DOMParser == "undefined") {
	   DOMParser = function () {}

	   DOMParser.prototype.parseFromString = function (str, contentType) {
	      if (typeof ActiveXObject != "undefined") {
	         var d = new ActiveXObject("MSXML.DomDocument");
	         d.loadXML(str);
	         return d;
	      } else if (typeof XMLHttpRequest != "undefined") {
	         var req = new XMLHttpRequest;
	         req.open("GET", "data:" + (contentType || "application/xml") +
	                         ";charset=utf-8," + encodeURIComponent(str), false);
	         if (req.overrideMimeType) {
	            req.overrideMimeType(contentType);
	         }
	         req.send(null);
	         return req.responseXML;
	      }
	   }
	}

function getWindowSizes() {
	var myWidth = 0, myHeight = 0;
	if( typeof( window.innerWidth ) == 'number' ) {
	  //Non-IE
	  myWidth = window.innerWidth;
	  myHeight = window.innerHeight;
	} else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
	  //IE 6+ in 'standards compliant mode'
	  myWidth = document.documentElement.clientWidth;
	  myHeight = document.documentElement.clientHeight;
	} else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
	  //IE 4 compatible
	  myWidth = document.body.clientWidth;
	  myHeight = document.body.clientHeight;
	}
	return {width:myWidth, height:myHeight};
}

/* button element "disable" property emulation for <a href> (new style STM buttons) */
function enableSTMButton(elem, enable) {
	if (enable) {
		elem.className = "";
	} else {
		elem.className = "btn-disabled";
		elem.onclick = "return false;";
	}
}

var UserUtils = {
		getCurrentUserKey : function() {
			var existInCache = stmCache.contains('cachedCurrentUserID');
			if (!existInCache) {
				UserUtil.getCurrentUserID(function(data){
					stmCache.push('cachedCurrentUserID', data);
					return data;
				});
			} else {
				return stmCache.load('cachedCurrentUserID');
			}
			
		},
		getCurrentUser : function() {
			var existInCache = stmCache.contains('cachedCurrentUser');
			if (!existInCache) {
				UserUtil.getCurrentUser(function(data){
					stmCache.push('cachedCurrentUser', data);
					return data;
				});		
			} else {
				return stmCache.load('cachedCurrentUser');
			}
		},
		getContextPath : function() {
			var existInCache = stmCache.contains('cachedContextPath');
			if (!existInCache) {
				UserUtil.getContextPath(function(data){
					stmCache.push('cachedContextPath', data);
					return data;
				});		
			} else {
				return stmCache.load('cachedContextPath');
			}			
		},
		executeFunction : function(functionName) {
			while((cotextPath=getContextPath())==undefined || contextPath==null) continue;
			var contextPath = getContextPath();
			return (functionName instanceof String)?window[functionName].call(contextPath):functionName.call(contextPath);
		}
}

function PlayerBuilder(url, contextPath) {
	var location = window.location.protocol+"//"+window.location.host+contextPath;
	var playerPath = location+"/javascript/media/flowplayer-3.1.5.swf";
	/*
	var playerPath = location+"/javascript/media/flowplayer-3.2.2.swf";
	*/
	var audioPlugin = location+"/javascript/media/flowplayer.audio-3.1.2.swf";
	var controlsPlugin = location+"/javascript/media/flowplayer.controls-3.1.5.swf";
	/*
	var controlsPlugin = location+"/javascript/media/flowplayer.controls-3.2.1.swf";
	*/
	var netConnectionPlugin = location+"/javascript/media/flowplayer.rtmp-3.1.3.swf";
	var flashVersionRequired = ['9','10'];
	this.autoplay = true;
	this.scaling = 'scale';
	this.duration = 0;
	this.fullscreen = true;
	this.autobuffering = true;
	this.provider = null;
	this.netConnection = null;
	this.controlbar = new Object();
	this.eventArray = new Array();
	this.playerInstance = null;
	this.logo = null;
	this.bufferLength = 5;
	this.liveMode = false;
	
	this.setAutoplay = function(autoplay) {
		this.autoplay = autoplay;
	}
	this.setScaling = function(scaling) {
		this.scaling = scaling;
	}
	this.setDuration = function(duration) {
		this.duration = parseInt(duration);
		this.bufferLength = this.duration>10?10:this.duration-1;
	}
	this.setFullscreen = function(fullscreen) {
		this.fullscreen = fullscreen;
	}
	this.setAutobuffering = function(autobuffering) {
		this.autobuffering = autobuffering;
	}
	this.setProvider = function(provider) {
		this.provider = provider;
	}
	this.setNetConnection = function(netConnection) {
		this.netConnection = netConnection;
	}
	this.disableControl = function() {this.controlbar=null;}
	this.adjust = function(mediaspace, width, height) {
		jQuery(document.getElementById(mediaspace)).css({width:width, height:height});
	}
	this.pushEvent = function(eventType, eventFunction) {
		this.eventArray.push({eventType:eventType, eventFunction:eventFunction});
	}
	this.getInstance = function() {
		return this.playerInstance;
	}
	this.setLogo = function(logo) {
		this.logo = logo;
	}
	this.setBufferLength = function(length) {
		this.bufferLength = length;
	}
	this.setLiveMode = function(mode) {
		this.liveMode = mode;
	}
	function observeElement(elementID, instance, callback) {
		var observeTimeout = null;
		var timeoutFunction = function() {
			var element = document.getElementById(elementID);
			if (element!=null)  {
				clearTimeout(timeoutFunction);
				callback.apply(null, [element, instance]);
			} else {
				observeTimeout = setTimeout(timeoutFunction, 10);		
			}
		}
		observeTimeout = setTimeout(timeoutFunction, 10);
	}
	
	function getFlashVersion(){
		  try {
		    try {
		      var axo = new ActiveXObject('ShockwaveFlash.ShockwaveFlash.6');
		      try { axo.AllowScriptAccess = 'always'; }
		      catch(e) { return '6,0,0'; }
		    } catch(e) {}
		    return new ActiveXObject('ShockwaveFlash.ShockwaveFlash').GetVariable('$version').replace(/\D+/g, ',').match(/^,?(.+),?$/)[1];
		  } catch(e) {
		    try {
		      if(navigator.mimeTypes["application/x-shockwave-flash"].enabledPlugin){
		        return (navigator.plugins["Shockwave Flash 2.0"] || navigator.plugins["Shockwave Flash"]).description.replace(/\D+/g, ",").match(/^,?(.+),?$/)[1];
		      }
		    } catch(e) {}
		  }
		  return '0,0,0';
		}
	function clear(mediaspace) {
		var currentElement = jQuery(document.getElementById(mediaspace));
		currentElement.empty();		
	}
	this.injectEmbed = function(placeholder, autoplay) {
		var supportedElements = new Array('input', 'textarea');		
		observeElement(placeholder, this,  function(elementToInsert, thisInstance) {
			var placeHolderArea = jQuery(elementToInsert);
			var embed = thisInstance.getInstance().embed().getEmbedCode(true, -1, autoplay);
			var domElement = placeHolderArea.get(0);
			if (jQuery.inArray((domElement.tagName?domElement.tagName:domElement.nodeName).toLowerCase(), supportedElements)!=-1) {
				placeHolderArea.val(embed);
			} else {
				placeHolderArea.html(embed);
			}			
		})
	}
	this.writeTo = function(mediaspace) {
		var reportError = function() {
			jQuery(document.getElementById(mediaspace)).append('<div style="color:red;text-align:center;">This content requires <a href="http://www.adobe.com/go/getflashplayer/">Adobe Flash Player</a></div>');
		}
		var version = getFlashVersion().split(',').shift();
		if (jQuery.inArray(version, flashVersionRequired)==-1) {
			reportError();
			return;
		}
		clear(mediaspace);
		var clipObject = new Object();
		clipObject.autoPlay = this.autoplay;
		clipObject.autoBuffering = this.autobuffering;
		clipObject.duration = this.duration;
		clipObject.url = url;
		clipObject.scaling = this.scaling;
		clipObject.bufferLength = this.bufferLength;
		clipObject.live = this.liveMode;
		if (this.provider!=null) clipObject.provider = this.provider;	
		
		jQuery.each(this.eventArray, function(index, item) {
			clipObject[item.eventType] = item.eventFunction;
		});
		if (this.controlbar!=null) {
			this.controlbar.fullscreen = this.fullscreen;
			this.controlbar.url = controlsPlugin;
			
			var skinObject = {					

					/*
					backgroundColor: "transparent",
					backgroundGradient: "none",
					sliderColor: '#FFFFFF',
					sliderBorder: '1.5px solid rgba(160,160,160,0.7)',
					volumeSliderColor: '#FFFFFF',
					volumeBorder: '1.5px solid rgba(160,160,160,0.7)',

					timeColor: '#ffffff',
					durationColor: '#535353',

					tooltipColor: 'rgba(255, 255, 255, 0.7)',
					tooltipTextColor: '#000000'					
					*/
					
					/*
					 buttonOverColor: '#ffffff',
				      borderRadius: '0px',
				      bufferGradient: 'none',
				      volumeSliderColor: '#ffffff',
				      sliderBorder: '1px solid rgba(128, 128, 128, 0.7)',
				      sliderColor: '#000000',
				      timeColor: '#ffffff',
				      sliderGradient: 'none',
				      tooltipColor: '#000000',
				      volumeSliderGradient: 'none',
				      tooltipTextColor: '#ffffff',
				      autoHide: 'never',
				      backgroundGradient: [0.5,0,0.3],
				      progressGradient: 'none',
				      bufferColor: '#445566',
				      timeSeparator: ' ',
				      timeBgColor: 'rgb(0, 0, 0, 0)',
				      timeBorder: '0px solid rgba(0, 0, 0, 0.3)',
				      progressColor: '#112233',
				      backgroundColor: '#222222',
				      volumeColor: '#ffffff',
				      durationColor: '#a3a3a3',
				      buttonColor: '#ffffff',
				      volumeBorder: '1px solid rgba(128, 128, 128, 0.7)',
				      height: 24,
				      opacity: 1.0
				      */
				      
			}
			jQuery.extend(true, this.controlbar, skinObject);
		}
		var logoObject = {};
		if (this.logo!=null) logoObject.url = this.logo; logoObject.fullscreenOnly = false;
		try {
			this.playerInstance = flowplayer(
					mediaspace, 
					{src:playerPath, cachebusting:true, wmode:'opaque'}, {
					plugins: {
						controls: this.controlbar,
						audio: {
							url: audioPlugin
						},
				        rtmp: { 
							url: netConnectionPlugin,
							netConnectionUrl: this.netConnection
				        }
					},					
					clip:clipObject,
					logo:logoObject,
					canvas: { 
				        backgroundGradient: 'none',
				        backgroundColor: 'transparent'
				    }					
			}); 
		} catch(e) {reportError();}
		this.playerInstance.onFinish(function() {this.stop(); this.seek(0);});
	}   
}

