var SSACTIVE = true;
var MSGACTIVE =true;
var draftTimer;

/* BADGES */
function saveBadge(badgeObj,action){
	spanElement = badgeObj.parentNode;
	spanIDelements = badgeObj.parentNode.id.split("-");
	// 1 - type; 2 - objectid; 3 - object owner id
	if(action === true){
		jQuery('#'+spanElement.id+' a.giveBadge_visible').attr('class','giveBadge_nonvisible');
		jQuery('#'+spanElement.id+' a.takeBadge_nonvisible').attr('class','takeBadge_visible');
	} else if(action === false){
		jQuery('#'+spanElement.id+' a.takeBadge_visible').attr('class','takeBadge_nonvisible');
		jQuery('#'+spanElement.id+' a.giveBadge_nonvisible').attr('class','giveBadge_visible');
	} else{
		return false;
	}
	
		jQuery.post('/common/commonXml.php',{task: 'save_badge',giveBadge:action,ownerid:spanIDelements[3],objid:spanIDelements[2],typeid:spanIDelements[1]});
	
}

/* LOAD COMMENT AFTER SUBMIT */
function updateCommentForm(ajaxUrl, typeid, itemid, commentid, ccount, form, append){
	jQuery.ajax({
		url: "/common/"+ajaxUrl,
		type: "POST",
		data: "typeid="+typeid+"&ccount="+ccount+"&itemid="+itemid+"&cid="+commentid,
		success: function(data){
			jQuery("#comm-add-"+typeid+"_"+itemid+"-box").remove();
			if(append == 1){
				jQuery('#'+form).append(data);
			} else {
				jQuery('#'+form).html(data);
			}
		}
	});
	
}

/* DELETE COMMENT FROM FIRST PAGE ACTIVITIES */
function delCommentUpdateContainer(typeid, itemid, commentid, form){
	jQuery.ajax({
		url: "/common/commentsSmallXml.php",
		type: "POST",
		data: "typeid="+typeid+"&itemid="+itemid+"&delcomment="+commentid,
		success: function(data){
			jQuery('#'+form).html(data);
		}
	});
	
}


var activitiesPage = 0;

function loadActivities(itemid){

	itemid = typeof(itemid) != 'undefined' ? itemid : 0;
	
	if($('activities-big-box')!==null){
		$('activities-big-box').appendChild (createLoad (0,'activities-big-box'));	
		jQuery.ajax({
			type: "POST",
			url: "/start/startXml.php",
			data: "task=load-activities&step="+activitiesPage+"&itemid="+itemid,
			success: function(html){
				jQuery('#activities-big-box_loading-img').remove();
				jQuery('#activities-big-box').append(html);
				activitiesPage++;
			}
		});
		
	}
}

function loadBBMessage(mid){
	jQuery.ajax({
			type: "POST",
			url: "/start/startXml.php",
			data: "task=load-bb-message&mid="+mid,
			dataType: "html",
			success: function(html){
				jQuery('#activities-big-box').prepend(html);
				jQuery('#bmessage').html('');
			}
		});
}

function showAllComments(objectid,typeid){
	divId = 'comment-form-'+typeid+'-'+objectid;
	jQuery.ajax({
			type: "POST",
			url: "/common/commentsSmallXml.php",
			data: "comtask=showallcomments&itemid="+objectid+"&typeid="+typeid,
			success: function(html){
				jQuery('#'+divId).html(html);
			}
		});
}

function startPageShowVideo(objid, videoCode){
	embedCode = '<object width="300" height="247">\
						  <param name="movie" value="http://www.youtube.com/v/'+videoCode+'"></param>\
						  <embed src="http://www.youtube.com/v/'+videoCode+'" type="application/x-shockwave-flash" width="300" height="247">\
						  </embed>\
						</object>';
	$('player-area-'+objid).appendChild (createLoad (0,'player-area-'+objid));	
	jQuery('#player-area-'+objid).html(embedCode);
}

/* DRAFT FUNCS */
function saveDraft(userid){
    var draftType = jQuery('#draft_type').val();
    var draftObject = jQuery('#itemid').val();
    var textVal = jQuery('#msgbody').val();

    jQuery.post('/common/commonXml.php',{task: 'save_draft',dtype:draftType,dobjid:draftObject,duserid:userid,dtext: textVal});
    draftTimer = setTimeout('saveDraft()',60000);
}

