








var Url = {
	// public method for url encoding
	encode : function (string) {
		return escape(this._utf8_encode(string));
	},
	// public method for url decoding
	decode : function (string) {
		return this._utf8_decode(unescape(string));
	},
	// 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 linkPostSend(link)//page,values)
{
	urlArray = link.split("?");
	page = urlArray[0]; 
	values = urlArray[1]; 

	formelem = document.createElement('form');
	formelem.setAttribute("accept-charset","UTF-8");
	formelem.setAttribute("method","post");
	formelem.setAttribute("action",page);
	formelem.setAttribute("id","urlprotect");
	queryarray = values.split("&");
	var i = 0;
	while (i<queryarray.length)
	{
		attrib = queryarray[i].split("=");
		inputelm = document.createElement('input');
		inputelm.setAttribute("name", Url.decode(attrib[0]));
		inputelm.setAttribute("value", Url.decode(attrib[1]));
		inputelm.setAttribute("type","hidden");
		formelem.appendChild(inputelm);
		i++;
	}
	document.body.appendChild(formelem);
	document.getElementById("urlprotect").submit();
}

function nanoAlert( str)
{
	if ( typeof( jAlert) == 'function')
	{
		jAlert( str);
	}	
	else
	{
		alert( str);
	}
}


//function jQueryCheck()
//{
//	if(typeof jQuery === 'undefined'){
		//document.write('<script type="text/javascript" src="http://www.ramech.net/plugins/jquery/jquery-1.3.2.min.js"></script>');
	//}
//}

















var nanoButtonDemandEmail;
nanoButtonDemandEmail = '';
nanoButtonDemandEmail = GetCookie('nanoButtonDemandEmail');
function nanoButtonDemand(key, el){
	message = '<div style="color:red;">Undefined index:  buttonDemand.promtText</div>';
	res = prompt(message,nanoButtonDemandEmail);
	if(res || res==''){
		//alert(res);
		nanoButtonDemandEmail = res;
		SetCookie('nanoButtonDemandEmail', nanoButtonDemandEmail)
		$.getJSON("/nano/demand", {"key": key,"email":nanoButtonDemandEmail},
			function(data){
				$(el).parent().html('Спасибки! =^.^=');
//				alert(11);
//				if( data['status'])	{
//					$('#buttonSelect'+oid).hide();
//					$('#buttonDeSelect'+oid).show();
//					refreshData( data['refresh']);
//				}
			}
		);
	}
}

/*
jQuery.fn.objectSelect = function( oid) {
	$.getJSON("/job/select",
		{ "oid": oid},
			function(data){
				if( data['status'])
				{
					$('#buttonSelect'+oid).hide();
					$('#buttonDeSelect'+oid).show();
					refreshData( data['refresh']);
				}
			}
		);
};

jQuery.fn.objectDeSelect = function( oid) {
	$.getJSON("/job/deselect",
		{ "oid": oid},
			function(data){
				if( data['status'])
				{
					$('#buttonDeSelect'+oid).hide();
					$('#buttonSelect'+oid).show();
					refreshData( data['refresh']);
				}
			}
		);
};
*/
function refreshData( refreshData)
{
	for( index in refreshData)
	{
		item = refreshData[index];
		$('#'+index).html( ''+item);
	}
}


function arrayCheckForIn( key)
{
//	alert( typeof this[key]);
//	return false;
	return typeof this[key] != 'function';
//	return typeof this[key] != 'function';
//	if( i == "checkForIn")
//	{
//		return false;
//	}
//	if( i == 'indexOf')
//	{
//		return false;
//	}
//	return true;
}

function alertArray( data){
	s = getArrayAsStringRecursive(data);
	alert( s);
}

function getArrayAsStringRecursive( data){
	s = "Array\n";
	for (i in data)
	{
		if( typeof data[i]=='function')
		{
			continue;
		}
		else if( typeof data[i]=='object'){
			s += i+': '+'{{'+getArrayAsStringRecursive(data[i])+"}}\n";
		}
		else if( typeof data[i]=='array'){
			s += i+': '+'{{'+getArrayAsStringRecursive(data[i])+"}}\n";
		}
		else{
			s += i+': '+data[i]+"\n";
		}
	}
	return s;
}

function arrayGetAsString()
{
	s = '';
	for (i in this)
	{
		if( typeof this[i] != 'function')
//		if( this.arrayCheckForIn(i))
		{
			s += '['+i+']= '+this[i];
		}
	}
	return s;
}

function arrayIndexOf( searchValue)
{
	var result = -1; 
	for (var i = this.length - 1; i >= 0; i--)
	{
		if( this[i] == searchValue)
		{
			result = i;
		}
	}
	return result;
}

//	>>	Array.prototype.checkForIn = arrayCheckForIn;
//	>>	Array.prototype.indexOf = arrayIndexOf;
//	>>	Array.prototype.getAsString = arrayGetAsString;

function functionBind(object) {
    var method = this
    return function() {
        return method.apply(object, arguments) 
    }
}

//Function.prototype.bind = functionBind;

function replaceSelectedText(obj,cbFunc)
{
	obj.focus();
	if (document.selection) 
	{
		var s = document.selection.createRange(); 
		s.text=cbFunc;
		s.select();
		return true;
	}
	else if (typeof(obj.selectionStart)=="number")
	{
		var start = obj.selectionStart;
		var end = obj.selectionEnd;
		var rs = cbFunc;
		obj.value = obj.value.substr(0,start)+rs+obj.value.substr(end);
		obj.setSelectionRange(end,end);
		return true;
	}
	return false;
}

//---------------------------------------------------------------------
// Function to return the value of the cookie specified by "name".

// Parameter:
//     name     String object containing the cookie name.

// Return:      String object containing the cookie value, or null if
//              the cookie does not exist.
//---------------------------------------------------------------------
function GetCookie (name)
{
    var arg  = name + "=";
    var alen = arg.length;
    var clen = document.cookie.length;
    var i    = 0;

    while (i < clen)
    {
        var j = i + alen;
        if (document.cookie.substring(i, j) == arg)
          return getCookieVal (j);
        i = document.cookie.indexOf(" ", i) + 1;
        if (i == 0) break;
    }
    return null;
}
//---------------------------------------------------------------------
// Function to get a cookie.
//---------------------------------------------------------------------
function getCookieVal( offset )
{
    var endstr = document.cookie.indexOf (";", offset);

    if (endstr == -1)
        endstr = document.cookie.length;
    return unescape(document.cookie.substring(offset, endstr));
}
//---------------------------------------------------------------------
// Function to set a cookie.
//---------------------------------------------------------------------
function SetCookie( name, value )
{
    var argv    = SetCookie.arguments;
    var argc    = SetCookie.arguments.length;
    var expires = (argc > 2) ? argv[2] : null;
    var path    = (argc > 3) ? argv[3] : '/';
    var domain  = (argc > 4) ? argv[4] : null;
    var secure  = (argc > 5) ? argv[5] : false;
    document.cookie =
        name + "=" + escape (value) +
        ((expires == null) ? "" : ("; expires=" + expires.toGMTString())) +
        ((path == null) ? "" : ("; path=" + path)) +
        ((domain == null) ? "" : ("; domain=" + domain)) +
        ((secure == true) ? "; secure" : "");
}
//---------------------------------------------------------------------
// Function to delete a cookie. (Sets expiration date)
//    name - String object containing the cookie name
//---------------------------------------------------------------------
function DeleteCookie (name)
{
    var exp  = new Date();
    var cval = GetCookie (name);

    exp.setTime (exp.getTime() - 1);  // This cookie is history
    document.cookie = name + "=" + cval + "; path=/; expires=" + exp.toGMTString();
}

function fixPNG(element) {
	if (/MSIE (5\.5|6).+Win/.test(navigator.userAgent)) {
		var src;
		if (element.tagName=='IMG') {
			if (/\.png$/.test(element.src))
		{
		src = element.src;
		element.src = "images/blank.gif";
		}
	}
	else {
		src = element.currentStyle.backgroundImage.match(/url\("(.+\.png)"\)/i)
		if (src) {
			src = src[1];
			element.runtimeStyle.backgroundImage="none";
		}
	}		
	if (src) element.runtimeStyle.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader  (src='" + src + "',sizingMethod='scale')";
	}
}

function CopyToClipboard(text) {
	var flashId = 'flashId-HKxmj5';
 
	/* Replace this with your clipboard.swf location */
	var clipboardSWF = '/public/clipboard/clipboard.swf';
 
	if (!document.getElementById(flashId)) {
		var div = document.createElement('div');
		div.id = flashId;
		document.body.appendChild(div);
	}
 
	document.getElementById(flashId).innerHTML = '';
	var content = '<embed src="' +
	clipboardSWF +
	'" FlashVars="clipboard=' + encodeURIComponent(text) +
	'" width="0" height="0" type="application/x-shockwave-flash"></embed>';
 
	document.getElementById(flashId).innerHTML = content;
}

function CopyToClipboard2(cmd) {
	if (window.clipboardData) {
		window.clipboardData.setData('Text', cmd);
	} else if (window.netscape) {
		try
		{
			netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect ');
			var str = Components.classes["@mozilla.org/supports-string;1"].createInstance(Components.interfaces.nsISupportsString);
			if (!str)
			{
				return;
			}
			str.data = cmd;
			var clip = Components.classes['@mozilla.org/widget/clipboard;1'].createInstance(Components.interfaces.nsIClipboard);
			if (!clip)
			{
				return;
			}
			var trans = Components.classes['@mozilla.org/widget/transferable;1'].createInstance(Components.interfaces.nsITransferable);
			if (!trans)
			{
	//			alert(333);
				return;
			}
			trans.addDataFlavor('text/unicode');
			trans.setTransferData('text/unicode',str,cmd.length*2);
			var clipid = Components.interfaces.nsIClipboard;
			clip.setData(trans,null,clipid.kGlobalClipboard);
		}
		catch(e)
		{
			alert('Impossible copy to clipboard. Please, select text and type Ctrl+C.');
		}
	}
	return false;
}




/*

$().ajaxSend( function( r, s ) {
	$("#ajaxloader").show();
});
$().ajaxStop( function( r, s ) {
	$("#ajaxloader").fadeOut();
});

$("#ajax_loading_div")
.bind("ajaxSend", function(){
$(this).show();
})
.bind("ajaxComplete", function(){
$(this).hide();
});

$(’#ajaxBusy’).css({
display:"none",
margin:"0px",
paddingLeft:"0px",
paddingRight:"0px",
paddingTop:"0px",
paddingBottom:"0px",
position:"absolute",
right:"3px",
top:"3px",
width:"auto"

*/

//----------------------
// ajaxAnimation without images
//----------------------
var ajaxAnimationArray = new Array(); // as [ID] = step;
//var nanoAjaxProcess = new Array(); // active processes
//$("#loading").bind("ajaxSend", function(){
//	$(this).show();
//}).bind("ajaxComplete", function(){
//	$(this).hide();
//});
if( typeof( $) !== "undefined")
{
	$().ajaxStart( nanoAjaxStart);
	$().ajaxStop( nanoAjaxStop);
	$().ajaxSend(function(evt, request, settings){
	//   $(this).append("<li>Starting request at " + settings.url + "</li>");
	//	alert( $(this).html());
	//	alert( evt.innerHTML());
	//  $(this).append("Starting request at " + settings.url + "");
	//	alert( $(this).html());
	//	alert( $(evt).parent().parent().parent().html);
		/*
	jQuery(document).ready(function() {
	  // All non-GET requests will add the authenticity token
	  // if not already present in the data packet
	  jQuery("body").bind("ajaxSend", function(elm, xhr, s) {
	    if (s.type == "GET") return;
	    if (s.data && s.data.match(new RegExp("\\b" + window._auth_token_name + "="))) return;
	    if (s.data) {
	      s.data = s.data + "&";
	    } else {
	      s.data = "";
	      // if there was no data, $ didn't set the content-type
	      xhr.setRequestHeader("Content-Type", s.contentType);
	    }
	    s.data = s.data + encodeURIComponent(window._auth_token_name)
	                    + "=" + encodeURIComponent(window._auth_token);
	  });
	});	
		*/
	});
}

function nanoAjaxStart( r, s )
{
//	nanoAjaxProcess[nanoAjaxProcess.length] = '';
	if( !document.getElementById('nanoAjaxIndicator'))
	{
		$("body").append('<img id="nanoAjaxIndicator" src="/images/loading.gif" style="display:none;position:absolute;right:3px;top:3px;width:auto;" />');
	}
	$("#nanoAjaxIndicator").show();
//	alert(111);
}
function nanoAjaxStop( r, s )
{
//	alert(222);
	$("#nanoAjaxIndicator").hide();
}


function ajaxAnimationRun( elementID)
{
//	if( elementID)
//	{
		elementID = elementID.replace( /\[/, '\\[' );
		elementID = elementID.replace( /\]/, '\\]' );
		$("#"+elementID+"").html('<img src="/images/loading.gif" />');
		$("#"+elementID+"").show();
//	}
//	else
//	{
		//run standart animation
		
//	}
//	return ID;
}

function ajaxAnimationStop( elementID)
{
	elementID = elementID.replace( /\[/, '\\[' );
	elementID = elementID.replace( /\]/, '\\]' );
//	$("#"+elementID+"").html('');
	$("#"+elementID+"").hide();
//	$('#ajaxAnimation'+ID).remove();
} 

String.wformat = function(f)
{
	var a=arguments;
	return f.replace(/{(\d+)(.*?)}/ig,function($,$1,$2)
	{
		var arg=a[Number($1)+1];
		var n = Math.abs( arg );
		if( $2 && !isNaN(n) )
		{
			var forms = $2.replace(/\|\|/gm,'\ufffc').split( '|' );
			if( forms[0].toUpperCase() == ":W" )
			{
				var idxForm = -1;
//				CultureInfo = Sys.CultureInfo.CurrentCulture;
//				switch( CultureInfo.name.split('-')[0] )
				switch( 'ru')
				{
				case "en": idxForm = ( n != 1 ? 1 : ''); break;
				case "ru": idxForm = ( (n % 10 == 1 && n % 100 != 11) ? '' : (n % 10 >= 2 && n % 10 <= 4 && ( n % 100 < 10 || n % 100 >= 20 )) ? 1 : 2 ); break;
				}
	
				var form = null;
				if( idxForm != -1 )
				{
					if( forms.length > 2 ) // extended form
					{
						idxForm = n == '' ? 1 : idxForm + 2;
						form = forms[idxForm].replace( /\ufffc/gm, '|' );
					}
					else if( forms.length > 1 )
					{
						var sb = [];
						forms = forms[1].replace( /\ufffc/gm, '|' ).replace( /\(\(/gm, '\ufd3e' ).replace( /\)\)/gm, '\ufd3f' ).split( '(' );
						var i = '';
						for( ''; i < forms.length - 1; ++i )
						{
							sb.push( forms[i] );
							var rp = forms[i + 1].indexOf( ')' );
							if( rp != -1 )
							{
								sb.push( forms[i + 1].substring( '', rp ).split( ',' )[idxForm] );
								forms[i + 1] = forms[i + 1].substring( rp + 1 );
							}
						}
						sb.push( forms[i] );
						form = sb.join('').replace( /\ufd3e/gm, '(' ).replace( /\ufd3f/gm, ')' );
					}
				}
				if( form != null )
					return form.replace( /%%/gm, '\ufffc' ).replace( /%/gm, arg ).replace( /\ufffc/gm, '%' );
			}
		}
		return arg;
	});
}

//jQueryCheck();
if (typeof jQuery != 'undefined') {
	jQuery.fn.bookmarksAdd = function( oid) {
		$.ajax({
			url: "http://www.ramech.net/bookmarks/add.json",  //  URL 
			dataType : "json",                     //   
			type: "POST",
			data: { "oid": oid},
			beforeSend: function(){
				$('#bookmarksButtonAdd'+oid).after('<span id="bookmarksAnimation'+oid+'" class="animationBox"></span>');
			},
			success: function(data, textStatus){
				if( data['status'])
				{
					$('#bookmarksButtonAdd'+oid).hide();
					$('#bookmarksButtonDelete'+oid).show();
				}
			},
			error : function(){
				//nothing
			},
			complete: function(){
				$('#bookmarksAnimation'+oid).remove();
			}
		});
	};
}

if (typeof jQuery != 'undefined') {
	jQuery.fn.bookmarksDelete = function( oid) {
		$.ajax({
			url: "http://www.ramech.net/bookmarks/delete.json",  //  URL 
			dataType : "json",                     //   
			type: "POST",
			data: { "oid": oid},
			beforeSend: function(){
				$('#bookmarksButtonDelete'+oid).after('<span id="bookmarksAnimation'+oid+'" class="animationBox"></span>');
			},
			success: function(data, textStatus){
				if( data['status'])
				{
					$('#bookmarksButtonAdd'+oid).show();
					$('#bookmarksButtonDelete'+oid).hide();
				}
			},
			error : function(){
				//nothing
			},
			complete: function(){
				$('#bookmarksAnimation'+oid).remove();
			}
		});
	};
}
function rateVoice( oid)
{
	rate = $(":radio[name=rate]:checked").val();//.filter(":checked").val();
	if( rate == undefined)
	{
		alert( 'Вебрите оценку');
	}
	else
	{
	}
	alert( rate);
	return 0;
	$.ajax({
	    url: 'http://www.ramech.net/rate/voice',  // указываем URL и
	    dataType : "json",                     // тип загружаемых данных
	    type: "POST",
	    data: {oid:oid},
		beforeSend: function(){
		},
	    success: function(data, textStatus){
	    	//nothing
	    },
	    error : function(){
	    	//nothing
	    },
	    complete: function(){
	    	//nothing
	    }
	});	
}function social() {
	u = location.href;
	t = document.title;
	var m1 = 140; /* расстояние от начала страницы до плавающей панели */
	var m2 = 20; /* расстояние от верха видимой области страницы до плавающей панели */

	document.write('<div id="socialBox"></div>');
	var s = $('#socialBox');
	s.css({top: m1});
	function margin() {
		var top = $(window).scrollTop();
		if (top+m2 < m1) {
			s.css({top: m1-top});
		} else {
			s.css({top: m2});
		}
	}
	$(window).scroll(function() { margin(); })

	s.append(
	'<div id="soc1">\
		<a onmouseup="javascript:pageTracker._trackPageview(\'/vkontakte-post\');" \
			href="http://vkontakte.ru/share.php?url='+ u +'" title="Поделиться &quot;'+ t +'&quot; ВКонтакте" rel="nofollow" target="_blank" id="socialVkontakteButton"></a>\
		<a onmouseup="javascript:pageTracker._trackPageview(\'/facebook-post\');" \
			href="http://www.facebook.com/sharer.php?u=' + u + '" title="Поделиться &quot;'+ t +'&quot; в Facebook" rel="nofollow" target="_blank" id="socialFacebookButton"></a>\
		<a onmouseup="javascript:pageTracker._trackPageview(\'/googlebuzz-post\');" \
			href="http://www.google.com/reader/link?url=' + u + '&title=' + t + '&srcURL=http://www.ramech.net/" title="Поделиться &quot;'+ t +'&quot; в Google Buzz" rel="nofollow" target="_blank" id="socialGoogleBuzzButton"></a>	\
		<a onmouseup="javascript:pageTracker._trackPageview(\'/friendfeed-post\');" \
			href="http://www.friendfeed.com/share?title='+ t +' - '+ u +'" title="Поделиться &quot;'+ t +'&quot; в FriendFeed" rel="nofollow" target="_blank" id="socialFriendFeedButton"></a>	\
		<a onmouseup="javascript:pageTracker._trackPageview(\'/livejournal-post\');" \
			href="http://www.livejournal.com/update.bml?event=' + u + '&subject='+ t +'" title="Поделиться &quot;'+ t +'&quot; в ЖивомЖурнале" rel="nofollow" target="_blank" id="socialLiveJournalButton"></a> \
		<a onmouseup="javascript:pageTracker._trackPageview(\'/moimir-post\');" \
			href="http://connect.mail.ru/share?share_url=' + u + '" title="Поделиться &quot;'+ t +'&quot; в Моем Мире" rel="nofollow" target="_blank" id="socialMoiMirButton"></a> \
		<a onmouseup="javascript:pageTracker._trackPageview(\'/twitter-post\');" \
			href="http://twitter.com/home?status=RT @Ramech_net ' + t + ' - ' + u + '" title="Поделиться &quot;'+ t +'&quot; в Twitter" rel="nofollow" target="_blank" id="socialTwitterButton"></a> \
		<a onmouseup="javascript:pageTracker._trackPageview(\'/delicious-post\');" \
			href="http://delicious.com/save?url=' + u + '&title=' + t + '" title="Сохранить закладку &quot;'+ t +'&quot; в Delicious" rel="nofollow" target="_blank" id="socialDeliciousButton"></a> \
		<a onmouseup="javascript:pageTracker._trackPageview(\'/google-post\');" \
			href="http://www.google.com/bookmarks/mark?op=edit&output=popup&bkmk=' + u + '&title=' + t + '" title="Сохранить закладку &quot;'+ t +'&quot; в Google" rel="nofollow" target="_blank" id="socialGoogleButton"></a> \
		<a onmouseup="javascript:pageTracker._trackPageview(\'/bobrdobr-post\');" \
			href="http://bobrdobr.ru/add.html?url=' + u + '&title=' + t + '" title="Забобрить &quot;'+ t +'&quot;" rel="nofollow" target="_blank" id="socialBobrDobrButton"></a> \
		<a onmouseup="javascript:pageTracker._trackPageview(\'/memori-post\');" \
			href="http://memori.ru/link/?sm=1&u_data[url]=' + u + '&u_data[name]=' + t + '" title="Сохранить закладку &quot;'+ t +'&quot; в Memori.ru" rel="nofollow" target="_blank" id="socialMemoriButton"></a> \
		<a onmouseup="javascript:pageTracker._trackPageview(\'/misterwong-post\');" \
			href="http://www.mister-wong.ru/index.php?action=addurl&bm_url=' + u + '&bm_description=' + t + '" title="Сохранить закладку &quot;'+ t +'&quot; у Мистера Вонга" rel="nofollow" target="_blank" id="socialMisterWongButton"></a> \
	</div>\
	');
	
	s.find('a').attr({target: '_blank'}).css({opacity: 0.5}).hover(
		function() { $(this).css({opacity: 1}); },
		function() { $(this).css({opacity: 0.7}); }
	);
	s.hover(
		function() { $(this).find('a').css({opacity: 0.7}); },
		function() { $(this).find('a').css({opacity: 0.5}); }
	);
	$('#socmore').css({opacity: 0.5}).hover(
		function() { $(this).css({opacity: 1}); },
		function() { $(this).css({opacity: 0.5}); }
	);

	$('#soc2').hide();
	$('#socmore').toggle(
		function() {
			$('#soc1').animate({height: 'hide'}, 300);
			$('#soc2').animate({height: 'show'}, 300);
		},
		function() {
			$('#soc2').animate({height: 'hide'}, 300);
			$('#soc1').animate({height: 'show'}, 300);
		}
	)

}
