var $j = jQuery;

(function(){
	if(!Prototype.Browser.IE) return;
	var substr = String.prototype.substr;
	String.prototype.substr = function(){
		return arguments[0] < 0 ? substr.call(this,this.length + arguments[0],this.length + (arguments[1] || 0)) : substr.apply(this,arguments)
	};
})();
(function(){
			if(!String.prototype.px)
				String.prototype.px = function(){
						return parseInt(this) ? parseInt(this)  + "px" : "0px";
				};
			if(!Number.prototype.px)
				Number.prototype.px = function(){
						return parseInt(this) + "px";
				};
			if(!String.prototype.toInt)
				String.prototype.toInt = function(){
						return parseInt(this);
				};
})();
Element.addMethods({
	liveHover:function(element,selector,style){

		if(!element || !selector || !style) return;
		var element = $(element);
		element.observe("mouseover",hover).observe("mouseout",hover)
		function hover(event){
			var target = event.findElement(selector);
			if (target){
				switch(event.type){
					case "mouseover": target.addClassName(style);break;
					case "mouseout":  target.removeClassName(style);break;
				};
			}
		}
		return element;
	}
});

(function($){
	$.Bubble = function(){
			bubble = $("<div id='la-bubble'></div>").appendTo(document.body).css({
				"width":"300px",
				"background-color":"#ffffff",
				"position":"absolute",
				"left":"0px",
				"top":"0px",
				"z-index":"9999"
				}).hide().hover(function(){$(this).show();},
					function(){$(this).hide();});
	}

	$.fn.bubble = function(event,content){
		var offset = {x:-10,y:-10};
		$("#la-bubble").html(content);
        /*
		$("#la-bubble")
			.css({
			"left":(offset.x + event.pageX - parseInt($("#la-bubble").css("width"))),
			"top":offset.y + event.pageY}); */
			return this;
	}


$j(function(){
	$.Bubble();
	if ($j(".calendar").size != 0) {
		$j("<img id='tab-loader' src='/i/loader.gif' style='position:absolute;right:5px;top:5px'/>").hide().appendTo(".calendar");
    }
    
    if ($j.datepicker) {
        $j.datepicker.setDefaults({
                dateFormat:"dd.mm.yy",
                changeMonth: true,
                changeYear: true,
                showButtonPanel: true,
                duration: 0
        });
        // DatePicker:initialize
        $j(document.body).click(function(event) {
            var t = event.target;
            if (! $j(t).is("input.set-date") && ! $j(t).is("#ui-datepicker-div") && ! $j(t).parents().filter("#ui-datepicker-div")) {
                $j.datepicker._hideDatepicker();
            };
        });
        $j.datepicker.setDefaults($j.datepicker.regional['ru']);
    }
});


})($j);

/*
var checkFunc = function( e ) {

	e.stop();
	var targetForm = e.element();
	var targetFormId = targetForm.getAttribute("id");
	//alert(targetFormId);
	var submit = false;
	
	$$("#" + targetFormId + " input[type=text], #" + targetFormId + " select, #" + targetFormId + " input[type=checkbox]").each(function(input) {
		if (input.tagName.toUpperCase() == "INPUT") {
			if ( input.getAttribute("type").toUpperCase() == "CHECKBOX" && input.checked ) {
				submit = true;
			} else if ( input.getAttribute("type").toUpperCase() == "TEXT" && !input.getValue().blank() ) {
				submit = true;
			};
		} else if (input.tagName.toUpperCase() == "SELECT") {
			if ( parseInt(input.getValue()) > 0 ) {
				submit = true;
			}
		}
	});
    
	if (submit) {
		targetForm.submit();
	} else {
		alert('Пожалуйста, укажите критерий поиска.');
	};
}
*/

var checkSubmitAction = function( e ) {
	var submit = false;
    $j(e.target).find(":checkbox:checked, :text, select").each(function() {
		if ($j(this).is(":text") && ! $j(this).val().blank()) {
			submit = true;
		} else if ($j(this).is(":checkbox")) {
            submit = true;
        } else if ($j(this).is("select") && parseInt($j(this).val()) > 0) {
            submit = true;
		};
    });

	if (! submit) {
        e.preventDefault();
        alert('Пожалуйста, укажите критерий поиска.');
	};
}
/*
document.observe("dom:loaded", function() {
	if ($("info-search")) {
		$("info-search").observe("submit", checkFunc);
	};
	if ($("user-search")) {
		$("user-search").observe("submit", checkFunc);
	};
});
*/