function stopDraft(){
    clearTimeout(draftTimer);
}
/* --- */

function getUrl(url) {
    document.location.href=url;
}

function OpenRadioSearch(){
	 var string = jQuery("#FpageRadio").val();
	popUp('/player2/?cat=search&subcat='+string);
}

function number_format( number, decimals, dec_point, thousands_sep ) {
    // Format a number with grouped thousands
    // 
    // +    discuss at: http://kevin.vanzonneveld.net/techblog/article/javascript_equivalent_for_phps_number_format/
    // +       version: 803.115
    // +   original by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +     bugfix by: Michael White (http://crestidg.com)
    // *     example 1: number_format(1234.5678, 2, '.', '');
    // *     returns 1: 1234.57

    var i, j, kw, kd, km;

    // input sanitation & defaults
    if( isNaN(decimals = Math.abs(decimals)) ){
        decimals = 2;
    }
    if( dec_point == undefined ){
        dec_point = ",";
    }
    if( thousands_sep == undefined ){
        thousands_sep = ".";
    }

    i = parseInt(number = (+number || 0).toFixed(decimals)) + "";

    if( (j = i.length) > 3 ){
        j = j % 3;
    } else{
        j = 0;
    }

    km = (j ? i.substr(0, j) + thousands_sep : "");
    kw = i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + thousands_sep);
    //kd = (decimals ? dec_point + Math.abs(number - i).toFixed(decimals).slice(2) : "");
    kd = (decimals ? dec_point + Math.abs(number - i).toFixed(decimals).replace(/-/, 0).slice(2) : "");


    return km + kw + kd;
}

/* 4 CHAT */
if (navigator.userAgent && navigator.userAgent.indexOf("MSIE") >= 0 && navigator.appVersion.indexOf("Win") != -1) {
  var plugin = (navigator.mimeTypes && navigator.mimeTypes["application/x-shockwave-flash"]) ? navigator.mimeTypes["application/x-shockwave-flash"].enabledPlugin : 0;

  if (!plugin) {
    document.write('<SCR' + 'IPT LANGUAGE=VBScript\> \n');
    document.write('on error resume next \n');
    document.write('MM_VB_FlashCanPlay3 = (IsObject(CreateObject("ShockwaveFlash.ShockwaveFlash.3")))\n');
    document.write('MM_VB_FlashCanPlay4 = (IsObject(CreateObject("ShockwaveFlash.ShockwaveFlash.4")))\n');
    document.write('MM_VB_FlashCanPlay5 = (IsObject(CreateObject("ShockwaveFlash.ShockwaveFlash.5")))\n');
    document.write('MM_VB_FlashCanPlay6 = (IsObject(CreateObject("ShockwaveFlash.ShockwaveFlash.6")))\n');
    document.write('MM_VB_FlashCanPlay7 = (IsObject(CreateObject("ShockwaveFlash.ShockwaveFlash.7")))\n');
    document.write('MM_VB_FlashCanPlay8 = (IsObject(CreateObject("ShockwaveFlash.ShockwaveFlash.8")))\n');
    document.write('MM_VB_FlashCanPlay9 = (IsObject(CreateObject("ShockwaveFlash.ShockwaveFlash.9")))\n');
    document.write('</SCR' + 'IPT\> \n');
  }
}

function AVP_ActivateFlash (htmlCode) {
  document.writeln(htmlCode);
}

