// JavaScript Document

// CHECKBOX BEGINS
$(document).ready(function() {
/*
	if ($(".safari").length > 0) {
		 $('input[".safari"]:checkbox').checkbox({cls:'jquery-safari-checkbox'});
	};
*/

// Resize новостей на главной
    if ($('.news_index_wrapper').length > 0) {
        if ($(document).width() > 1235) {
            $('.news_index_wrapper').css('width', '250px');
        } else {
            $('.news_index_wrapper').css('width', '17%');
        }
        }
        
    if ($('.apartment_location').length > 0 && $('.ap_full_desc').length > 0) {
        if ($(document).width() > 1235) {
            $('.apartment_location').css('width', '100%');
        } else {
            $('.apartment_location').css('width', '300px');
        }
        }
    
// APARTMENTS CAROUSEL
if ( $('ul.previv').length > 0 ) {	$('ul.previv').jcarousel(); }
if ($('.ap_gal_big_photo_wrapper').length > 0) {
loadImgs([	$(".ap_gal_big_photo_wrapper img"), $("ul.previv li a img") 
			], function() {
             $('#bigImg').fadeIn("fast");
             $('ul.previv li.jcarousel-item a img:first').hide();
		});
$('ul.previv li.jcarousel-item a').live('click', function(){
    $('ul.previv li.jcarousel-item a img:hidden').show();
    bigpic = $(this).attr('href');
    $(this).children('img').hide();
    $('#bigImg').fadeOut("fast", function() {
    loadImgs([	$("<img src='" + bigpic + "' />") 
			], function() {
			 $('#bigImg').attr('src', bigpic);
             $('#bigImg').fadeIn("fast");
		});       
    });
    return false;
})
}

if ($('.ap_full_desc').length > 0) {
    var height = $('.ap_full_desc_inside').height();
    if (height < 406) {$('.ap_full_desc_inside').height('406px'); }  
}
// APARTMENTS CAROUSEL END

// Пересчет валют
if ( $('#curr').length > 0 ) {
	$('#curr select').change(function(){
		$(this).parent().ajaxSubmit({
		  success: function() {
              document.location.reload();
		}
        });
		return false;
	})
}
// Пересчет валют конец

	$('div.blocks_type_2_wrapper div.block_type_2:last, div.blocks_type_1_wrapper div.block_type_1:last, div.blocks_type_1_wrapper div.block_type_3:last').css({'border-bottom': 'none'});

// Отправка резюме
if ($("#rezumeForm").length > 0) {
	$(".sendform_button").click(function(){
		$(this).parent().parent().submit();
	})
	
	$('#rezumeForm').prepend('<div class="warnText"></div>');
	
	$("#rezumeForm").validate({
		submitHandler: function() {
			sendform_vacancy ();
		},
		
		errorElement: "p",
		errorLabelContainer: $(".warnText"),
		
		rules: {
			f_Name: "required",
			f_Vacancy: "required",
			f_Text: "required"
		},
		messages: {
			f_Name: "Введите имя!",
			f_Vacancy: "Введите название компании!",
			f_Text: "Введите комментарий!"
		}
	});
}
// Отправка резюме конец


// Контакты
/*
if ($(".map_1, .print_link").length > 0) {
    $(".map_1, .print_link").colorbox({
		iframe: true,
        width: '750px',
        height: '710px'
	});
}
*/

if ($(".map_1, .print_link").length > 0) {
    $(".map_1, .print_link").colorbox({
        iframe:true,
        width:'750px',
        height:'710px',
        href: function() {
          var link_1 = $(this).attr('href');
          return link_1 + '?template=999';
          }
        });
};


if ($("a[rel='layout_gal']").length > 0) {
	$("a[rel='layout_gal']").colorbox();
}

if ($(".favsbmt, #addfavsbmt").length > 0) {
	$('.favsbmt, #addfavsbmt').live('click', function() {
		$(this).parent('form').ajaxSubmit({
//          target: '#fav_wrapp',
          success: function(msg){ document.location.reload(); }
		});
		return false;
	});
}

// CHECKBOX BEGINS
	if ($('.specials_leftside').length > 0 || $('.specials_rightside').length > 0 ) 
			 $('.specials_leftside .specials_list_wrapper .specials_list_double>li:gt(1), .specials_rightside .specials_list_wrapper .specials_list_double>li:gt(1)').hide(); 
		else $('.specials_list>li:gt(3)').hide();		


	$('.next').click( function () {
		var ul = $(this).parents('.specials_leftside').find('.specials_list_wrapper ul');
		ul_content = ul.html();
		if (!ul_content) { ul = $(this).parents('.specials_rightside').find('.specials_list_wrapper ul');}		
		if ($(this).parent().parent().hasClass('long')) {ul = $(this).parents('.specials_wrapper').find('.specials_list_wrapper ul');}				
		
		var len = ul.find('li:visible').length;	
		ul.find('.clear').remove();		
		var first = '<li>'+ul.find('li:first').html()+'</li><div class="clear"></div>';
		ul.find('li:first').remove();
		ul.find('li').hide();
		ul.append(first);
		ul.find('li:gt('+ len +')').hide();
		ul.find('li:lt('+ len +')').show();

		return false;
	});
	
	
	$('.prev').click( function () {
		var ul = $(this).parents('.specials_leftside').find('.specials_list_wrapper ul');
		ul_content = ul.html();
		if (!ul_content) { ul = $(this).parents('.specials_rightside').find('.specials_list_wrapper ul');}
		if ($(this).parent().parent().hasClass('long')) {ul = $(this).parents('.specials_wrapper').find('.specials_list_wrapper ul');}	
		
		var len = ul.find('li:visible').length;	
		var last = '<li>'+ul.find('li:last').html()+'</li>';
		ul.find('li:last').remove();		
		ul.find('li').hide();		
		ul.prepend(last);
		ul.find('li:gt('+ len +')').hide();
		ul.find('li:lt('+ len +')').show();

		return false;
	});
	
	
	// INDEX SLIDE SHOW NAVY BEGINS
	$('ul.slideshow_img li:gt(0)').hide();
	$('.photo_slideshow_navy .navy_right .next').click( function () {
		var slideshow_imgs = $('.slideshow_img li');
		var tec = slideshow_imgs.index($('.slideshow_img li:visible'));
		var nex = tec + 1;
		if ( slideshow_imgs.length-1 < tec+1 ) nex = 0;
		change_slideshow_img ( tec, nex);
	});
	$('.photo_slideshow_navy .navy_left .prev').click( function () {
		var slideshow_imgs = $('.slideshow_img li');
		var tec = slideshow_imgs.index($('.slideshow_img li:visible'));
		var nex = tec - 1;
		if ( tec-1 < 0 ) nex = slideshow_imgs.length-1;
		change_slideshow_img ( tec, nex);
	});
	// INDEX SLIDE SHOW NAVY ENDS
	
	
	// INNER FORMS AND PATHS SLIDE BEGINS
	$('#close_bt').live('click', function() {
		$(this).parent().parent().slideUp(500);
		$(this).parent().parent().prev().slideDown(250);
		$(this).hide();
		$('#show_bt').show();
        fl = '1'
	});
	$('#show_bt').live('click', function() {
	   if (navigator.appName.indexOf("Microsoft") == -1 || window.fl != '1') {
	       setTimeout("chk_toflash();", 2000);
        }
		$(this).parent().parent().slideUp(500);
		$(this).parent().parent().next().slideDown(250);
		$(this).hide();
		$('#close_bt').show();
	});
	// INNER FORMS AND PATHS SLIDE ENDS
	
	// MAIN NAVY SUB MENU BEGINS
	$('.main_navy li').hover(
		function(){
			$(this).addClass('active');
			$(this).find('ul').stop(true, true);
			$(this).find('ul').slideDown(200);
		},
		function (){
			$(this).removeClass('active');
			$(this).find('ul').stop(true, true);
			$(this).find('ul').slideUp(300);
		}
	);
	
	$('.main_navy li:last').css({'margin':0})
//	$('.main_navy').append('<div class="clear"></div>')
	// MAIN NAVY SUB MENU ENDS
	
	if ($('ul.sort_by').length > 0) {
	$('ul.sort_by li a').live('click', function() {
	   var direction = $(this).attr('href').slice(1);
       var wht = $(this).attr('rel');
       $('#mainsearch').find('input[name=datesort]').val('');
       $('#mainsearch').find('input[name=pricesort]').val('');
       $('#mainsearch').find('input[name=' + wht + 'sort]').val(direction);
       if (wht == 'date') { $('#mainsearch').find('input[name=pricesort]').val('1'); }
       if (wht == 'price') { $('#mainsearch').find('input[name=datesort]').val('1'); }
       $('#mainsearch').submit();
       return false;
	})
    }
	
    // Обработка раскрывающихся списков
    if ($('div.drop_list').length > 0) {
        setTimeout("chk_toflash();", 3000);

	// Открытие
	$('div.drop_list').live('click', function(){
	        $('.list_with_checkboxes').each(function(){
           var height = Number($(this).height());
           if (height > '335') {
            $(this).css('height', '335px');
           } 
        });
		$('div.drop_list_active:visible').next('ul.list_with_checkboxes').slideUp('fast');
		$(this).removeClass('drop_list');
		$(this).addClass('drop_list_active');
		$(this).next('ul.list_with_checkboxes').slideDown('fast').addClass('drop_list_opened');
        hover_drop_list(this);
	})
    
	// Закрытие
	$('div.drop_list_active').live('click', function(){
		$(this).next('ul.list_with_checkboxes').slideUp('fast').removeClass('drop_list_opened');
		$(this).removeClass('drop_list_active');
		$(this).addClass('drop_list');
        hover_drop_list(this);
	})
    

    }
      
    $('ul.list_with_checkboxes input:checkbox').live('click' ,function(){
        var id = $(this).parent().parent().attr('id');
        idtoflash = $(this).attr('value');
        if ($('#' + id).hasClass('toflash')) {thisMovie('flash').jsToFlashHandler(idtoflash);} 
        if ($('#' + id).hasClass('list_aj')){ checked_boxes_conn(id, idtoflash); }
        checked_boxes(id);   
	});
	
	// List with checkboxes end

});