$j(document).ready(function() {

    $j.fn.extend({
        activate: function() {
            return this.focus().select();
        }
    });

	if ($j("#info-search")) {
		$j("#info-search").submit(checkSubmitAction);
	};
	if ($j("#user-search")) {
		$j("#user-search").submit(checkSubmitAction);
	};
    $j(".img-question").each(function() {
        var text = $j(this).next().html();
        text = '<span class="help"><span class="top_help"></span><span class="bottom_help"><span></span></span><span class="text_help">'+text+'</span></span>';
        $j(this).tooltip({
            left: 0,
            top: 0,
            delay: 0.3,
            showURL: false,
            track: false,    
            bodyHandler: function() {
                return text;
            } 
        });
        $j(this).next().remove();
    });
/*    
    $j("#key.key").click(function(e) {
        e.preventDefault();
        openCms('/people/');
    });
*/ 
    
});

function trim12 (str) {
	var	str = str.replace(/^\s\s*/, ''),
		ws = /\s/,
		i = str.length;
	while (ws.test(str.charAt(--i)));
	return str.slice(0, i + 1);
}

var add = function() {
    $j("<input type=\"file\">").attr({
        name: "attach"+(parseInt($j("#num").val())),
        size: 50
    }).appendTo($j("#files"));
    $j("<br>").appendTo($j("#files"));
    $j("#num").val(parseInt($j("#num").val())+1);
    /*
	var inp=document.createElement('input');
	var br=document.createElement('br');
	inp.setAttribute('name','attach'+(parseInt($('num').value)));
	inp.setAttribute('type','file');
	inp.setAttribute('size',50);
	$('files').appendChild(inp);
	$('files').appendChild(br);
	$('num').value = parseInt($('num').value)+1;
    */
}

function reportError() {
	alert("Error! Could not load the image!");
}

function isInteger(s) {
	var i;
    for (i = 0; i < s.length; i++){   
        // Check that current character is number.
        var c = s.charAt(i);
        if (((c < "0") || (c > "9"))) return false;
    }
    // All characters are numbers.
    return true;
}

var checkSearchField = function(form) {
	var el = form.elements['userId'];
	if (el.value.length < 3) {
		alert('Для поиска введите не менее 3х символов!');
		$j(el).focus();
		return false;
	}
	return true;
}

function openAttachView(newUrl){
	winobj=open(newUrl,"popup","width=500,height=350,left=250,top=250,scrollbars=1,location=0,menubar=0,resizable=1");
	winobj.focus();
}

function openContent(newUrl){
	winobj=open(newUrl,"content","width=980,height=640,left=0,top=0,scrollbars=0,location=0,menubar=0,resizable=1");
	winobj.focus();
}
function openBuilder(newUrl){
	winobj=open(newUrl,"builder","width=980,height=640,left=20,top=20,scrollbars=1,location=0,menubar=0,resizable=1");
	winobj.focus();
}
function openCms(newUrl){
	winobj=open(newUrl,"cms","width=980,height=640,left=20,top=20,scrollbars=1,location=0,menubar=0,resizable=1");
	winobj.focus();
}
function openHelp(newUrl){
	winobj=open(newUrl,"help","width=980,height=640,left=60,top=60,scrollbars=1,location=0,menubar=0,resizable=1");
	winobj.focus();
}
function openDescr(newUrl){
	winobj=open(newUrl,"descr","width=450,height=350,left=20,top=20,scrollbars=1,location=0,menubar=0,resizable=1");
	winobj.focus();
}
function openDescrSize(newUrl,wp,hp){
	winobj=open(newUrl,"_blank","width=" + wp + ",height=" + hp + ",left=20,top=20,scrollbars=1,location=0,menubar=0,resizable=1");
	winobj.focus();
}
function openPopup(newUrl){
	winobj=open(newUrl,"popup","width=400,height=150,left=250,top=250,scrollbars=1,location=0,menubar=0,resizable=1");
	winobj.focus();
    document.getElementById("winobj").style.background = "#ff0000";
}

function UnHide( eThis ){    
  if( eThis.className == 'sc' ){
      eThis.className = 'sc_active';
      eThis.parentNode.parentNode.parentNode.className = '';
  }else{
      eThis.className = 'sc';
      eThis.parentNode.parentNode.parentNode.className = 'cl';
  }
  return false;
}

