function hv() { $(this).toggleClass('act'); }

function preload()
{
    $.imgpreload( '/img/aclouds2.jpg', '/img/airplane.jpg', '/img/askies.png',
	'/img/fields.jpg', '/img/tractor.jpg', '/img/tskies.jpg',
	'/img/wagons.jpg', '/img/wskies.jpg', '/img/dlg.png',
	'/img/wbnr_01.jpg', '/img/wbnr_02.jpg', '/img/abnr_01.jpg',
	'/img/abnr_02.jpg', '/img/abnr_03.jpg', '/img/abnr_04.jpg'
	);
    if( slides )
	{
	for( i=0; i<offers.length; i++ )
	    for( j=0; j<offers[i].itms.length; j++ )
		{
		$.imgpreload( offers[i].itms[j].img, '/img/dlg.png' );
		}
	}
}

function menuLinks( idx, curr )
{
	c = $(curr);
	c.parent().click( function() { window.location = curr.href; } );
	c.parent().mouseenter( function() { $(this).addClass('hov'); } );
	c.parent().mouseleave( function() { $(this).removeClass('hov'); } );
}

function bannerLinks( idx, curr )
{
	c = $(curr).parent().parent().parent().parent().parent();
	c.click( function() { window.location = curr.href; } );
	c.mouseenter( function() { $(this).addClass('hov'); } );
	c.mouseleave( function() { $(this).removeClass('hov'); } );
}

function smenuLinks( idx, curr )
{
	c = $(curr);
	c.parent().data('id',c.attr('id').substr(2));
	c.parent().mouseenter( function( e ) { showSubmenu($(this)); e.stopPropagation(); } );
}

function showSubmenu( obj )
{
	$('.smenu').hide();
	id = obj.data('id');
	of = obj.offset();
	sm = $('#s_'+id);
	$('.tp .lh',sm).width( obj.width() );
	scnt = $('.msl .cp .tp',sm);
	if( scnt.length )
		{
		if( scnt.width() > obj.width() || obj.width()<150 )
			{
			w = obj.width() > 150 ? obj.width()+20 : 170;
			w = 190; // obj.width()+20;
			scnt.parent().parent().width( w );
			}
		else
			scnt.parent().parent().width( obj.width()+14 );
		}
	sm.css( { top: of.top, left: of.left } );
	sm.show();
	sm.css( { top: of.top+$('a',obj).offset().top-$('a',sm).offset().top, left: of.left+/*7-xo*/+$('a',obj).offset().left-$('a',sm).offset().left } );

}

function adjustSubmenus( e )
{
//	m = $(e.target).parents('.smenu').length || 
//		$(e.target).parents('.mmenu').length ||
//		$(e.target).parents('.dropmenu').length;
//	if( !m )
//		$('.smenu').hide();
    m = ($(e.tagret).parents('.dmenucnt').lentgh || 
	($(e.target).attr('className').lastIndexOf('dmenucnt')!=-1)) ||
	($(e.target).attr('className').lastIndexOf('drpdn')!=-1) ||
	($(e.target).parents('.ddmi').length ||
	($(e.target).attr('className').lastIndexOf('ddmi')!=-1));
    if( !m )
        $('.dmenu').hide();
    if( !$('#dbg').length )
	$('body').prepend( '<div id="dbg"></div>' );
    $('#dbg').html( m+' '+$(e.target).parents('.smenu').length +' ' +$(e.target).attr('className') + ' '+
	$(e.target).parents('.dmenucnt').length + ' ' + $(e.target).parents('.drpdn').length );
		
}