function AVP_ActivateFlashByVersion (flashCode, alternateCode, requiredVersion) {
  if (!alternateCode || alternateCode.length == 0) {
    document.writeln(flashCode);
  }

  else {
    var MM_contentVersion = requiredVersion;
    var MM_PluginVersion = 0;
    var MM_FlashCanPlay = 0;

    var plugin = (navigator.mimeTypes && navigator.mimeTypes["application/x-shockwave-flash"]) ? navigator.mimeTypes["application/x-shockwave-flash"].enabledPlugin : 0;

    if (plugin) {
      var words = navigator.plugins["Shockwave Flash"].description.split(" ");

      for (var i = 0; i < words.length; ++i) {
        if (isNaN(parseInt(words[i]))) {
          continue;
        }

        MM_PluginVersion = words[i];
      }

      MM_FlashCanPlay = (MM_PluginVersion >= MM_contentVersion);
    }

    else if (navigator.userAgent && navigator.userAgent.indexOf("MSIE") >= 0 && navigator.appVersion.indexOf("Win") != -1) {
      if (MM_VB_FlashCanPlay3 && requiredVersion <= 3) { MM_FlashCanPlay = 1; }
      else if (MM_VB_FlashCanPlay4 && requiredVersion <= 4) { MM_FlashCanPlay = 1; }
      else if (MM_VB_FlashCanPlay5 && requiredVersion <= 5) { MM_FlashCanPlay = 1; }
      else if (MM_VB_FlashCanPlay6 && requiredVersion <= 6) { MM_FlashCanPlay = 1; }
      else if (MM_VB_FlashCanPlay7 && requiredVersion <= 7) { MM_FlashCanPlay = 1; }
      else if (MM_VB_FlashCanPlay8 && requiredVersion <= 8) { MM_FlashCanPlay = 1; }
      else if (MM_VB_FlashCanPlay9 && requiredVersion <= 9) { MM_FlashCanPlay = 1; }
      else { MM_FlashCanPlay = 0; }
    }

    if (MM_FlashCanPlay) {
      document.writeln(flashCode);
    }

    else {
      document.writeln(alternateCode);
    }
  }
}
/* 4 chat end */


function formatCurrency(num) {
        num = num.toString().replace(/\$|\,/g,'');
        if(isNaN(num))
        num = "0";
        sign = (num == (num = Math.abs(num)));
        num = Math.floor(num*100+0.50000000001);
        cents = num%100;
        num = Math.floor(num/100).toString();
        if(cents<10)
        cents = "0" + cents;
        for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
        num = num.substring(0,num.length-(4*i+3))+','+
        num.substring(num.length-(4*i+3));
        return (((sign)?'':'-') + '' + num + '.' + cents);
    }
    
    
function submitCommentForm () {
                $('submit-btn').setAttribute('disabled','disabled');
                $('comm-add-box').submit();
          }

function submitCommentFormFP (formid) {
								$('submit-btn-'+formid).setAttribute('disabled','disabled');
                $('comm-add-'+formid+'-box').submit();
                
}
          
function submitRegisterForm() {
	$('SubmitRegister').setAttribute('disabled','disabled');
	$('SubmitRegister').addClassName('disabled');
	$('form-register-box').submit();
	window.setTimeout('enableRegisterButton()',2000);
}

function enableRegisterButton(){
	$('SubmitRegister').removeAttribute('disabled');
	$('SubmitRegister').removeClassName('disabled');
	
}

function submitFormDisableButton(formName,buttonObj) {
	//$(buttonObj.id).addClassName('disabled');
	$(formName).submit();
	buttonObj.setAttribute('disabled','disabled');
	buttonObj.addClassName('disabled');
	window.setTimeout("enableSubmitButton('"+buttonObj.id+"')",2000);
}

function enableSubmitButton(buttonObj){
	$(buttonObj).removeAttribute('disabled');
	$(buttonObj).removeClassName('disabled');
	
}
         
function openRadio (){
    popUp (PlayerServer+'player2/?fp=1',990,759,false,true);
}

function openPrivateChat(uid){
  popUp ('/chat/private.php?uid='+uid,600,600,false,true);
 //privChatWin = window.open('/chat/private.php?uid='+uid,'pchat'+uid,'width=600,height=600,resizable=yes,adress=yes,status=yes');
 //privWindows[uid]=privChatWin;
 //alert(privWindows[uid])
}


function showSecondaryNav () {
	jQuery('#topnav-second').css('height','34px');
}


function ToggleMessage (id,update) {
	jQuery('#msg-body-'+id).toggle('fast',function(){;});	
	if (update) {
		var row = $('msg-subj-'+id);
		Element.removeClassName ($('row-'+id),'unread');
		new Ajax.Request ('/messages/messagesXml.php', {parameters:'task=setread&id='+id});
	}
}

function getCookie( name ) {
    var start = document.cookie.indexOf( name + "=" );
    var len = start + name.length + 1;
    if ( ( !start ) && ( name != document.cookie.substring( 0, name.length ) ) ) {
        return null;
    }
    if ( start == -1 ) return null;
    var end = document.cookie.indexOf( ";", len );
    if ( end == -1 ) end = document.cookie.length;
    return unescape( document.cookie.substring( len, end ) );
}