$(window).resize(function(){
    
    if ($('.news_index_wrapper').length > 0) {
        if ($(document).width() > 1235) {
            $('.news_index_wrapper').css('width', '250px');
        } else {
            $('.news_index_wrapper').css('width', '17%');
        }
        }
});

function thisMovie(flash) {
    if (navigator.appName.indexOf("Microsoft") != -1) {
        return window[flash];
// return window.document.flash;
    }
    else {
        return document[flash];
// return window.document.flash;
    }
}

function flashToJSHandler (id) {
    $('ul.toflash input:checkbox').each(function() {
       if ($(this).attr('value') == id) {
        if ($(this).attr('checked') ) {
            $(this).removeAttr('checked');
        } else {
            $(this).attr('checked', true);
        }
    var ids = $(this).parent().parent().attr('id');
    checked_boxes(ids);
       } 
    });
}

function chk_toflash() {
    $('ul.toflash input:checked').each(function() {
    var id = $(this).parent().parent().attr('id');
    var idtoflash = $(this).attr('value');
    thisMovie('flash').jsToFlashHandler(idtoflash);
    if ($('.list_aj').length > 0){ checked_boxes_conn(id, idtoflash); }
    checked_boxes(id);    
    });
}

// INDEX SLIDE SHOW BEGINS
function change_slideshow_img (tec, nex) {
	$('.slideshow_img li:eq(' + tec + ')').fadeOut(500);
	$('.slideshow_img li:eq(' + nex + ')').fadeIn(500);
	var str = $('.slideshow_img li:eq(' + nex + ') img').attr('alt') + '<em>' + $('.slideshow_img li:eq(' + nex + ') img').attr('title') + '</em>';
	$('.photo_slideshow_navy .photo_desc').html(str);
}
// INDEX SLIDE SHOW ENDS