function init()
{
    if( slides )
	slider = new setupOffers( 8000 );
    $('.mmenu a').each( function( idx, c ) {
	p = $(c).parent();
	if( p.hasClass('hov') )
	    return;
	p.mouseenter( function() { $(this).addClass('hov'); } );
	p.mouseleave( function() { $(this).removeClass('hov'); } );
	p.click( function() { window.location = c.href; } );
	} );
	
    $('.drpcnt').mouseenter( function() {
	t = $(this);
	nc = '#s_'+t.attr('id').substr(2);
	tgt = $(nc);
	if( !tgt.length )
	    return;
	o1 = t.offset();
	tgt.css( { top: o1.top-6, left: o1.left-11, width: t.width()+32 } );
	tgt.show( 0 );
	} );
    $('.dmenu').mouseleave( function() { $('.dmenu').hide(); } );
	
    $('.mmenu a.dsmenu').each( smenuLinks );
    $('.dropmenu a').each( smenuLinks );
    $('.smenu').mouseleave( function() { $(this).hide() } );
    $('.smi a').each( menuLinks );
    $('.nh').mouseenter( function() { $(this).addClass('hov'); } );
    $('.nh').mouseleave( function() { $(this).removeClass('hov'); } );
    $('.btn').mouseenter( function() { $(this).addClass('hov'); } );
    $('.btn').mouseleave( function() { $(this).removeClass('hov'); } );    
    $('.bnr a').each( bannerLinks );
    $(window).resize( adjustDivs );
    $('body').mousemove( adjustSubmenus );
    
    initLeasingCalculator();
    initSearch();

    $('#btn_checkout').click( gotoLeasingCalculator );
    $('#btn_request').click( gotoLeasingRequest );
    
    adjustDivs();
    initTextSlides();    
}

var slider;
var slides = null;
var offers = null;

function initSearch()
{
    $('.scont').append('<div class="srchzoomer"></div>');
    $('.srchzoomer').click( function() { $('.scont form').submit(); } );
    $('#q').bind( 'focus', function() { 
	if( this.defaultValue == this.value )
	    this.value = '';
	} );
    $('#q').bind( 'blur', function() { 
	if( this.value == '' )
	    this.value = this.defaultValue;
	} );	
}

function setupOffers( timeout )
{
	this.moff = { obj: $('#off0'), txt: $('#off0 .txt') };
	this.off1 = { obj: $('#off1'), txt: $('#off1 .txt'), img: $('#off1 .img img'), all: $('#off2 .alln a') };
	this.off2 = { obj: $('#off2'), txt: $('#off2 .txt'), img: $('#off2 .img img') };
	this.currSlide = 0;
	this.tgtSlide = 0;
	this.slObjs = new Array();
	this.animTimer = null;
	this.timeShift = timeout;
	this.shown = false;

	this.init = function()
		{
		for( i=0; i<slides.length; i++ )
			this.slObjs[i] = $('.'+slides[i]);
		this.currOffer();
		if( slides.length>1 )
		    this.startTimer();
		}

	this.startTimer = function() { this.animTimer = setTimeout( jQuery.proxy( this, 'animateSlides' ), this.timeShift ); }
	this.endTimer = function()
		{
		if( this.animTimer )
			{
			clearTimeout( this.animTimer );
			this.animTimer = null;
			}
		}

	this.currOffer = function()
		{
		this.moff.txt.html( offers[this.currSlide].msg );
		ofrs = this.randomIndices( offers[this.currSlide].itms, 2 );
		this.off1.txt.html( '<a href="' +
		    offers[this.currSlide].itms[ofrs[0]].link+'">'+
		    offers[this.currSlide].itms[ofrs[0]].desc+'</a>' );
		this.off1.img.attr('src',offers[this.currSlide].itms[ofrs[0]].img );
		this.off1.all.attr('href',offers[this.currSlide].link );
		this.off1.all.html( offers[this.currSlide].all );
		this.off2.txt.html( '<a href="'+
		    offers[this.currSlide].itms[ofrs[1]].link+'">'+
		    offers[this.currSlide].itms[ofrs[1]].desc+'</a>' );
		this.off2.img.attr('src',offers[this.currSlide].itms[ofrs[1]].img );
		if( !this.shown )
			{
			speed = $.support.opacity ? 'slow' : 0;
			this.moff.obj.fadeIn( speed );
			this.off1.obj.fadeIn( speed );
			this.off2.obj.fadeIn( speed );
			$('.bnr a').each( bannerLinks );
			this.shown = true;
			}
		}

	this.hideOffer = function()
		{
		speed = $.support.opacity ? 'slow' : 0;
		this.moff.obj.fadeOut( speed );
		this.off1.obj.fadeOut( speed );
		this.off2.obj.fadeOut( speed );
		this.shown = false;
		}
	
	this.randomIndices = function( src, amount )
		{
		res = new Array();
		idxs = new Array();
		for( i=0; i<src.length; i++ )
			idxs.push( i );
		for( i=0; i<amount; i++ )
			{
			r = Math.floor( Math.random()*idxs.length );
			res.push( idxs[r] );
			idxs.splice(r,1);
			}
		return res;
		}

	this.animateSlides = function()
		{
		this.endTimer();

		if( $.support.opacity )
			this.hideOffer();

		this.tgtSlide = this.currSlide+1;
		if( this.tgtSlide >= this.slObjs.length )
			this.tgtSlide = 0;

		this.slObjs[this.currSlide].css( { zIndex: 3 } );
		this.slObjs[this.tgtSlide].css( { zIndex: 10 } );

		this.slObjs[this.tgtSlide].fadeIn( 700, jQuery.proxy( this, 'finishSlides' ) );

		}

	this.finishSlides = function()
		{
		this.slObjs[this.currSlide].hide();
		this.currSlide++;
		if( this.currSlide >= this.slObjs.length )
			this.currSlide = 0;
		this.currOffer();
		this.startTimer();
		}

	this.debug = function()
		{
		d = $('#dbg');
		if( !d.length )
			{
			$('body').append('<div id="dbg" style="position: absolute; top: 0px; left: 0px; z-index: 400; background-color: white;"></div>' );
			d = $('#dbg');
			}
		d.html( 'Air: ' + this.slObjs[0].css('zIndex') +
			' Cars: ' + this.slObjs[1].css('zIndex') +
			' Fields: ' + this.slObjs[2].css('zIndex') );
		}

	this.init();

	return this;
}

