$(document).ready(function(){
	init_converter();
	updateCurrency();
	randomImageInit();
	initConvertHelp();
});

function init_exchange_tables()
{
	$('h3').each(function(index) {
		if(index != 0 && $(this).parent().attr('id') != 'rates-block-cb'){
			$(this).parent().addClass('rates-block-hidden');
		}
		$(this).click(function() {
			// $('h3').each(function(index) {
			// 	$(this).parent().addClass('rates-block-hidden');
			// });
			
			$(this).parent().toggleClass('rates-block-hidden');
		});
		$(this).mouseover(function() {
			$(this).addClass('hover');
		});
		$(this).mouseout(function() {
			$(this).removeClass('hover');
		});
	});
}

var sPrevDirection = '';
var sPrevFromType = 'RUR';
var sPrevToType = 'USD';

function init_converter()
{
	$('div.b-converter h4').click(function() {
		toggleConverter($(this));
		return false;
	});
	$('#currencyFromValue, #comissionValue, #currencyToValue').keyup(function(){
		var sDirection = 'forward';
		if($(this).attr('id') == 'currencyToValue'){
			sDirection = 'backward';
		}
		if($(this).attr('id') == 'comissionValue' && sPrevDirection != ''){
			sDirection = sPrevDirection;
		}
		convertCurrency( sDirection );
	});
	
	$('#currencyFromType, #currencyToType').change(function() {
		if($('#currencyFromType').val() == $('#currencyToType').val()){
			if($(this).attr('id') == 'currencyFromType'){
				$('#currencyToType').val(sPrevFromType);
			}else{
				$('#currencyFromType').val(sPrevToType);
			}
		}
		if(($('#currencyFromType').val() == 'USD' && $('#currencyToType').val() == 'EUR') || ($('#currencyFromType').val() == 'EUR' && $('#currencyToType').val() == 'USD')){
			if($(this).attr('id') == 'currencyFromType'){
				$('#currencyToType').val('RUR');
			}else{
				$('#currencyFromType').val('RUR');
			}
		}
		
		var sDirection = 'forward';
		if($(this).attr('id') == 'currencyToType'){
			sDirection = 'backward';
		}
		
		sPrevFromType = $('#currencyFromType').val();
		sPrevToType = $('#currencyToType').val();
		
		convertCurrency( sDirection );
	});
	
	$('#currencyFromValueNonCash').keyup(function(){
		convertCurrencyNonCash();
	});
	$('#currencyFromTypeNonCash').change(function() {
		convertCurrencyNonCash();
	});
}

function toggleConverter( element )
{
	$(element).next().toggle();
	$(element).toggleClass('selected');
}

function convertCurrency( sDirection )
{
	var iSourceValue = stringToFloat($('#currencyFromValue').val());
	var iResultValue = stringToFloat($('#currencyToValue').val());
	var iComission = $('#comissionValue').val() / 100;
	
	var sSourceCurrency = $('#currencyFromType').val();
	var sResultCurrency = $('#currencyToType').val();
	var _oCurrency = {
		'RUR' : {
			'label' : 'рублях'
		},
		'USD' : {
			'label' : 'долларах'
		},
		'EUR' : {
			'label' : 'евро'
		}
	};
	
	sPrevDirection = sDirection;
	
	if(!iComission){
		var _sComission = '%';
			iComission = 0;
	}else{
		var _sComission = '%, ' + floatToString( (iSourceValue * iComission) ) + ' в ' + _oCurrency[sSourceCurrency]['label'];
		
	}
	
	$('#exchange-rates #converter #convert-comission').text(_sComission);
	
	if(iSourceValue > 0 && sDirection == 'forward'){
		if(sSourceCurrency == 'RUR' && sResultCurrency == 'USD'){
			$('#currencyToValue').val(floatToString(iSourceValue/stringToFloat(usd_selling) - iSourceValue/stringToFloat(usd_selling) * iComission));
		}
		if(sSourceCurrency == 'RUR' && sResultCurrency == 'EUR'){
			$('#currencyToValue').val(floatToString(iSourceValue/stringToFloat(eur_selling) - iSourceValue/stringToFloat(eur_selling) * iComission));
		}
		if(sSourceCurrency == 'USD' && sResultCurrency == 'RUR'){
			$('#currencyToValue').val(floatToString(iSourceValue*stringToFloat(usd_buying) - iSourceValue*stringToFloat(usd_buying) * iComission));
		}
		if(sSourceCurrency == 'EUR' && sResultCurrency == 'RUR'){
			$('#currencyToValue').val(floatToString(iSourceValue*stringToFloat(eur_buying) - iSourceValue*stringToFloat(eur_buying) * iComission));
		}
	}
	if(iResultValue > 0 && sDirection == 'backward'){
		if(sResultCurrency == 'RUR' && sSourceCurrency == 'USD'){
			$('#currencyFromValue').val(floatToString(iResultValue/stringToFloat(usd_selling) + iResultValue/stringToFloat(usd_selling) * iComission));
		}
		if(sResultCurrency == 'RUR' && sSourceCurrency == 'EUR'){
			$('#currencyFromValue').val(floatToString(iResultValue/stringToFloat(eur_selling) + iResultValue/stringToFloat(eur_selling) * iComission));
		}
		if(sResultCurrency == 'USD' && sSourceCurrency == 'RUR'){
			$('#currencyFromValue').val(floatToString(iResultValue*stringToFloat(usd_buying) + iResultValue*stringToFloat(usd_buying) * iComission));
		}
		if(sResultCurrency == 'EUR' && sSourceCurrency == 'RUR'){
			$('#currencyFromValue').val(floatToString(iResultValue*stringToFloat(eur_buying) + iResultValue*stringToFloat(eur_buying) * iComission));
		}
	}
}