function setCookie( name, value, expires, path, domain, secure ) {
    var today = new Date();
    today.setTime( today.getTime() );
    if ( expires ) {
        expires = expires * 1000 * 60 * 60 * 24;
    }
    var expires_date = new Date( today.getTime() + (expires) );
    document.cookie = name+"="+escape( value ) +
        ( ( expires ) ? ";expires="+expires_date.toGMTString() : "" ) + //expires.toGMTString()
        ( ( path ) ? ";path=" + path : "" ) +
        ( ( domain ) ? ";domain=" + domain : "" ) +
        ( ( secure ) ? ";secure" : "" );
}

function deleteCookie( name, path, domain ) {
    if ( getCookie( name ) ) document.cookie = name + "=" +
            ( ( path ) ? ";path=" + path : "") +
            ( ( domain ) ? ";domain=" + domain : "" ) +
            ";expires=Thu, 01-Jan-1970 00:00:01 GMT";
}


openMusicPlayer = function(){
 var newp = arguments[1];
 if(!newp){
  playerWin = window.open(PlayerServer+'player/music.php?'+arguments[0],'player','width=400,height=400,resizable=yes');
 }else{
  var dims = getCookie('playerWindowSize');
  //alert(dims)
  if(dims){
   var tmp = dims.split('x');
            var ww = tmp[0]; var wh = tmp[1]; var wx = tmp[2]; var wy = tmp[3];
  }else{
            var ww = 950;
            var wh = 650;
   wx=wy=0;
  }
        playerWin = window.open(PlayerServer+'player2/?'+arguments[0]+'&fp=1','player_new','width='+ww+',height='+wh+',left='+wx+',top='+wy+',scrollbars=yes,resizable=yes');
 }
 playerWin.focus();
}

function openParent (URL) {
	if (window.opener) {
		window.opener.location.href=URL;	
	} else
		window.self.location.href=URL;
}

function sleep(naptime) {
      var sleeping = true;
      var now = new Date();
      var alarm;
      var startingMSeconds = now.getTime();
      while(sleeping){
         alarm = new Date();
         alarmMSeconds = alarm.getTime();
         if(alarmMSeconds - startingMSeconds > naptime){ sleeping = false; }
      }      
	  return true;
}
   
function array_pop (arr,index) {
	var newarr = [];
	for (i=0;i<arr.length;i++) {
		if (i != index) newarr.push(arr[i]); else continue;
	}
	return newarr;
}

function addVideoToPlaylist (id) {
	if (id) {
		var a = $('plbtn-'+id);
		var c = a.getAttribute ('ref');
		if (c) {
			a.removeClassName ('inactive');	
			a.setAttribute('ref','');
			task='remvideo';
		} else {
			a.addClassName ('inactive');	
			a.setAttribute('ref','set');
			task = 'setvideo';
		}
		new Ajax.Request ('/common/commonXml.php', {parameters:'task='+task+'&videoid='+id});
	}
}

function observeMessenger(){
	checkMessenger();
	setInterval("checkMessenger()",20000);
	//setInterval("checkMessenger()",30000);
}

function positonMessenger(){
	var size = getWindowSize();
	var posittion = getScrollPosition();
	var meg = $('messenger');
	if(posittion[1] > 0){
		Element.setStyle(meg,{left:size[0]-300+'px'});
		Element.setStyle(meg,{top:(size[1]+posittion[1])-135+'px'});
	} else {
		Element.setStyle(meg,{left:size[0]-300+'px'});
		Element.setStyle(meg,{top:size[1]-135+'px'});
	}
}
function checkMessenger(){
	if(MSGACTIVE)
		new Ajax.Updater($('messenger'),'/common/commonXml.php',{postBody: 'task=check-messenger',evalScripts:true});
}
function hideMessenger(){
	jQuery('#messenger').fadeOut('fast');
	MSGACTIVE = true;
}

function callMessenger(){
	MSGACTIVE = false;
	positonMessenger();
	jQuery('#messenger').fadeIn('fast');
	setTimeout('hideMessenger()',10000);
}

function getScrollPosition () {
	var x,y;
	if (self.pageYOffset) {
		x = self.pageXOffset;
		y = self.pageYOffset;
	} else if (document.documentElement && document.documentElement.scrollTop) {
		x = document.documentElement.scrollLeft;
		y = document.documentElement.scrollTop;
	} else if (document.body) {
		x = document.body.scrollLeft;
		y = document.body.scrollTop;
	}
	return new Array (x,y);
}