function adjustDivs()
{
    if( slides )
	{
	$('.copy').css( { top: $('.'+slides[0]).height()-$('.copy').height()-25 } );
	$('.copy').show();
	}
    $('.smenu').hide();

    o1 = $('#fstm').position();
    o2 = $('.menu').position();
    if( o1 && o2 )
	$('#langdv').width( Math.round(o1.left-o2.left)-10 );

    bh = $('body').height();
    wh = $(window).height();
    fh = $('.footer').height();
    $('.footer').css( { top: (bh > wh-fh ? bh : wh-fh ) } );
    $('.footer').show( 0 );	
}

eprts = Array( 'ua', 'com', 'utl', '@' );
function putEmail( what )
{
    s = '';
    for( i=eprts.length; i>0; s += eprts[--i] + (i==eprts.length-1?'':'.') );
    s = what+s.substr(0,s.length-1);
    document.write( '<a class="email" href="mailto:'+s+'">'+s+'<\/a>' );
}

function initLeasingCalculator()
{
    $('#btn_baseLeasingGraph').click( leasingCalculator );
    $('.calcs').bind( 'change blur', updateCalculatorForm );
    updateCalculatorForm();
}

function updateCalculatorForm()
{
    cost = getValue( $('#c_price').val(), true );
    if( cost < 0 )
	{
	$('#c_price').val(0);
	cost = 0;
	}
    amount = getValue( $('#c_amount').val(), true );
    if( amount < 1 )
	{
	$('#c_amount').val(1);
	amount = 1;
	}
    rcost = cost*amount*0.75;
    
    years = getValue( $('#p_years').val(), true );
    if( years < 1 )
	{
	$('#p_years').val(1);
	years = 1;
	}
    months = years*12;
    pyears = getValue( $('#pp_years').val(), false );
    if( pyears < 5 || pyears > 50 )
	{
	pyears = 5;
	$('#pp_years').val( pyears );
	}
    pmonths = pyears/12;
    
    $('#c_cost').html( sprintf('%.2f', cost*amount ) );
    $('#r_cost').html( sprintf('%.2f', rcost ) );
    $('#p_months').html( years*12 );
    $('#pp_months').html( sprintf('%.3f', pmonths ) );
    $('#min_pay').html( sprintf('%.2f', rcost*Math.pow((1-1/Math.pow(1+pmonths/100,months))/pmonths*100,-1) ) );
    $('#pre_pay').html( sprintf('%.2f', cost*0.25 ) );
    $('#c_rows').html( '' );
}

var monthes = null;