function convertCurrencyNonCash()
{
	var sourceValue = stringToFloat($('#currencyFromValueNonCash').val());
	var sourceCurrency = $('#currencyFromTypeNonCash').val();
		
	$('#converterNonCash table.result tbody').html('');
	$('#converterNonCash table.result').hide();

	if(sourceValue > 0){
		$('#converterNonCash table.result').show();
		if(sourceCurrency == 'RUR'){
			convertAppendResult('USD', sourceValue/stringToFloat(usd_noncash_selling), 'NonCash');
			convertAppendResult('EUR', sourceValue/stringToFloat(eur_noncash_selling), 'NonCash');
		}
		if(sourceCurrency == 'USD'){
			convertAppendResult('RUR', sourceValue*stringToFloat(usd_noncash_buying), 'NonCash');
			convertAppendResult('EUR', sourceValue*stringToFloat(usd_noncash_buying) / stringToFloat(eur_noncash_selling), 'NonCash');
		}
		if(sourceCurrency == 'EUR'){
			convertAppendResult('RUR', sourceValue*stringToFloat(eur_noncash_buying), 'NonCash');
			convertAppendResult('USD', sourceValue*stringToFloat(eur_noncash_buying) / stringToFloat(usd_noncash_selling), 'NonCash');
		}
	}
}


function stringToFloat(value)
{
	return(value.toString().replace(",", ".").replace(" ", ""));
}

function floatToString(value)
{
	value = value.toFixed(2).toString().replace(".", ",");
	if(value.length <= 7){
		return(value);
	}else{
		if(value.length > 9){
			var position1 = value.length-9;
			var position2 = value.length-6;
			return(value.substring(0,position1)+' '+value.substring(position1,position2)+' '+value.substring(position2, value.length));

		}else{
			var position = value.length-6;
			return(value.substring(0,position)+' '+value.substring(position, value.length));
		}
	}
}

function convertAppendResult(currency, value, type)
{
	$('#converter' + type + ' table.result tbody').append('<tr><td class="value"><nobr>'+floatToString(value)+'</nobr></td><td class="label">'+currency+'</td></tr>');
}