function getWindowSize(){
	if (self.innerWidth){
		frameWidth = self.innerWidth;
		frameHeight = self.innerHeight;
	} else if (document.documentElement && document.documentElement.clientWidth){
		frameWidth = document.documentElement.clientWidth;
		frameHeight = document.documentElement.clientHeight;
	} else if (document.body) {
		frameWidth = document.body.clientWidth;
		frameHeight = document.body.clientHeight;
	}
	return new Array(frameWidth,frameHeight);
}
function resumeInfoSlideShow() {
	SSACTIVE = true;	
	var area = $('ss-content');
	area.removeClassName ('paused');	
}

function pauseInfoSlideShow () {
	SSACTIVE = false;
	var area = $('ss-content');

	area.addClassName ('paused');
}
	
function startInfoSlideShow () {
	var area = $('ss-content');
	if (area) {
		setInterval ("reloadSlideShowEntry()",4000);
	}
}

function reloadSlideShowEntry () {
	if (SSACTIVE) {
		var area = $('ss-content');
		if (area) {
			jQuery('#ss-content').fadeOut('fast');
			now = new Date();
			seed = now.getSeconds();
			var random_number = Math.random(seed);
			var range = random_number * SSNEWS.length;
			var rounded_number = Math.round(range);
			if (rounded_number == SSNEWS.length){rounded_number = 0}
			var quote = rounded_number;
			area.innerHTML = SSNEWS[quote];
			jQuery('#ss-content').fadeIn('fast');
		}
	}
}

function popUp(URL,w,h,scrollbars,resize) {
	var day = new Date();
	var id = day.getTime();
	var sc = scrollbars ? 1 : 0;
	var rs = resize ? 1 : 0;
	eval("page" + id + " = window.open(URL, '" + id + "', 'toolbar=0,scrollbars="+sc+",location=0,statusbar=0,menubar=0,resizable="+rs+",width="+w+",height="+h+"');");
}

// to open in same window
function popUp2(URL,w,h,scrollbars,resize,windowName) {
	var day = new Date();
	if(windowName===false){
		var windowName = day.getTime();
	}
	var sc = scrollbars ? 1 : 0;
	var rs = resize ? 1 : 0;
	eval("page" + windowName + " = window.open(URL, '" + windowName + "', 'toolbar=0,scrollbars="+sc+",location=0,statusbar=0,menubar=0,resizable="+rs+",width="+w+",height="+h+"');");
}


function SetChecked (form) {
	if (form) {
		var Inputs = form.getElementsByTagName("input");
		for (i=0;i<Inputs.length;i++) {
			Inputs[i].checked = !Inputs[i].checked;
		}
	}	
}

function insertAtCaret(obj, text) {  	
	if(document.selection)	{
		obj.focus();  	
		var orig = obj.value.replace(/\r\n/g, "\n");  	
		var range = document.selection.createRange();  	
		range.text = text;  	
		var actual = tmp = obj.value.replace(/\r\n/g, "\n");  	
	 	
		for(var diff = 0; diff < orig.length; diff++)	
			if(orig.charAt(diff) != actual.charAt(diff)) 
				break;  	
	 	
		for (var index = 0, start = 0;tmp.match(text)&& (tmp = tmp.replace(text, ""))&& index <= diff;index=start + text.length)
			start = actual.indexOf(text, index);  	
    } else if(obj.selectionStart) {
		var start = obj.selectionStart;  	
		var end   = obj.selectionEnd;  	
		obj.value = obj.value.substr(0, start) + text + obj.value.substr(end, obj.value.length);  	
    }  	
	      	
	if(start != null)
		setCaretTo(obj, start + text.length);  	
	else
		obj.value += text;  	
	}  	
	 	
function setCaretTo(obj, pos) {  	
    if(obj.createTextRange) {  	
        var range = obj.createTextRange();  	
        range.move('character', pos);  	
        range.select();  	
    } else if(obj.selectionStart) {  	
        obj.focus();  	
        obj.setSelectionRange(pos, pos);  	
    }  	
} 

function InsertSmiley (smiley, textarea) {
	insertAtCaret (textarea,smiley);
	var smileybar = $('smileys-placeholder');
	Element.setStyle (smileybar,{display:'none'});
}


