(function(jQuery){
	jQuery.each(['backgroundColor', 'borderBottomColor', 'borderLeftColor', 'borderRightColor', 'borderTopColor', 'color', 'outlineColor'], function(i,attr){
		jQuery.fx.step[attr] = function(fx){
			if ( fx.state == 0 ) {
				fx.start = getColor( fx.elem, attr );
				fx.end = getRGB( fx.end );
			}
			fx.elem.style[attr] = "rgb(" + [
				Math.max(Math.min( parseInt((fx.pos * (fx.end[0] - fx.start[0])) + fx.start[0]), 255), 0),
				Math.max(Math.min( parseInt((fx.pos * (fx.end[1] - fx.start[1])) + fx.start[1]), 255), 0),
				Math.max(Math.min( parseInt((fx.pos * (fx.end[2] - fx.start[2])) + fx.start[2]), 255), 0)
			].join(",") + ")";
		}
	});
	function getRGB(color) {
		var result;
		if ( color && color.constructor == Array && color.length == 3 )
			return color;
		if (result = /rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/.exec(color))
			return [parseInt(result[1]), parseInt(result[2]), parseInt(result[3])];
		if (result = /rgb\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*\)/.exec(color))
			return [parseFloat(result[1])*2.55, parseFloat(result[2])*2.55, parseFloat(result[3])*2.55];
		if (result = /#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/.exec(color))
			return [parseInt(result[1],16), parseInt(result[2],16), parseInt(result[3],16)];
		if (result = /#([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])/.exec(color))
			return [parseInt(result[1]+result[1],16), parseInt(result[2]+result[2],16), parseInt(result[3]+result[3],16)];
		return colors[jQuery.trim(color).toLowerCase()];
	}
	function getColor(elem, attr) {
		var color;
		do {
			color = jQuery.curCSS(elem, attr);
			if ( color != '' && color != 'transparent' || jQuery.nodeName(elem, "body") )
				break; 
			attr = "backgroundColor";
		} while ( elem = elem.parentNode );
		return getRGB(color);
	};
	var colors = {
		aqua:[0,255,255],
		azure:[240,255,255],
		beige:[245,245,220],
		black:[0,0,0],
		blue:[0,0,255],
		brown:[165,42,42],
		cyan:[0,255,255],
		darkblue:[0,0,139],
		darkcyan:[0,139,139],
		darkgrey:[169,169,169],
		darkgreen:[0,100,0],
		darkkhaki:[189,183,107],
		darkmagenta:[139,0,139],
		darkolivegreen:[85,107,47],
		darkorange:[255,140,0],
		darkorchid:[153,50,204],
		darkred:[139,0,0],
		darksalmon:[233,150,122],
		darkviolet:[148,0,211],
		fuchsia:[255,0,255],
		gold:[255,215,0],
		green:[0,128,0],
		indigo:[75,0,130],
		khaki:[240,230,140],
		lightblue:[173,216,230],
		lightcyan:[224,255,255],
		lightgreen:[144,238,144],
		lightgrey:[211,211,211],
		lightpink:[255,182,193],
		lightyellow:[255,255,224],
		lime:[0,255,0],
		magenta:[255,0,255],
		maroon:[128,0,0],
		navy:[0,0,128],
		olive:[128,128,0],
		orange:[255,165,0],
		pink:[255,192,203],
		purple:[128,0,128],
		violet:[128,0,128],
		red:[255,0,0],
		silver:[192,192,192],
		white:[255,255,255],
		yellow:[255,255,0]
	};
})(jQuery);
(function($){$.browserTest=function(a,z){var u='unknown',x='X',m=function(r,h){for(var i=0;i<h.length;i=i+1){r=r.replace(h[i][0],h[i][1]);}return r;},c=function(i,a,b,c){var r={name:m((a.exec(i)||[u,u])[1],b)};r[r.name]=true;r.version=(c.exec(i)||[x,x,x,x])[3];if(r.name.match(/safari/)&&r.version>400){r.version='2.0';}if(r.name==='presto'){r.version=($.browser.version>9.27)?'futhark':'linear_b';}r.versionNumber=parseFloat(r.version,10)||0;r.versionX=(r.version!==x)?(r.version+'').substr(0,1):x;r.className=r.name+r.versionX;return r;};a=(a.match(/Opera|Navigator|Minefield|KHTML|Chrome/)?m(a,[[/(Firefox|MSIE|KHTML,\slike\sGecko|Konqueror)/,''],['Chrome Safari','Chrome'],['KHTML','Konqueror'],['Minefield','Firefox'],['Navigator','Netscape']]):a).toLowerCase();$.browser=$.extend((!z)?$.browser:{},c(a,/(camino|chrome|firefox|netscape|konqueror|lynx|msie|opera|safari)/,[],/(camino|chrome|firefox|netscape|netscape6|opera|version|konqueror|lynx|msie|safari)(\/|\s)([a-z0-9\.\+]*?)(\;|dev|rel|\s|$)/));$.layout=c(a,/(gecko|konqueror|msie|opera|webkit)/,[['konqueror','khtml'],['msie','trident'],['opera','presto']],/(applewebkit|rv|konqueror|msie)(\:|\/|\s)([a-z0-9\.]*?)(\;|\)|\s)/);$.os={name:(/(win|mac|linux|sunos|solaris|iphone)/.exec(navigator.platform.toLowerCase())||[u])[0].replace('sunos','solaris')};if(!z){$('html').addClass([$.os.name,$.browser.name,$.browser.className,$.layout.name,$.layout.className].join(' '));}};$.browserTest(navigator.userAgent);})(jQuery);
		$(document).ready(function(){
			$('body').addClass($.os.name).addClass($.browser.name).addClass($.browser.className);
			function colorizer()
			{
				$('#colorizer,#phone').animate({'color':'#EC720D'},5000).animate({'color':'#07A8F9'},5000).animate({'color':'#E1E9EB'},5000,function(){colorizer();});
			}
			colorizer();
			$('#orey img.show').animate({'opacity':'0'},0);
			$('#orey').hover(function(){
				$(this).find('img.show').animate({'opacity':'1'},400);
				$('#orey_more').show(200);
			},function(){
				$(this).find('img.show').animate({'opacity':'0'},400);
				$('#orey_more').hide(200);
			});
			
			$('#pitf img.show').animate({'opacity':'0'},0);
			$('#pitf').hover(function(){
				$('#opitf_more').show(200);
				$(this).find('img.show').animate({'opacity':'1'},400);
			},function(){
				$('#opitf_more').hide(200);
				$(this).find('img.show').animate({'opacity':'0'},400);
			});
			
			$('#bd img.show').animate({'opacity':'0'},0);
			$('#bd').hover(function(){
				$(this).find('img.show').animate({'opacity':'1'},400);
			},function(){
				$(this).find('img.show').animate({'opacity':'0'},400);
			});
			$('#orey_more, #opitf_more').hide(0);
			$('#pitf_m_0, #orey_m_0').hide(0);
			$('#orey_m').hover(function(){$('#orey_m_0').show(50);},function(){$('#orey_m_0').hide(50);});
			$('#pitf_m').hover(function(){$('#pitf_m_0').show(50);},function(){$('#pitf_m_0').hide(50);});
			if (/MSIE (\d+\.\d+);/.test(navigator.userAgent)){$('#bd img.show').css({'top':'0px'});}else{$('#bd img.show').css({'top':'-35px'});}
		});