/* Обновление курсов валют */
function updateCurrency(){
	var rndRequest = "?rndRequest=" + Math.random();
	var sUrl = '/_/_currency.xml' + rndRequest;
	
	if(city != '/'){
		sUrl = '/_/ajax/_get_currency_for_frontpage.html' + rndRequest + '&cityID=' + cityId;
	}
	$.ajax({
		url: sUrl,
		type: 'GET',
		dataType: 'xml',
		cache: false,
		timeout: 10000,
		success: function(xml) {
			fillCurrencyTable($(xml));
		},
		error: function() {
		}
	});
}
function fillCurrencyTableTmp(xml){
	if($(xml).find('rates').length == 0){
		$('#exchange-rates').hide();
	}else{
		$('#exchange-rates').html('<h2>Курсы валют на ' + $(xml).find('rates').attr('today') + '</h2>');
		$('#exchange-rates').append(fillCurrencyNonCash($(xml)));
	}
}
function fillCurrencyNonCash(xml){
	var code = '<div class="rates-block"><h3><span></span></h3>';
	
	code += '</div>';
	
	return(code);
}
function fillCurrencyTable(xml){               
	var USDnoncashBuy = $(xml).find('rates[type="non-cash"] item[currency-id = 840]').attr('value-buying');
	var USDnoncashSell = $(xml).find('rates[type="non-cash"] item[currency-id = 840]').attr('value-selling');
	var CHFnoncashBuy = $(xml).find('rates[type="non-cash"] item[currency-id = 756]').attr('value-buying');
	var CHFnoncashSell = $(xml).find('rates[type="non-cash"] item[currency-id = 756]').attr('value-selling');
	var EURnoncashBuy = $(xml).find('rates[type="non-cash"] item[currency-id = 978]').attr('value-buying');
	var EURnoncashSell = $(xml).find('rates[type="non-cash"] item[currency-id = 978]').attr('value-selling');

	var USDconvert = $(xml).find('rates[type="convert"] item[currency-id = 840]').attr('value');
	var EURconvert = $(xml).find('rates[type="convert"] item[currency-id = 978]').attr('value');
	var EURconvert_dir = $(xml).find('rates[type="convert"] item[currency-id = 978]').attr('risedir');

	var USDcashBy = $(xml).find('rates[type="cash"] item[currency-id = 840]').attr('value-buying');
	var USDcashSell = $(xml).find('rates[type="cash"] item[currency-id = 840]').attr('value-selling');
	var JPYcashBy = $(xml).find('rates[type="cash"] item[currency-id = 392]').attr('value-buying');
	var JPYcashSell = $(xml).find('rates[type="cash"] item[currency-id = 392]').attr('value-selling');
	var EURcashBy = $(xml).find('rates[type="cash"] item[currency-id = 978]').attr('value-buying');
	var EURcashSell = $(xml).find('rates[type="cash"] item[currency-id = 978]').attr('value-selling');

	var USDcb = $(xml).find('rates[type="cb"] item[currency-id = 840]').attr('value');
	var JPYcb = $(xml).find('rates[type="cb"] item[currency-id = 392]').attr('value');
	var EURcb = $(xml).find('rates[type="cb"] item[currency-id = 978]').attr('value');

	$('#USDnoncashBuy').html(USDnoncashBuy);
	put_src_arrow($('#USDnoncashBuy_label'), $(xml).find('rates[type="non-cash"] item[currency-id = 840]').attr('risedir'));
	$('#USDnoncashSell').html(USDnoncashSell);
	put_src_arrow($('#USDnoncashSell_label'), $(xml).find('rates[type="non-cash"] item[currency-id = 840]').attr('risedir'));
	$('#CHFnoncashBuy').html(CHFnoncashBuy);
	put_src_arrow($('#CHFnoncashBuy_label'), $(xml).find('rates[type="non-cash"] item[currency-id = 756]').attr('risedir'));
	$('#CHFnoncashSell').html(CHFnoncashSell);
	put_src_arrow($('#CHFnoncashSell_label'), $(xml).find('rates[type="non-cash"] item[currency-id = 756]').attr('risedir'));
	$('#EURnoncashBuy').html(EURnoncashBuy);
	put_src_arrow($('#EURnoncashBuy_label'), $(xml).find('rates[type="non-cash"] item[currency-id = 978]').attr('risedir'));
	$('#EURnoncashSell').html(EURnoncashSell);
	put_src_arrow($('#EURnoncashSell_label'), $(xml).find('rates[type="non-cash"] item[currency-id = 978]').attr('risedir'));

	
	$('#USDconvert').html(USDconvert);
	put_src_arrow($('#USDconvert_label'), $(xml).find('rates[type="convert"] item[currency-id = 840]').attr('risedir'));
	$('#EURconvert').html(EURconvert);
	put_src_arrow($('#EURconvert_label'), $(xml).find('rates[type="convert"] item[currency-id = 978]').attr('risedir'));

	$('#USDcashBy').html(USDcashBy);
	put_src_arrow($('#USDcashBy_label'), $(xml).find('rates[type="cash"] item[currency-id = 840]').attr('risedir'));
	$('#USDcashSell').html(USDcashSell);
	put_src_arrow($('#USDcashSell_label'), $(xml).find('rates[type="cash"] item[currency-id = 840]').attr('risedir'));
	$('#JPYcashBy').html(JPYcashBy);
	put_src_arrow($('#JPYcashBy_label'), $(xml).find('rates[type="cash"] item[currency-id = 392]').attr('risedir'));
	$('#JPYcashSell').html(JPYcashSell);
	put_src_arrow($('#JPYcashSell_label'), $(xml).find('rates[type="cash"] item[currency-id = 392]').attr('risedir'));
	$('#EURcashBy').html(EURcashBy);
	put_src_arrow($('#EURcashBy_label'), $(xml).find('rates[type="cash"] item[currency-id = 978]').attr('risedir'));
	$('#EURcashSell').html(EURcashSell);
	put_src_arrow($('#EURcashSell_label'), $(xml).find('rates[type="cash"] item[currency-id = 978]').attr('risedir'));

	$('#USDcb').html(USDcb);
	put_src_arrow($('#USDcb_label'), $(xml).find('rates[type="cb"] item[currency-id = 840]').attr('risedir'));
	$('#JPYcb').html(JPYcb);
	put_src_arrow($('#JPYcb_label'), $(xml).find('rates[type="cb"] item[currency-id = 392]').attr('risedir'));
	$('#EURcb').html(EURcb);
	put_src_arrow($('#EURcb_label'), $(xml).find('rates[type="cb"] item[currency-id = 978]').attr('risedir'));
	
	usd_buying = USDconvert;
	usd_selling = USDconvert;
	eur_buying = EURconvert;
	eur_selling = EURconvert;
	
	usd_noncash_buying = USDnoncashBuy;
	usd_noncash_selling = USDnoncashSell;
	eur_noncash_buying = EURnoncashBuy;
	eur_noncash_selling = EURnoncashSell;
}