function folder( tmp ){    
  eThis = document.getElementById(tmp);
  if( eThis.className == 'sc' ){
      eThis.className = 'sc_active';
      eThis.parentNode.parentNode.parentNode.className = '';
  }else{
      eThis.className = 'sc';
      eThis.parentNode.parentNode.parentNode.className = 'cl';
  }
  return false;
}
function Unselect( eThis ){  
  tmp = document.getElementById('ddcontainer');  
  if( eThis.className == 'btn_select_close' ){
      tmp.className = 'ddopen';
      eThis.className = 'btn_select_open';
  }else{
      eThis.className = 'btn_select_close';
      tmp.className = 'ddclose';
  }
  return false;
}


function ddHide(t){  
  tmp_btn = document.getElementById('btn_select');  
  tmp_dd = document.getElementById('ddcontainer');  

  if( tmp_dd.className == 'ddopen' ){
      tmp_btn.className = 'btn_select_close';
      tmp_dd.className = 'ddclose';
      document.request.userMess.value = t.innerHTML; 
  }else{
      tmp_dd.className = 'ddopen';
      tmp_btn.className = 'btn_select_open';
  }
  return false;
}

var flash_version = 7;
function flashdetect(versionRequired)
{   
	var isIE  = (navigator.appVersion.indexOf("MSIE") != -1) ? true : false;
	var isWin = (navigator.appVersion.toLowerCase().indexOf("win") != -1) ? true : false;
	var isOpera = (navigator.userAgent.indexOf("Opera") != -1) ? true : false;	
	if (isIE && isWin && !isOpera)    
	{     
		document.write('<SCRIPT LANGUAGE=VBScript\> \n');
		document.write('on error resume next \n');
		document.write('result=(IsObject(CreateObject("ShockwaveFlash.ShockwaveFlash.'+versionRequired+'"))) \n'); 
		document.write('</SCR'+'IPT\> \n');
		if (result)
			return true;
		else 
			return false;
	}
	else
	{
		if (navigator.plugins["Shockwave Flash 2.0"] || navigator.plugins["Shockwave Flash"]) {
			var swVer2 = navigator.plugins["Shockwave Flash 2.0"] ? " 2.0" : "";
			var flashDescription = navigator.plugins["Shockwave Flash" + swVer2].description;
			var versionMajor=parseInt(flashDescription.charAt(flashDescription.indexOf(".") - 1));
			if (versionRequired <= versionMajor)
				return true;
			else
				return false;
		}
		else 
			return false;
	}   
}

var timeId;
var isDOM=document.getElementById //DOM1 browser (MSIE 5+, Netscape 6, Opera 5+)
var isOpera=isOpera5=window.opera && isDOM //Opera 5+
var isOpera6=isOpera && window.print //Opera 6+
var isOpera7=isOpera && document.readyState //Opera 7+
var isMSIE=document.all && document.all.item && !isOpera //Microsoft Internet Explorer 4+
var isMSIE5=isDOM && isMSIE //MSIE 5+
var isNetscape4=document.layers //Netscape 4.*
var isMozilla=isDOM && navigator.appName=="Netscape" //Mozilla или Netscape 6.*}'

/* popup */
function openDescriptionWindow( url, width, height, event ) {
	Event.stop(event);
	var $this = $('DescriptionContainer');
    $(document.body).appendChild($this);
	var frameS = '<iframe src="' + url + '" width="' + width + '" height="' + height + '" name="DescriptionIframe" id="DescriptionIframe" frameborder="0" marginheight="0" marginwidth="0"></iframe>';
	$this.innerHTML = frameS;
	var cur = Event.pointer(event),
		dwidth = document.viewport.getWidth(),
		dheight = document.viewport.getHeight(),
		sheight = document.viewport.getScrollOffsets()[1];
	
	$this.style.left = cur.x + 'px';
	$this.style.top = cur.y + 'px';
	$this.style.zIndex = 9000;
    
	if ((cur.x + width) > document.body.clientWidth) {
		$this.style.left = (parseInt($this.style.left) - width) + 'px';
	}

	/*if ((cur.y + height) > document.body.clientHeight) {
		$this.style.top = (parseInt($this.style.top) - height) + 'px';
	}*/
	
	/*if((dwidth - $this.viewportOffset()[0] - $this.getWidth()) < 0) 
	$this.style.left = parseInt($this.style.left) + (dwidth - $this.viewportOffset()[0] - $this.getWidth()) + "px";
	
	
	if((dheight - $this.viewportOffset()[1] - $this.getHeight()) < 0)
	$this.style.top = parseInt($this.style.top) + (dheight - $this.viewportOffset()[1] - $this.getHeight()) + "px";
        */
	// make it visible
	$this.style.visibility = 'visible';
}