// дефолтный объект state генерится в _overrides.php


function formatItem(row) {
    return row[0];
}

function formatResult(row) {
    return row[0].replace(/(<.+?>)/gi, '');
}



$(document).ready(function() {


/* init */

$('#country .replace').remove(); // убираем сообщение о том, что нужен JS

$('a.valutes_del').css({'opacity':'0.1'});

$('#country a.country').click(function(){return false});

if(typeof(state) != 'undefined'){

	if(state['cur_type'] == 'code'){
		$('#country .show_name').hide();
		$('#country .show_code').show();
	} else {
		$('#show_switch a.show_code').removeClass('sel');
		$('#show_switch a.show_name').addClass('sel');
		$('#country .show_code').hide();
		$('#country .show_name').show();
	}


	if(state['rbc'] == 0){
		$('#rbc .minus').removeClass('minus').addClass('plus').css({'top':'-15px'});
		$('#rbc').css({
				'height':'50px'});
		if(cmsBrowser.ie){

			$('#rbc_hidden').css({
					'height':'50px',
					'top':'-240px'
			});

		} else {

			$('#rbc_hidden').css({
				'height':'50px',
				'top':'-220px'
			});

		}

  } else {

		$('#rbc .minus').css({
				'top':'0px'
		});
		$('#rbc').css({
				'height':'260px'
		});
		$('#rbc_hidden').css({
				'height':'0px',
				'top':'0px'
		});

	}


    if(state['head'] == 0){
		 $('#head .minus').removeClass('minus').addClass('plus').css({
					'top':'-140px'
			}, 'normal');
			$('#head').css({
					'height':'50px'
			}, 'normal');
			$('#head_hidden').css({
					'height':'50px',
					'top':'-160px'
			}, 'normal');
		} else {
			$('#head .minus').css({
					'top':'0px'
			});
			$('#head').css({
					'height':'190px'
			});
			$('#head_hidden').css({
					'height':'0px',
					'top':'0px'
			});
    }


		$('#valutes .row').each(function(){
			var secondclass = $(this).attr('class').split(' ')[1];
			if(jQuery.inArray(secondclass, state['curs']) < 0)
				$('#valutes .row.'+secondclass).remove();
		})
		
		var i;
    var temp = new Array();
    for ( i in state['curs']){
			if($('#valutes .row.'+i).length == 0)
	    	temp.push(i);
    }
    if(temp.length)
			add_country(temp, true);
    delete temp;

}

  if(cmsBrowser.ie)
		$("#country .link").css('background-color','#ffffff');

	
/* REFRESH */

	var refresh_fn = function(){
			
		  cmsAjax(
				'/modules/xcur_' + xcurid + '/includes/check_new.php', // backend
			{ 
				'time': $('#lctime').val()
			},
			function(res) {
				
				if(res.refresh){
					$('#lctime').val(res.refresh);
					
					time =  new Date(res.refresh*1000);
					minutes = time.getMinutes();
					if (minutes < 10)
  					minutes = "0" + minutes
					$('#refresh span').text(time.getHours()+':'+minutes);
				}
				
				if(res.time){
					
					var st = res.time * 1000;
					$('#head .clock').show().jclock({seedTime: st});

				}
				
				if (res.reload) {
			     window.location.reload();
				}
			
			});

	}
	
	refresh_fn();
	var refresh = setInterval('refresh_fn()', 60*10*1000);





// add country to a main list
function add_country(id, checkvolumes){

  cmsAjax(
	'/modules/xcur_' + xcurid + '/index.php', // backend
	{
	    'action' : 'add',
	    'id': id
	},
	function(res) { // ONREADYSTATE

	    if($('#valutes .row.'+id).length > 0){ // замена работает только для одной валюты

				$('#valutes .row.'+id).replaceWith(res.html);

	    } else {
				$('#valutes').append(res.html);

				$('#valutes .row.'+id).hide().slideDown('slow');
				$('#country .course_hover').animate({
						opacity:0,
						top:'100px',
						left:'50px'
				},'slow','linear',function(){
						$(this).css({
							display:'none',
							opacity:1
						})
		    });

	    }

			$('#valutes a.valutes_del').css('opacity','0.1');

	if(checkvolumes) // проверка и установка активного объема добавленных валют
		for ( i in state['curs'] ){
		    if(state['curs'][i] != 1){

					$('#valutes .row.'+i+' .price1 a').each(function(){ // кликаем на ссылку нужного объема
					    if(!$(this).hasClass('act') && $(this).text().slice(1) == state['curs'][i])
						$(this).click();
					});

		    }
		}

	    $('table.fheight').css('height','100%');

	    if(!state['curs'][id]){
				var rstate = eval('(' + res.state + ')'); // добавляем валюты
				for(i in rstate)
				    state['curs'][i] = parseInt(rstate[i]);
	    }


	}
    );
}


/* наведение на валюту в списке валют  */
contry_link_over = function() {
	w = $("#country .course_hover");
	w.stop().hide().css('opacity',1);
	offset = $(this).offset( );
	
	var id = 1;
	var classes = $(this).attr('class').split(' ');
	for (i in classes)
	    if(classes[i].indexOf('cur')>-1)
		id = classes[i];



	/* fill details */
	if(state['cur_type'] == 'code'){

	    $("#country .course_hover .name").css({
		'background-image': 'url(' + currencies[id]['flag'] + ')'
		}).text(currencies[id]['lcode']);
			$("#country .course_hover .descr").html(currencies[id]['description']);
			
	} else {

	    $("#country .course_hover .name").css({
		'background-image':'none'}).html(currencies[id]['description']);

	}

	$("#country .course_hover .buy .value").text(currencies[id]['buy']);
	$("#country .course_hover .sell .value").text(currencies[id]['sell']);

	if($('#valutes .row.'+id).length > 0)
	    $('#country .course_hover .add').hide();
	else
	    $('#country .course_hover .add').show();

	/* modify hover links*/
	$('#country .course_hover .add').attr('href','#'+id);
	$('#country .course_hover .desc').attr('href','/detailed/'+id+'.' + xcurid + '.html');
				
	/* show */
	w.css({
	    'display':'block',
	    'left': offset.left+'px',
	    'top': offset.top+'px'
	    });
				
if (w.length) {
  if (offset.left > 950-240) {
		// сдвигаем влево от правого края экрана
		col = $(this).parent();
		left = w.width() - col.width() - col.css("margin-right").slice(0, col.css("margin-right").length - 2);
		w.css("left", offset.left-left+"px");

		if(state['cur_type'] == 'code')
		    correcting = left+40; // поправка от флага и сдвига
		else
		    correcting = 5;

		//подвигаем флаг на место подложки
		w.find('.name').css({
		    'padding-left':correcting+'px',
		    'background-position':(left+5)+'px 5px'
	    });

  } else {
		if(state['cur_type'] == 'code')
		    correcting = 40;
		else
		    correcting = 5;

		if(!cmsBrowser.ie)
			w.children(".inner").css("left", "-5px");
		else
			w.css({"margin-left": "-5px", 'margin-top': '-5px'});
		
		w.find('.name').css({
		    'padding-left':correcting+'px',
		    'background-position':'5px 5px'
		});
						
    }
				
	}
}
		
    $("#country .link").mouseover(contry_link_over);
		
    $(".course_hover").mouseleave(
	function() {
	    $(this).hide();
	}
	);
	
	
    /* input cleaning */

    $('input.input_code, #search_currency').focus(function(){
	var tis = $(this);
	if(tis.attr('title') == '')
	    tis.attr('title', tis.val()).val('');
			
					
    });
				
    $('input.input_code, #search_currency').blur(function(){
	var tis = $(this);
	if(tis.attr('title') != '' && jQuery.trim(tis.val()) == '')
	    tis.val(tis.attr('title')).attr('title','');
	
    });


    /* personal form, загрузка */
		
    $('#personal form').submit(function(){
	if($('.input_code').val() == 'кодовое слово' || jQuery.trim($('.input_code').val()) == ''){
	    nme = '';
	    return false;
				
	}
	else
	    nme = $('.input_code').val();
			
	$(this).attr('action','/code/'+ nme +'.html');

    });
		
		
    $('#personal_submit').click(function(){
	$('#personal form').submit();
	return false;
    });

    if(cmsBrowser.ie6){
	$('#personal_submit').keyup(function(e){
	    if (e.which == "13") { //Enter
		$('#personal form').submit();
	    }
	});
    }


    $('#save_submit').click(function(e){
	cmsAjax(
	    '/modules/code/save_state.php', // backend
	    {
			'state': state
	    },
	    function(res)
		{
			$('div#word').empty().append(res.word);
			$('div.yCode').modal({
					close: false,
					position: ["25px",],
					overlayId: 'order-overlay',
					containerId: 'order-container'
			});
	    }
	    );
		
			
    });
	
	
	
		$('a.schema').click(function(e){ // карта проезда
			e.preventDefault();
			$.get("/pages/gmap.php", function(data){

				$(data).modal({
					close: false,
					position: ["25px",],
					overlayId: 'order-overlay',
					containerId: 'order-container'
				});
		
			});
	  	});
	  	
	  	$('a.schema_new').click(function(e){ // карта проезда
			e.preventDefault();
			var lnk=$(this).attr("href");
			$.get(lnk, function(data){

				$(data).modal({
					close: false,
					position: ["25px",],
					overlayId: 'order-overlay',
					containerId: 'order-container'
				});
				return false;
			});
	  	});
	  	
	  	




    /* ORDER */

    $('#order_link').click(function(e){
			e.preventDefault();
			$.get("/pages/order.php", function(data){
					
		    $(data).modal({
					close: false,
					position: ["25px",],
					overlayId: 'order-overlay',
					containerId: 'order-container'
  			});

	    $('#form_send_1_currency').autocomplete("/modules/xcur_" + xcurid + "/includes/getcodes.php", {
					    'width': 260,
					    'delay': 100,
					    'selectFirst': true,
					    'highlight': false,
					    'extraParams': {'obj_type':'country' },
					    formatItem: formatItem,
					    formatResult: formatResult
			    });
		
			}
			);
		
  });

    $('#order-overlay').live('click',function(){
			$('.modalCloseX').click();
    });



	$('a.schema').click(function(e){ // карта проезда
		e.preventDefault();
		$.get("/pages/gmap.php", function(data){

			$(data).modal({
				close: false,
				position: ["25px",],
				overlayId: 'order-overlay',
				containerId: 'order-container'
	    });
	
		}
		);
  });










    /* forming page */


    $('#head .minus, #head .plus').live('click', function(){ // шапка, скрытие/показ

	if($(this).hasClass('minus')){
	    $(this).removeClass('minus').addClass('plus').animate({
		'top':'-140px'
	    }, 'normal');
	    $('#head').animate({
		'height':'50px'
	    }, 'normal');
	    $('#head_hidden').animate({
		'height':'50px',
		'top':'-160px'
	    }, 'normal');

	    if(typeof(state) != 'undefined')
		state['head'] = 0; // запись в общий массив

	} else {
	    $(this).removeClass('plus').addClass('minus').animate({
		'top':'0px'
	    }, 'normal');
	    $('#head').animate({
		'height':'188px'
	    }, 'normal');
	    $('#head_hidden').animate({
		'height':'0px',
		'top':'0px'
	    }, 'normal');

	    if(typeof(state) != 'undefined')
		state['head'] = 1;

	}

	return false;
    });

    $('#rbc .minus, #rbc .plus').live('click', function(){ // рбк, скрытие/показ

	if($(this).hasClass('minus')){
	    $(this).removeClass('minus').addClass('plus').animate({
		'top':'-15px'
	    }, 'normal');
	    $('#rbc').animate({
		'height':'50px',
		'padding-top':'5px'
	    }, 'normal');
			
			if(cmsBrowser.ie){
				
				$('#rbc_hidden').animate({
					'height':'50px',
					'top':'-240px'
	  	  }, 'normal');
			
			} else
			
	    $('#rbc_hidden').animate({
				'height':'50px',
				'top':'-220px'
	    }, 'normal');
			

	    if(typeof(state) != 'undefined')
		state['rbc'] = 0;

	} else {
	    $(this).removeClass('plus').addClass('minus').animate({
		'top':'0px'
	    }, 'normal');
	    $('#rbc').animate({
		'height':'260px'
	    }, 'normal');
	    $('#rbc_hidden').animate({
		'height':'0px',
		'top':'0px'
	    }, 'normal');

	    if(typeof(state) != 'undefined')
		state['rbc'] = 1;

	}

	return false;
    });
	

    /* VALUTES */
		
		// Клик по валюте
		$('.col.val').live('click', function(){
			
			var val_id = $(this).parent().attr('class').split('_')[1];
			window.location.replace('/detailed/cur_' + val_id + '.' + xcurid + '.html');

		});


    // переключение объемов
    $('#valutes .col a').live('click', function(){
	var tis = $(this);
	if(!tis.hasClass('act')){

	    tis.addClass('act').siblings('b').fadeOut('fast',function(){
		$(this).text(tis.attr('title'));
	    }).fadeIn('fast');
	    tis.siblings('a').removeClass('act');

	    tis.parent('div.col').siblings('div.col').find('a[href='+tis.attr('href')+']').click();
	    
	    var id = tis.closest('div.row').attr('class').slice(4); // берем id валюты
	    
	    if(typeof(state) != 'undefined')
		state['curs'][id] = tis.text().slice(1);
	    
	    
	}

	return false;
    });



    // удаление валюты из списка валют
    $('a.valutes_del').live('mouseover', function(){
	if($('#valutes .row').length > 2){
	    $('a.valutes_del').stop().css({
		'opacity':'0.1'
	    });
	    $(this).stop().fadeTo('normal',1);
	}
    });

    $('a.valutes_del').live('mouseout', function(){
	$(this).fadeTo('normal',0.1);
    });

    $('a.valutes_del').live('click',function(){
	if($('#valutes .row').length > 2){

	    $(this).parents('div.row').slideUp('slow',function(){
		$(this).remove();
		var vopr_obj = $('table.fheight');

		vopr_obj.css({
		    'height': ($('#valutes .row').length * 77) +'px'
		    });

	    });

	    delete state['curs'][$(this).attr('href').slice(1)];

	}
	return false;
    });

    // добавление валюты в список валют
    $('#country .add').click(function(){
	var tis = $(this);
	
	if(tis.attr('href').length >1){
	    var id = tis.attr('href').slice(1);

	    add_country(id);

	    tis.hide();
		
		
	}
	
	return false;
    })


    /* смена варианта отображения код валюты / страна  */

    $('#show_switch a').click(function(){

	if(!$(this).hasClass('sel')){

	    state['cur_type'] = $(this).attr('class').slice(5);
	    
	    $('#show_switch a').removeClass('sel');
	    $(this).addClass('sel');

	    if(state['cur_type'] == 'code'){
	        $('#country .show_name').hide();
		$('#country .show_code').show();
	    } else {
		$('#country .show_code').hide();
		$('#country .show_name').show();
	    }

	}

	return false;

    });


    /* SEARCH CURRENCY */
	
    $('#search_currency').keyup(function(e){
	var search_str = jQuery.trim($(this).val().toLowerCase());
	$('.course_hover').hide();

		
	if (e.which == "27" || search_str == '') { //Esc
	    $(this).val('');
				
	    $("#country .link").fadeTo('slow', 1).bind('mouseover', contry_link_over);
		
	    return true;
	
	}
		
	$("#country .link").stop();
	for(i in currencies){

	    if(currencies[i]['lcode'].toLowerCase().indexOf(search_str) == -1 && currencies[i]['description'].toLowerCase().indexOf(search_str) == -1){
		$('#country .link.'+i).fadeTo('slow', 0.33);
		$('#country .link.'+i).unbind('mouseover', contry_link_over);
	    }
	    else{
		$('#country .link.'+i).fadeTo('slow', 1);
		$('#country .link.'+i).bind('mouseover',contry_link_over);
				
				
	    }
			
	}
			
    });
	
	
});