// Load IMGs BEGIN
function loadImgs(images, callback) {
	var loaded = {};
	$(images).each(function() {
		if ($(this).length > 0) {
			$(this).each(function() {
				loaded[$(this).attr("src")] = false;
			});
		}
	});
	$(images).each(function() {
		if ($(this).length > 0) {
			$(this).each(function() {
				$(new Image()).load(function() {
					loaded[$(this).attr("src")] = true;
					var l = true;
					$.each(loaded, function(i, n) {
						if (this != true) l = false;
					});
					if (l) callback.call();
				}).attr("src", $(this).attr("src"));
			});
		} else {
			callback.call();
		}
	});
}
// Load IMGs END

function insertflash (swfpath, xmlpath, id, width, height) {
       var flashvars = {
            xmlURL: xmlpath
        };
       var params = {
            menu: 'false',
            quality: 'high',
            wmode: 'transparent',
            allowFullscreen: 'false',
            allowScriptAccess: 'always',
            name: id
        };
    swfobject.embedSWF(swfpath, 'flash', width, height, '9.0.0', '/netcat_files/swf/Scripts/expressInstall.swf', flashvars, params, null);
}

	//Vivod otmechennih chekboksov
function checked_boxes (id) {
    var chb_cont = '';
	$('#' + id + ' li').find('input:checked').each(function() {
            chb_cont += $(this).next('label').text() + ', ';
            });
            chb_cont = chb_cont.slice(0, -2);
		$('#' + id).prev('div').html(chb_cont);
}