function getX( width, event ) {
	var x = Event.pointer(event).x;
	return x;
}

function getY( height, event ) {
	var y = Event.pointer(event).y;
	return y;

}

function closeDescriptionWindow() {
	$('DescriptionContainer').style.visibility = 'hidden';    
}


function reloadParentWindow() {
    closeDescriptionWindow();
    window.location.reload();
}

function printProperties( obj ) {
	var s = '';
	for( var i in obj ) {
		s += i + '=' + obj[i] + '<br>\n';
	}
	var w = window.open();
	w.document.open();
	w.document.write(s);
	w.document.close();
}

function closeFrame(){
	if ( ( window.parent ) && (window.parent.closeDescriptionWindow) ) {
		window.parent.closeDescriptionWindow();
	}	
}

function reloadParent(){
	if ( ( window.parent ) && (window.parent.reloadParentWindow) ) {
		window.parent.reloadParentWindow();
	}	
}

function ddAvatar(t){  
  tmp_img = document.getElementById(t);  
  lnk = t + '-link';
  tmp_lnk = document.getElementById(lnk);    

  if( tmp_img.className == '' ){
      tmp_img.className = 'rollOn';
	  tmp_lnk.className = 'friendName active';
  }else{
      tmp_img.className = '';
	  tmp_lnk.className = 'friendName';
  }
  return false;
}

function dddAvatar(t){  
  tmp_img = document.getElementById(t);  
  lnk = t + '-link';
  tmp_lnk = document.getElementById(lnk);    

  if( tmp_img.className == '' ){
      tmp_img.className = 'rollOn';
	  tmp_lnk.className = 'friendName active';
  }else{
      tmp_img.className = '';
	  tmp_lnk.className = 'friendName';
  }
  return false;
}

function openMessage(newUrl, userIdParam){
	var winname = 'popup'+Math.ceil(Math.random()*10000);
	winobj=window.open(newUrl,winname,"width=650,height=605,left=240,top=120,scrollbars=auto,location=0,menubar=0,resizable=yes");
	winobj.focus();
    if ($j("#newNotice")) {
        $j("#newNotice").submit();
    }
  
    if (userIdParam) {
        var userId = userIdParam;
        if ($j("#user-" + userId)) {
            $j("#user-" + userId).hide();
            $j("#user-" + userId).next().hide();
            var newCount = parseInt($j("#count-unreaded").html()) - parseInt($j("#user-unread-" + userId).html());
            $j("#count-unreaded").html(newCount);
        }
    }
  
    /*
    if (userIdParam) {
        if ($j("#fromUserId") && $j("#newNotice") && $j("#fromUserId").val() == userIdParam) {
            $j("#newNotice").submit();
        }
        
        var userId = userIdParam;
        if ($j("#user-" + userId)) {
            $j("#user-" + userId).hide();
            $j("#user-" + userId).next().hide();

            var newCount = parseInt($j("#count-unreaded").html()) - parseInt($j("#user-unread-" + userId).html());
            $j("#count-unreaded").html(newCount);
        }
    } else if ($j("#fromUserId")) {
        if ($j("#newNotice")) {
            $j("#newNotice").submit();
        }
    
        var userId = (userIdParam) ? $j("#fromUserId").val() : userIdParam;
        if ($j("#user-" + userId)) {
            $j("#user-" + userId).hide();
            $j("#user-" + userId).next().hide();

            var newCount = parseInt($j("#count-unreaded").html()) - parseInt($j("#user-unread-" + userId).html());
            $j("#count-unreaded").html(newCount);
        }
    }
    */
}
function openMessageNotice(newUrl){
	var winname = 'popup'+Math.ceil(Math.random()*10000);
	winobj=open(newUrl,winname,"width=800,height=600,left=240,top=120,scrollbars=0,location=0,menubar=0,resizable=0");
	winobj.focus();
	$('newNotice').submit();
}

function messageWindowClose()
{
	window.opener.location.reload();
	window.close();
}
function checkBlacklist()
{
	$('removeOn').value = 'no';
	$('blacklistOn').value = 'on';
	$('removeForm').submit();
}