/**
*
*  Base64 encode / decode
*  http://www.webtoolkit.info/
*
**/
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;  
     }  
   
 } 

function applyRoundBoxes () {
	jQuery(".box").wrap ('<div class="rbxt"><div class="rbxb"><div class="rbxl"><div class="rbxr"><div class="rbxbl"><div class="rbxbr"><div class="rbxtl"><div class="rbxtr"></div></div></div></div></div></div></div></div>');
}

function SetPreview (area,src,imggif) {
	Element.setStyle (area,{display:'block'});
	new Ajax.Updater (area,'/common/commonXml.php',{parameters:'task=preview&src='+Base64.encode(src.value)});
	var img = $(document.createElement ('img'));
	img.src = imggif;
	area.innerHTML = '';
	area.appendChild (img);
}

function disableSmileys (obj,id) {
	var imgs = obj.getElementsByClassName ('smiley');
	for (i=0;i<imgs.length;i++) {
		var el = imgs[i];
		var newChild = document.createElement ('span');
		newChild.appendChild (document.createTextNode(el.getAttribute ('alt')));
		newChild.setAttribute ('dir',el.getAttribute('src'));
		newChild.className='old_smiley';
		obj.replaceChild(newChild, el);
	}
	Element.setStyle ($('rem-sm-link'+id),{display:'none'});
	Element.setStyle ($('en-sm-link'+id),{display:'block'});
}

function enableSmileys (obj,id) {
	var spans = obj.getElementsByClassName ('old_smiley');
	for (i=0;i<spans.length;i++) {
		var el = spans[i];
		var newChild = document.createElement ('img');
		newChild.setAttribute ('src',el.getAttribute('dir'));
		newChild.setAttribute ('alt',el.innerHTML);
		newChild.className = 'smiley';
		obj.replaceChild(newChild, el);		
	}
	Element.setStyle ($('rem-sm-link'+id),{display:'block'});
	Element.setStyle ($('en-sm-link'+id),{display:'none'});
}

accessMovie = function(movieName){
  if (navigator.appName.indexOf ("Microsoft") !=-1) {
    return window[movieName]
  } else {
    return document[movieName]
  }
}

movieIsLoaded = function(movieName) {
  if (typeof(movieName) != "undefined") {
    return movieName.PercentLoaded() == 100;
  } else {
    return false;
  }
}

function callExternalInterface(js_top) {
 accessMovie("colorEditor").SetVariable("js_top", js_top);
 accessMovie("colorEditor").setPos();
}

function loadItem(type,id){ 
    if (id > 0) { 
        var txt = $('msgbody'); 
           insertAtCaret (txt,'\n['+type+']'+id+'[/'+type+']\n') 
         } 
}

function openGallery (gid,pid,uid,reloadParent) {
    if (typeof reloadParent == 'undefined'){
			reloadParent = false;
    }
    if (typeof uid != 'undefined') {
        var task = '&task=galleries';
    }
    if(typeof gid != 'undefined'){
        var task = '';
    }
	//popUp ('http://www.orb.lv/gallery/?gid='+gid+task+'&pid='+pid+'&uid='+uid,1010,710,false,true);
	popUpLink = 'http://www.orb.lv/gallery/?gid='+gid+task+'&pid='+pid+'&uid='+uid;
	if(reloadParent == true){
		popUpLink+='&reload=true';
	}
	popUp (popUpLink,1010,710,false,true);
}

function toggleBox (id) {
     var obj = jQuery('#'+id);
     var lnk = jQuery('#boxlnk-'+id);
     lnk.toggleClass('closed');
     obj.toggle('fast');
     new Ajax.Request ('/common/commonXml.php', {parameters:'task=toggleboxstate&box='+id});
}

function toggleMsgInfo (id) {
     var obj = jQuery('#'+id);
     var lnk = jQuery('#boxlnk-'+id);
     lnk.toggleClass('closed');
     obj.toggle('fast');
     //new Ajax.Request ('/common/commonXml.php', {parameters:'task=toggleboxstate&box='+id});
}
function setNewsRead(){
	new Ajax.Request ('/common/commonXml.php', {parameters:'task=setnewsread'});
}