function leasingCalculator()
{
    $('#c_rows').html( '' );
    cost = getValue( $('#c_price').val(), true );
    if( cost < 0 )
	{
	$('#c_price').val(0);
	cost = 0;
	}
    pre_pay = cost*0.25;
    amount = getValue( $('#c_amount').val(), true );
    if( amount < 1 )
	{
	$('#c_amount').val(1);
	amount = 1;
	}
    rcost = cost*amount*0.75;
    
    years = getValue( $('#p_years').val(), true );
    if( years < 1 )
	{
	$('#p_years').val(1);
	years = 1;
	}
    months = years*12;
    pyears = getValue( $('#pp_years').val(), false );
    if( pyears < 5 || pyears > 50 )
	{
	pyears = 5;
	$('#pp_years').val( pyears );
	}
    pmonths = pyears/12;
    
    percents = rcost*pmonths/100;	// g15
    min_pay = rcost*Math.pow((1-1/Math.pow(1+pmonths/100,months))/pmonths*100,-1);
    payback = min_pay-percents;		// f15    
    remains = rcost-payback;		// h15

    today = new Date();
    c_month = today.getMonth();
    c_year = today.getFullYear();
    $('#c_rows').append('<tr><td class="r">0<td>'+monthes[c_month]+'<td>'+c_year+
	'<td colspan=4 class="r">Аванс: '+byThree('%.2f',pre_pay) );
    for( i=0; i<months; i++ )
	{
	c_month++;
	if( c_month >= monthes.length )
	    {
	    c_month = 0;
	    c_year++;
	    }
	$('#c_rows').append('<tr><td class="r">'+(i+1)+'<td>'+monthes[c_month]+
	    '<td>'+c_year+
	    '<td class="r">'+byThree('%.2f',min_pay)+
	    '<td class="r">'+byThree('%.2f',payback)+
	    '<td class="r">'+byThree('%.2f',percents)+
	    '<td class="r">'+byThree('%.2f',remains) 
	    );
	percents = remains*pmonths/100;
	payback = min_pay-percents;
	remains = remains-payback;
	}
    adjustDivs();
}

function byThree( frm, val )
{
    return sprintf( frm, val );
    dig = 3;
    rs = r.substr(r.length-3);
    alert( rs );
    for( i=r.length-4; i>0; i-- )
	{
	rs = r.substr(i,1)+rs;
	dig--;
	if( !dig )
	    {
	    rs = ' '+rs;
	    dig = 3;
	    }
	}
    return rs;
}

function getValue( val, kind )
{
    if( kind )
	p = parseInt( val );
    else
	p = parseFloat( val );
    if( isNaN(p) )
	p = 0;
    return p;
}

function gotoLeasingCalculator()
{
    window.location = '/leasing/leasing-calculator/';
}

function gotoLeasingRequest()
{
    window.location = '/leasing/request/';
}

