
/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

function TabActivate(contentName, tab) {
    $('[id^=subContent]').not('#'+contentName).css('display', 'none');
    $('span[id^=tab]').not(tab).removeClass('activeTab');
    $('#'+contentName).css('display', 'block');
    $(tab).addClass('activeTab');
}


$(document).ready(function(){

//$('#YMapsID').height($('#map').height());
//$(window).resize(function(){
//    $('#YMapsID').height($('#map').height());
//});

	
var widthTar = $('#tarBlock').width();
$('#costForm select').css('width', widthTar);

var activeCity = $('#cities span').eq(0);
$(activeCity).css('color', '#A10505');

$('#cities span').click(function(){
    $('#phone1').html($(this).attr('tel1'));
    $('#phone2').html($(this).attr('tel2'));
    $(activeCity).css({'color':'#000000'});
    $(this).css('color', '#A10505');
    activeCity = this;
});

$.validator.setDefaults({
	highlight: function(input) {
		$(input).addClass("highlight");
	},
	unhighlight: function(input) {
		$(input).removeClass("highlight");
	}
});

//
// Валидация форм
//
$("form#contract, form#feedbackForm, form#orderForm").validate({
    invalidHandler: function() {
        $('div#error').show();
    }
});



/*
 *
 * Выделение активной ссылки
 *
 */
$('a').each(function(){
    if ($(this).attr('href') == window.location.pathname) {
        $(this).css({'color':'#A10505'});
    }
});

/*
 * Генерация дополнительного поля со страницы @feedback
 */
$('select').change(function(){
    if ($(this).val() == 'Другое:') {
        $('#feedback2').css({'visibility':'visible'});
    }
    else {
        $('#feedback2').css({'visibility':'hidden'});
    }
});

var place1 = null;
var place2 = null;
$('form').hover(function(){
    if (place1 == $('input[name="citySender"]').val() && place2 == $('input[name="cityReceiver"]').val())
        return;
    place1 = $('input[name="citySender"]').val();
    if (!place1) return;
    place2 = $('input[name="cityReceiver"]').val();
    if (!place2) return;
    $.post('/cost', {place1:place1, place2:place2}, function(data){
        var options = '<option selected="selected"></option>';
        var select = eval('(' + data + ')');
        for (var key in select) {
            var val = select[key];
            options += '<option>'+val['name']+'</option>'; 
        }
        $('select[name="tariff"]').html(options);
    });
});
$('input[name="citySender"], input[name="cityReceiver"]').keyup(function(){
    if (place1 == $('input[name="citySender"]').val() && place2 == $('input[name="cityReceiver"]').val())
        return;
    place1 = $('input[name="citySender"]').val();
    if (!place1) return;
    place2 = $('input[name="cityReceiver"]').val();
    if (!place2) return;
    $.post('/cost', {place1:place1, place2:place2}, function(data){
        var options = '<option selected="selected"></option>';
        var select = eval('(' + data + ')');
        for (var key in select) {
            var val = select[key];
            options += '<option>'+val['name']+'</option>'; 
        }
        $('select[name="tariff"]').html(options);
    });    
});


//
// Функция появления бланка со страницы Order 
//
$('div#getBlank span').click(function(){
    $('div#blankComplete').text('');
    $('#blank').slideToggle(1000, 'easeInQuad', function(){
       //window.location.href = '#getBlank';

    });    
    $('#blank').css({'display':'block'});
//    window.location.href = '#getBlank';
});

$('div#getContract').click(function(){
   $('div.forms form').slideToggle(1000, 'easeInQuad', function(){
       //window.location.href = '#getContract';
       
   });
});

/*
 * Функции появления дополнительных условий и расчета веса со страницы @getCost
 */
$('div#getCostOther').click(function(){
   if ($('div#getCost2').css('display') == 'none') {
       $('div#getCost2').css({'display':'block'});
   }
   else {
       $('div#getCost2').css({'display':'none'});
   }
});

$('div#getCostOther2').click(function(){
   if ($('div.getCost2').css('display') == 'none') {
       $('div.getCost2').css({'display':'block'});
   }
   else {
       $('div.getCost2').css({'display':'none'});
   }
});

$('div#getWeight span').click(function(){
   if ($(this).next().css('display') == 'none') {
       $(this).next().css({'display':'block'});
   }
   else {
       $(this).next().css({'display':'none'});
   }
});

function setImages () {
    $('#gotWeight').text('0');
    switch ($('input[type=radio]:checked').attr('value')) {
        case 'box':
	    $('#len, #diam').val('');
	    var len = null;
	    var diam = null;
            $('#img').attr({'src':'images/box.png', 'style':'margin-top: -4px; margin-left:-42px'});
            $('#boxFields').css({'display':'block'});
            $('#rollFields').css({'display':'none'});
        break;
        case 'roll':
	    $('#lenght, #width, #height').val('');
	    var lenght = null;
	    var width = null;
	    var height = null;
            $('#img').attr({'src':'images/roll.png', 'style':'margin-top: -4px; margin-left:-42px'});
            $('#rollFields').css({'display':'block'});
            $('#boxFields').css({'display':'none'});            
        break;
    }
}
$('#lenght, #width, #height, #len, #diam').keypress(function(){
    $('#gotWeight').text('0');
});
$('#lenght').focus(function(){    
    $('#img').attr({'src':'images/boxLength.png', 'style':'margin-top: -11px; margin-left:-54px'});
});
$('#width').focus(function(){    
    $('#img').attr({'src':'images/boxWidth.png', 'style':'margin-top: -9px; margin-left:-54px'});
});
$('#height').focus(function(){    
    $('#img').attr({'src':'images/boxHeight.png', 'style':'margin-top: -12px; margin-left:-54px'});
});
$('#len').focus(function(){    
    $('#img').attr({'src':'images/rollHeight.png', 'style':'margin-top: -10px; margin-left:-62px'});
});
$('#diam').focus(function(){    
    $('#img').attr({'src':'images/rollDiam.png', 'style':'margin-top: -12px; margin-left:-63px'});
});
setImages();
$('input[type=radio]').click(function(){
    setImages();
});
$('#getObWeight input[type=button]').click(function(){
    if ($('input[type=radio]:checked').attr('value') == 'box') {
        if (!($('#lenght').val()) || !($('#width').val()) || !($('#height').val())) {
            return;
        }
        else {
            var lenght = parseInt($('#lenght').val());
            var width = parseInt($('#width').val());
            var height = parseInt($('#height').val());
            var weight = Math.ceil(lenght*width*height/6000);
            $('#gotWeight').text(weight);
        }
    }
    else {
        if (!($('#len').val()) || !($('#diam').val())) {
            return;
        }
        else {
            var len = parseInt($('#len').val());
            var diam = parseInt($('#diam').val());
            var weight = Math.ceil(len*(((diam/2)*(diam/2))*3.14)/6000);
            $('#gotWeight').text(weight);
        }        
    }
})

$('form#costForm').submit(function(event){
    
    event.preventDefault();
    
    var $form = $(this),
        citySender = $form.find( 'input[name="citySender"]' ).val(),
        cityReceiver = $form.find( 'input[name="cityReceiver"]' ).val(),
        tariff = $form.find('select[name="tariff"]').val(),
        weight = $form.find('input[name="weight"]').val(),
        url = $form.attr( 'action' );
	
	if ($('input[type=radio]:checked').attr('value') == 'box') {
	    if (!($('#lenght').val()) || !($('#width').val()) || !($('#height').val())) {
	    }
	    else {
		var lenght = parseInt($('#lenght').val());
		var width = parseInt($('#width').val());
		var height = parseInt($('#height').val());
		var weight2 = Math.ceil(lenght*width*height/6000);
		$('#gotWeight').text(weight2);
	    }
		if (parseInt(weight2) < parseInt($('#gotWeight').text())) {
		    weight2 = parseInt($('#gotWeight').text());
		}	    
	}
	else {
	    if (!($('#len').val()) || !($('#diam').val())) {
	    }
	    else {
		var len = parseInt($('#len').val());
		var diam = parseInt($('#diam').val());
		var weight2 = Math.ceil(len*(((diam/2)*(diam/2))*3.14)/6000);
		$('#gotWeight').text(weight2);
	    }
		if (parseInt(weight2) < parseInt($('#gotWeight').text())) {
		    weight2 = parseInt($('#gotWeight').text());
		}	    
	}
	
	if (weight < weight2){
	    weight = weight2;
	}
        
        if (!citySender || !cityReceiver || !tariff || !weight) return;

        
    $.post(url, {
        citySender:citySender,
        cityReceiver:cityReceiver,
        tariff:tariff,
        weight:weight
    }, function(data){
        var firstData = parseInt(data);                    
        data = parseInt(data);
        $('input[type="checkbox"]:checked').each(function(){
            data += ($(this).val())*firstData - firstData;
        });
	if (!data) {
		alert('Расчёт по данному тарифу не производится!');
		data = 0;
	}
	data = Math.ceil(data);
        $('#getCost3 div span').html(data);
    })   
});

 
//
// Обработка формы бланка и генерация, собственно, самого бланка
//
var imageSrc = '';
$('div#blank form').submit(function(event){

    event.preventDefault();
    
        
    var $form = $(this),
        companySender = $form.find( 'input[name="companySender"]' ).val(),
        citySender = $form.find( 'input[name="citySender"]' ).val(),
        countrySender = $form.find( 'input[name="countrySender"]' ).val(),
        regionSender = $form.find( 'input[name="regionSender"]' ).val(),
        districtSender = $form.find( 'input[name="districtSender"]' ).val(),
        addressSender = $form.find( 'input[name="addressSender"]' ).val(),
        nameSender = $form.find( 'input[name="nameSender"]' ).val(),
        phoneSender = $form.find( 'input[name="phoneSender"]' ).val(),
        infoSender = $form.find( 'input[name="infoSender"]' ).val(),
        companyReceiver = $form.find( 'input[name="companyReceiver"]' ).val(),
        cityReceiver = $form.find( 'input[name="cityReceiver"]' ).val(),
        countryReceiver = $form.find( 'input[name="countryReceiver"]' ).val(),
        regionReceiver = $form.find( 'input[name="regionReceiver"]' ).val(),
        districtReceiver = $form.find( 'input[name="districtReceiver"]' ).val(),
        addressReceiver = $form.find( 'input[name="addressReceiver"]' ).val(),
        nameReceiver = $form.find( 'input[name="nameReceiver"]' ).val(),
        handsReceiver = '',
        phoneReceiver = $form.find( 'input[name="phoneReceiver"]' ).val(),
        infoReceiver = $form.find( 'input[name="infoReceiver"]' ).val(),
        inDesc = $form.find( 'input[name="inDesc"]' ).val(),
        docum = '',
        danger = '',
        mesta = $form.find( 'input[name="mesta"]' ).val(),
        weight = $form.find( 'input[name="weight"]' ).val(),
        obWeight = $form.find( 'input[name="obWeight"]' ).val(),
        inCity = '',
        inCountry = '',
        outCountry = '',
        express23 = '',
        express = '',
        standart = '',
        econom = '',
        inetShop = '',
        vostr = '',
        otprav = '',
        poluch = '',
        third = '',
        poSchetu = '',
        cash = '',
        garant = '',
        nalozh = $form.find( 'input[name="nalozh"]' ).val(),
        yes = '',
        no = '',
        cennost = $form.find( 'input[name="cennost"]' ).val(),
        
        url = $form.attr( 'action' );
        
        if ($form.find('input[name="handsReceiver"]:checked').attr('id') == 'handsReceiver') {
            handsReceiver = 'V';
        }
        if ($form.find('input[name="docum"]:checked').attr('id') == 'docum') {
            docum = 'V';
        }
        if ($form.find('input[name="danger"]:checked').attr('id') == 'danger') {
            danger = 'V';
        }
        if ($form.find('input[name="inCity"]:checked').attr('id') == 'inCity') {
            inCity = 'V';
        }
        if ($form.find('input[name="inCountry"]:checked').attr('id') == 'inCountry') {
            inCountry = 'V';
        }
        if ($form.find('input[name="outCountry"]:checked').attr('id') == 'outCountry') {
            outCountry = 'V';
        }
        if ($form.find('input[name="express23"]:checked').attr('id') == 'express23') {
            express23 = 'V';
        }
        if ($form.find('input[name="express"]:checked').attr('id') == 'express') {
            express = 'V';
        }
        if ($form.find('input[name="standart"]:checked').attr('id') == 'standart') {
            standart = 'V';
        }
        if ($form.find('input[name="econom"]:checked').attr('id') == 'econom') {
            econom = 'V';
        }
        if ($form.find('input[name="inetShop"]:checked').attr('id') == 'inetShop') {
            inetShop = 'V';
        }
        if ($form.find('input[name="vostr"]:checked').attr('id') == 'vostr') {
            vostr = 'V';
        }
        if ($form.find('input[name="otprav"]:checked').attr('id') == 'otprav') {
            otprav = 'V';
        }
        if ($form.find('input[name="poluch"]:checked').attr('id') == 'poluch') {
            poluch = 'V';
        }
        if ($form.find('input[name="third"]:checked').attr('id') == 'third') {
            third = 'V';
        }
        if ($form.find('input[name="poSchetu"]:checked').attr('id') == 'poSchetu') {
            poSchetu = 'V';
        }
        if ($form.find('input[name="cash"]:checked').attr('id') == 'cash') {
            cash = 'V';
        }
        if ($form.find('input[name="garant"]:checked').attr('id') == 'garant') {
            garant = 'V';
        }
        if ($form.find('input[name="yes"]:checked').attr('id') == 'yes') {
            yes = 'V';
        }
        if ($form.find('input[name="no"]:checked').attr('id') == 'no') {
            no = 'V';
        }
        
        

    $.post( url, {
        companySender:companySender,
        citySender:citySender,
        countrySender:countrySender,
        regionSender:regionSender,
        districtSender:districtSender,
        addressSender:addressSender,
        nameSender:nameSender,
        phoneSender:phoneSender,
        infoSender:infoSender,
        companyReceiver:companyReceiver,
        cityReceiver:cityReceiver,
        countryReceiver:countryReceiver,
        regionReceiver:regionReceiver,
        districtReceiver:districtReceiver,
        addressReceiver:addressReceiver,
        nameReceiver:nameReceiver,
        handsReceiver:handsReceiver,
        phoneReceiver:phoneReceiver,
        infoReceiver:infoReceiver,
        inDesc:inDesc,
        docum:docum,
        danger:danger,
        mesta:mesta,
        weight:weight,
        obWeight:obWeight,
        inCity:inCity,
        inCountry:inCountry,
        outCountry:outCountry,
        express23:express23,
        express:express,
        standart:standart,
        econom:econom,
        inetShop:inetShop,
        vostr:vostr,
        otprav:otprav,
        poluch:poluch,
        third:third,
        poSchetu:poSchetu,
        cash:cash,
        garant:garant,
        nalozh:nalozh,
        yes:yes,
        no:no,
        cennost:cennost
    }, function( data ) {
        imageSrc = data;
            $('div#blank').css({'display':'none'});
            window.location.href = '#getBlank';
            $('div#blankComplete').html('<img src="blanks/mini'+data+'.jpg" alt="" width="100%" /><br /><br />\n\
                                        <a href="/blanks/'+data+'.jpg">Распечатать</a>\n\
                                        ');
            
//            $('html, body').animate({
//                scrollTop: $('#getBlank').offset().top
//            }, 1500,'easeInOutExpo');           
      }
    );
   
});
    
/*
 * Генерация полей на странице @trace
 */
var lastField = 3;
$('#addField span').click(function(){
    $(this).parent().before('<div class="traceField">\n\
                                    <input type="text" name="num'+(++lastField)+'" value="" />\n\
                                  </div>\n\
                                  <div class="traceField">\n\
                                    <input type="text" name="num'+(++lastField)+'" value="" />\n\
                                  </div>\n\
                                  <div class="traceField" style="margin:0">\n\
                                    <input type="text" name="num'+(++lastField)+'" value="" />\n\
                                  </div>');
});
$('#submit input').click(function(){
    $('#traceMessage').css({'display':'block'});
});

//
// Автозаполнение полей "Город" и "Улица"
//
$("#cityUr").autocomplete('/cityView.php');
$("#city").autocomplete('/cityView.php');
$('#citySender').autocomplete('/cost');
$('#cityReceiver').autocomplete('/cost');

//$('input[type=text]').focus(function(){
//    if ($('input[name="cityUr"]').val() == String.fromCharCode('Москва')) {
//        $("#streetUr").autocomplete('mskStreetView.php');
//    }
//    if ($('input[name="cityUr"]').val() == String.fromCharCode('Санкт-Петербург')) {
//        $("#streetUr").autocomplete('spbStreetView.php');
//    }  
//    if ($('input[name="city"]').val() == 'Москва') {
//        $("#street").autocomplete('mskStreetView.php');
//    }
//    if ($('input[name="city"]').val() == 'Санкт-Петербург') {
//        $("#street").autocomplete('spbStreetView.php');
//    }  
//});


});