var LoadingImgGif = 'http://i2.orb.lv/img/common/loading-big.gif';
var FormElements = ['p','ul','table','blockquote','h2','h3','div']; // 26.07.2007 - pieliku 'div' elementu klaat. Bloga formaam un tiem kam 'form-col'

getMsgContId = function(form){
	obj=$A(Form.getInputs (form,'','msgBox'));
	if(obj[0]) {
		val=obj[0].value;
		obj=false;
		return val;
 	}
}

removeChildNodes = function(node)
	{
	while (node.hasChildNodes())
		{
		node.removeChild(node.firstChild);
		}
	}

resetMsgContainer = function(container_id)
	{
	errCont=$(container_id);
	if (errCont)
		{
		Element.hide (errCont);
		removeChildNodes(errCont);
		}
	}

toggleChildNodes = function (obj,unhide,tags) 
	{
	$A(obj.childNodes).each(function(node)
		{
		if (tags.indexOf(node.nodeName.toLowerCase())!=-1)
			{
			var st = (node.nodeName.toLowerCase()=='table'?'table':'block');
			Element.setStyle(node,{display:(unhide?st:'none')});
			}
		}
	);
}

createLoad = function()
	{
	var sm = arguments[0];
	img=document.createElement("img");
	img.src=LoadingImgGif;
	img.id=arguments[1]+'_loading-img';
	Element.addClassName(img,'loading-img');
	return img;
	}

Submit = function(form,handler)
	{
	var show_form = arguments[2];
	var reset_form = arguments[3];
	
	resetMsgContainer (getMsgContId(form));
	toggleChildNodes(form,0,FormElements);
	form.appendChild (createLoad (0,form.id));
	formid=form.id.replace('-box','');
	postStr=Form.serialize(form)+'&task='+formid;
	
	var handlerFunc = function (t) 	{
		form.removeChild($(form.id+'_loading-img'));
		errors = parseResponse(t.responseText,formid);
		
		if ((show_form==1)||(errors))
			toggleChildNodes(form,1,FormElements);
			
		if ((reset_form==1)&&(!errors))
			{
			form.reset();
			}
		}
	new Ajax.Request (handler, {parameters:postStr, onSuccess:handlerFunc, onFailure:AjaxErrFunc});
	}


var AjaxErrFunc = function (t)
	{
	alert('Error ' + t.status + ' -- ' + t.statusText);
	}

parseResponse = function (txt,formid) {
	var tmp = '';
	tmp=txt.split('|');
	var status=tmp[0];
	if (status != 'OK') {
		fields=tmp[1].split(',');
		formError(formid,fields,tmp[2]);
		if (tmp[3])
			eval(tmp[3]);
		return true;
	} else {
		resetFormSuccess(formid,tmp[1]);
		var f=$(formid+'-box');

		if (tmp[2])
			eval(tmp[2]);
		return false;
		}
}
	
formError = function (id,forNames,msg) {
	var form = $(id+'-box');
	if (msg) {
		container_id=getMsgContId(form);
		//alert(id);
		errCont=$(container_id);
		Element.update (errCont,'');
		resetMsgContainer (errCont);
		new Insertion.Top(errCont, msg);
		Element.removeClassName (errCont,'msg-ok');
		Element.addClassName(errCont,'msg-er');
		Element.setStyle(errCont,{display:'block'});
		if(forNames.length==0)
			Element.addClassName(errCont,'msg-ok');
}

	var nodes = $A(form.getElementsByTagName('label'));
	nodes.each(function(node)
		{
		attrValue=node.getAttribute('htmlFor');
		if (!attrValue)
			attrValue=node.getAttribute('for');
	  	Element.removeClassName(node,'error');
  		
		if(forNames.length>0)
			{
  			if(forNames.indexOf(attrValue)!=-1)	
				{
	  			Element.addClassName(node,'error');
				}
		 	}
		 }
	);
}

resetFormSuccess = function (id,msg)
	{
	if(msg)
		{
		form=$(id+'-box');
		var nodes = $A(form.getElementsByTagName('label'));
		nodes.each(function(node)
			{
			Element.removeClassName(node,'error');
			}
		);
 	container_id=getMsgContId(form);
	errCont=$(container_id);
	resetMsgContainer (errCont);
	new Insertion.Top(errCont, msg);
	Element.removeClassName (errCont,'msg-er');
	Element.addClassName(errCont,'msg-ok');
	Element.setStyle(errCont,{display:'block'});
	}
	}