function put_src_arrow(object, dir){
	switch(dir){
		case 'none' :
			object.css({display:'none'})
		break;
		case 'up' :
			object.attr('src', '/f/1/global/icon_arrow_up.gif')
		break;
		case 'none' :
			object.attr('src', '/f/1/global/icon_arrow_down.gif')
		break;
	}
}


function randomImageInit(){
	var iMaxIndex = 999; // images with numbers 1..20 in filenames will be used
	//var iCurrentImage = Math.floor(Math.random() * iMaxIndex) + 1;
	var iCurrentImage = getRandomImageNumber(iMaxIndex);
	
	$('td.body div.logo').each(function(index) {
		var sCode = '';
		if (checkPngImage(iCurrentImage)) {
			sCode = '<div class="top png" style="background: url(/f/1/splash-' + iCurrentImage + '.png) no-repeat 100% 100% !important;"><spacer /></div>';
		} else {
			sCode = '<div class="top png" style=""><spacer /></div>';
		}
//		sCode = '<div class="top png"><spacer /></div>';
		sCode += '<div class="main" style="background-image: url(/f/1/splash-' + iCurrentImage + '.jpg);"><spacer /></div>';
		$(this).before('<div class="image">'+sCode+'</div>');
	});
}

function getRandomImageNumber (max_index) {
	var number = Math.floor(Math.random() * max_index) + 1;
	if (!checkRandomImage(number)) {
		return getRandomImageNumber(max_index);
	} else {
		return number;
	}
}
function checkRandomImage (number) {
	if (typeof jpg_rotation != 'undefined') {
		if ($.inArray('splash-' + number + '.jpg', jpg_rotation) != -1) {
			return true;
		} else {
			return false;
		}
	} else {
		return true;
	}
}
function checkPngImage (number) {
	if (typeof png_rotation != 'undefined') {
		if ($.inArray('splash-' + number + '.png', png_rotation) != -1) {
			return true;
		} else {
			return false;
		}
	} else {
		return true;
	}
}