function checked_boxes_conn (id, val) {
    var nextul_id = $('#' + id).parent().parent().next().find('ul').attr('id');
    var result = $('#' + nextul_id);
    if ($('div#sale_form').length > 0) { var rentsale = '2'; }
    if ($('div#rent_form').length > 0) { var rentsale = '1'; }

    if ($('#' + id + ' li').find('input:checked').length > 1) {
        if (nextul_id == 'ultube') {
            var direct = '';
            $('#' + id + ' li').find('input:checked').each(function(){
            var inval = $(this).val();
               direct += '' + inval + ',';
            });
        }
    } else {
        if ($('#' + id).find('input[value=' + val + ']').is(':checked')) {
            var direct = val;
            } else {
                var direct = '';
                var rentsale = '';
                }
            }

            if (nextul_id == 'ultube') { url = '/xml/city/connection.html'; }
            if (nextul_id == 'uldoplotname') { url = '/xml/outside/connection.html'; }

        $.ajax({
		    url: url,
            type: 'GET',
            data: ({direction : direct, rentsale: rentsale}),
            async: false,
            success: function(msg){ $(result).html(msg); }
    	});
     // Пересчет высоты получившегося списка
     $('#' + nextul_id).css('height', null);
     var height = Number($('#' + nextul_id).height());
     if (height > '335') { $('#' + nextul_id).css('height', '335px'); }  
}


function sendform_vacancy () {
	$('#rezumeForm').ajaxSubmit({
		beforeSubmit: function() {
			$('input.sendform_button').attr('disabled', 'disabled');
			$('input.sendform_button').attr('value', '...Отправка...');
		},
					
		target: '.s_m_middle'
	});

}

// OnHover Drop List
function hover_drop_list() {
    $('ul.list_with_checkboxes').hover(null, function(){
		if ($(this).hasClass('drop_list_opened')) {
			$(this).removeClass('drop_list_opened').delay(600).slideUp('fast', function(){
			$(this).prev().removeClass('drop_list_active');
            $(this).prev().addClass('drop_list'); 
			});
		}
	})
}