function checkMessageWindow(form, button)
{
    var regexp = new RegExp(/<img(.*?)src="(.*?)\/tinymce\/plugins\/emotions\/smiles\/(.*?)"(.*?)>/gi);
    var isSmily = regexp.test(tinyMCE.get('message').getContent());

	if (tinyMCE.get('message').getContent().replace(/\&nbsp\;|<\/?[^>]+>/gi, '').blank() && ! isSmily)
	{
		alert('Введите текст сообщения.');
		return false;
	} else {
        $(button).setAttribute('disabled', 'disabled');
		$('message').value = tinyMCE.get('message').getContent();
		form.submit();
	}
	return false;
}

document.observe("dom:loaded",function (){
	if( !$("female") || !$("male") || !$("c-word")) return;

	if ($("female").checked) $("c-word").update("согласна");

	$("female").observe("click",function(){
		if(this.checked)	$("c-word").update("согласна");
	});
	$("male").observe("click",function(){
		if(this.checked)	$("c-word").update("согласен");
	});
});



//*** This code is copyright 2003 by Gavin Kistner, gavin@refinery.com
//*** It is covered under the license viewable at http://phrogz.net/JS/_ReuseLicense.txt
//*** Reuse or modification is free provided you abide by the terms of that license.
//*** (Including the first two lines above in your source code satisfies the conditions.)
//***Cross browser attach event function. For 'evt' pass a string value with the leading "on" omitted
//***e.g. AttachEvent(window,'load',MyFunctionNameWithoutParenthesis,false);
function AttachEvent(obj,evt,fnc,useCapture){
	if (!useCapture) useCapture=false;
	if (obj.addEventListener){
		obj.addEventListener(evt,fnc,useCapture);
		return true;
	} else if (obj.attachEvent) return obj.attachEvent("on"+evt,fnc);
	else{
		MyAttachEvent(obj,evt,fnc);
		obj['on'+evt]=function(){ MyFireEvent(obj,evt) };
	}
} 
//The following are for browsers like NS4 or IE5Mac which don't support either
//attachEvent or addEventListener
function MyAttachEvent(obj,evt,fnc){
	if (!obj.myEvents) obj.myEvents={};
	if (!obj.myEvents[evt]) obj.myEvents[evt]=[];
	var evts = obj.myEvents[evt];
	evts[evts.length]=fnc;
}
function MyFireEvent(obj,evt){
	if (!obj || !obj.myEvents || !obj.myEvents[evt]) return;
	var evts = obj.myEvents[evt];
	for (var i=0,len=evts.length;i<len;i++) evts[i]();
}
//debug toolbar
var debugToolbar = {

	// current toolbar section thats open
	current: null,
	
	// current vars and config section open
	currentvar: null,
	
	// current config section open
	currentli: null,
	
	// toggle a toolbar section
	show : function(obj) {
		if (obj == debugToolbar.current) {
			debugToolbar.off(obj);
			debugToolbar.current = null;
		} else {
			debugToolbar.off(debugToolbar.current);
			debugToolbar.on(obj);
			debugToolbar.current = obj;
		}
	},
	
	// toggle a vars and configs section
	showvar : function(li, obj) {
		if (obj == debugToolbar.currentvar) {
			debugToolbar.off(obj);
			debugToolbar.currentli = null;
			debugToolbar.currentli.className = '';
			debugToolbar.currentvar = null;
		} else {
			debugToolbar.off(debugToolbar.currentvar);
			if (debugToolbar.currentli)
				debugToolbar.currentli.className = '';
			debugToolbar.on(obj);
			debugToolbar.currentvar = obj;
			debugToolbar.currentli = li;
			debugToolbar.currentli.className = 'active';
		}
	},
	
	// turn an element on
	on : function(obj) {
		if (document.getElementById(obj) != null)
			document.getElementById(obj).style.display = '';
	},
	
	// turn an element off
	off : function(obj) {
		if (document.getElementById(obj) != null)
			document.getElementById(obj).style.display = 'none';
	},
	
	// toggle an element
	toggle : function(obj) {
		if (typeof obj == 'string')
			obj = document.getElementById(obj);
			
		if (obj)
			obj.style.display = obj.style.display == 'none' ? '' : 'none';
	},
	
	// close the toolbar
	close : function() {
		document.getElementById('debug-bar').style.display = 'none';
	},
	
	swap: function() {
		var toolbar = document.getElementById('debug-toolbar');
		if (toolbar.style.right) {
			toolbar.style.left = '0px';
			toolbar.style.right = null;
		} else if (toolbar.style.left) {
			toolbar.style.left = null;
			toolbar.style.right = null;
		} else {
			toolbar.style.left = null;
			toolbar.style.right = '0px';
		}
	}

};