function randomImageInit_honesty(){
	var aImages = new Array();
	
		aImages[1] = new Array();
		aImages[1]['img'] = "rk-1";
		aImages[1]['img-width'] = "477";
		aImages[1]['img-height'] = "305";
		aImages[1]['text-pos-x'] = "264";
		aImages[1]['text-pos-y'] = "59";
		aImages[1]['text'] = "<a style='color: #EC3225;' href='about/ads/advertisment/honesty/'>Я это сделал</a>";
		
		aImages[2] = new Array();
		aImages[2]['img'] = "rk-2";
		aImages[2]['img-width'] = "437";
		aImages[2]['img-height'] = "305";
		aImages[2]['text-pos-x'] = "243";
		aImages[2]['text-pos-y'] = "51";
		aImages[2]['text'] = "<a style='color: #EC3225;' href='about/ads/advertisment/honesty/'>Вам нравится мое платье?</a>";
		
		aImages[3] = new Array();
		aImages[3]['img'] = "rk-3";
		aImages[3]['img-width'] = "419";
		aImages[3]['img-height'] = "305";
		aImages[3]['text-pos-x'] = "228";
		aImages[3]['text-pos-y'] = "61";
		aImages[3]['text'] = "<a style='color: #EC3225;' href='about/ads/advertisment/honesty/'>Я &mdash; художник Шишкин</a>";
		
		aImages[4] = new Array();
		aImages[4]['img'] = "rk-4";
		aImages[4]['img-width'] = "429";
		aImages[4]['img-height'] = "309";
		aImages[4]['text-pos-x'] = "221";
		aImages[4]['text-pos-y'] = "49";
		aImages[4]['text'] = "<a style='color: #EC3225;' href='about/ads/advertisment/honesty/'>Я&nbsp;могу поработать в&nbsp;выходные</a>";
		
		aImages[5] = new Array();
		aImages[5]['img'] = "rk-5";
		aImages[5]['img-width'] = "389";
		aImages[5]['img-height'] = "304";
		aImages[5]['text-pos-x'] = "178";
		aImages[5]['text-pos-y'] = "49";
		aImages[5]['text'] = "<a style='color: #EC3225;' href='about/ads/advertisment/honesty/'>А&nbsp;я&nbsp;поеду с&nbsp;вами переводчицей</a>";
		
		aImages[6] = new Array();
		aImages[6]['img'] = "rk-new-year";
		aImages[6]['img-width'] = "437";
		aImages[6]['img-height'] = "309";
		aImages[6]['text-pos-x'] = "221";
		aImages[6]['text-pos-y'] = "60";
		aImages[6]['text'] = "<a style='color: #EC3225;' href='about/ads/newyear-2010/'>С&nbsp;Новым годом</a>";

	var iMaxIndex = 5; // images with numbers 1..2 in filenames will be used
	var iCurrentImage = Math.floor(Math.random() * iMaxIndex) + 1;
	//iCurrentImage = 6; // for new year splash

	var aSelected = aImages[iCurrentImage];
	
	$('td.body .frame-whole div.logo').each(function(index) {
		var sHtml = '';
			sHtml = '<div class="top png"><spacer /></div>';
			sHtml += '<div class="main" style="width: '+ aSelected["img-width"] +'px !important; height: '+ aSelected["img-height"] +'px !important; background: url(/f/1/splash-' + aSelected["img"] + '.png); //background: none; //filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src=/f/1/splash-' + aSelected["img"] + '.png, sizingMethod=scale);">'
			sHtml += '<div style="position: absolute; width: 172px; height: 52px; top: '+ aSelected["text-pos-y"] +'px; right: '+ aSelected["text-pos-x"] +'px; font-size: 11pt; line-height: 134%; letter-spacing: -0.2pt;">'+ aSelected["text"] +'</div>';
			sHtml += '</div>';
		
		$(this).after('<div class="image" style="width: '+ aSelected["img-width"] +'px !important; height: 325px !important;">'+sHtml+'</div>');
	});	
}

function initConvertHelp () {
	$("#show-convert-help").click(function(){
		$("#convert-comm-help").css({top: $(document).scrollTop(), left:30}).toggle();
		if ($.browser.msie && $.browser.version == "6.0") {
			$("body").toggleClass("fuck-ie");
		}
	});
}
function abFrameCloseFunc () {
	$("#show-convert-help").click();
}