sprintfWrapper = {
 
	init : function () {
 
		if (typeof arguments == "undefined") { return null; }
		if (arguments.length < 1) { return null; }
		if (typeof arguments[0] != "string") { return null; }
		if (typeof RegExp == "undefined") { return null; }
 
		var string = arguments[0];
		var exp = new RegExp(/(%([%]|(\-)?(\+|\x20)?(0)?(\d+)?(\.(\d)?)?([bcdfosxX])))/g);
		var matches = new Array();
		var strings = new Array();
		var convCount = 0;
		var stringPosStart = 0;
		var stringPosEnd = 0;
		var matchPosEnd = 0;
		var newString = '';
		var match = null;
 
		while (match = exp.exec(string)) {
			if (match[9]) { convCount += 1; }
 
			stringPosStart = matchPosEnd;
			stringPosEnd = exp.lastIndex - match[0].length;
			strings[strings.length] = string.substring(stringPosStart, stringPosEnd);
 
			matchPosEnd = exp.lastIndex;
			matches[matches.length] = {
				match: match[0],
				left: match[3] ? true : false,
				sign: match[4] || '',
				pad: match[5] || ' ',
				min: match[6] || 0,
				precision: match[8],
				code: match[9] || '%',
				negative: parseInt(arguments[convCount]) < 0 ? true : false,
				argument: String(arguments[convCount])
			};
		}
		strings[strings.length] = string.substring(matchPosEnd);
 
		if (matches.length == 0) { return string; }
		if ((arguments.length - 1) < convCount) { return null; }
 
		var code = null;
		var match = null;
		var i = null;
 
		for (i=0; i<matches.length; i++) {
 
			if (matches[i].code == '%') { substitution = '%' }
			else if (matches[i].code == 'b') {
				matches[i].argument = String(Math.abs(parseInt(matches[i].argument)).toString(2));
				substitution = sprintfWrapper.convert(matches[i], true);
			}
			else if (matches[i].code == 'c') {
				matches[i].argument = String(String.fromCharCode(parseInt(Math.abs(parseInt(matches[i].argument)))));
				substitution = sprintfWrapper.convert(matches[i], true);
			}
			else if (matches[i].code == 'd') {
				matches[i].argument = String(Math.abs(parseInt(matches[i].argument)));
				substitution = sprintfWrapper.convert(matches[i]);
			}
			else if (matches[i].code == 'f') {
				matches[i].argument = String(Math.abs(parseFloat(matches[i].argument)).toFixed(matches[i].precision ? matches[i].precision : 6));
				substitution = sprintfWrapper.convert(matches[i]);
			}
			else if (matches[i].code == 'o') {
				matches[i].argument = String(Math.abs(parseInt(matches[i].argument)).toString(8));
				substitution = sprintfWrapper.convert(matches[i]);
			}
			else if (matches[i].code == 's') {
				matches[i].argument = matches[i].argument.substring(0, matches[i].precision ? matches[i].precision : matches[i].argument.length)
				substitution = sprintfWrapper.convert(matches[i], true);
			}
			else if (matches[i].code == 'x') {
				matches[i].argument = String(Math.abs(parseInt(matches[i].argument)).toString(16));
				substitution = sprintfWrapper.convert(matches[i]);
			}
			else if (matches[i].code == 'X') {
				matches[i].argument = String(Math.abs(parseInt(matches[i].argument)).toString(16));
				substitution = sprintfWrapper.convert(matches[i]).toUpperCase();
			}
			else {
				substitution = matches[i].match;
			}
 
			newString += strings[i];
			newString += substitution;
 
		}
		newString += strings[i];
 
		return newString;
 
	},
 
	convert : function(match, nosign){
		if (nosign) {
			match.sign = '';
		} else {
			match.sign = match.negative ? '-' : match.sign;
		}
		var l = match.min - match.argument.length + 1 - match.sign.length;
		var pad = new Array(l < 0 ? 0 : l).join(match.pad);
		if (!match.left) {
			if (match.pad == "0" || nosign) {
				return match.sign + pad + match.argument;
			} else {
				return pad + match.sign + match.argument;
			}
		} else {
			if (match.pad == "0" || nosign) {
				return match.sign + match.argument + pad.replace(/0/g, ' ');
			} else {
				return match.sign + match.argument + pad;
			}
		}
	}
}
 
sprintf = sprintfWrapper.init;

var currSlide = 0, prevSlide = -1;    
var slTimer = null;
var sld = null;

function initTextSlides()
{
    if( !sld )
	return;
    $('.slpnts').append( '<div class="sldscnt"></div>' );
    for( i=0; i<sld.length; i++ )
	$('.sldscnt').append( '<div class="sldpnt" id="p'+i+'"></div>' );
    animateTextSlides();
    $('.sldpnt').click( function() {
	prevSlide = currSlide;
	currSlide = $(this).attr('id').substr(1);
	animateTextSlides();
	} );
}

function animateTextSlides()
{
    if( slTimer )
	{
	clearTimeout( slTimer );
	slTimer = null;
	}
    $('.sldpnt').removeClass('slact');
    $('#p'+currSlide).addClass('slact');
    graphSlides();
    $('.slider').fadeOut( 500, function() { $('.slider').html( sld[currSlide].msg ).fadeIn( 500 ); } );
    slTimer = setTimeout( 'nextSlide()', 8500 );
}

function graphSlides()
{
    tgt = $('#grslide'+(currSlide+1));
    tgt.css( {zIndex:5} );
    if( prevSlide == -1 )
	{
	tgt.fadeIn( 500 );
	return;
	}
    prv = $('#grslide'+(prevSlide+1));
    prv.css( {zIndex:1} );
    tgt.fadeIn( 1000, function() { prv.hide(); } );
}

function nextSlide()
{
    prevSlide = currSlide;
    currSlide++;
    if( currSlide >= sld.length )
	currSlide = 0;
    animateTextSlides();
}
