function getcode_href_click() {
	$('.getcode_code').toggle();
	if ($('.getcode_code > .getcode_textarea').text() == '') {
		var gch = $('.getcode_head');
		var gct = $('.getcode_text');
		$('.getcode_code > .getcode_textarea').text('<p><a href="' + document.location.href.toString() + '">' + gch.html() + '</a></p>' + gct.html() + '<p>Источник: <a href="http://fasadinfo.com/">Fasadinfo.com</a></p>');
	}
}


function basename (path, suffix) {
    var b = path.replace(/^.*[\/\\]/g, '');
        if (typeof(suffix) == 'string' && b.substr(b.length-suffix.length) == suffix) {
        b = b.substr(0, b.length-suffix.length);
    }
    return b;
}


function checkFileNames() {
	errtxt = "";
	$('input[type=file]').each(function() {
		v = basename($(this).val());
//		alert(v);
		if ( v != '' && !v.match(/^[\w-\.]+$/i) ) {
			errtxt += "В имени файла допустимы только _латинские_буквы_.\n";
		}
	});
	if (errtxt != "") {
		alert(errtxt);
		return false;
	}
}


var map = null;
var geocoder = null;

function showGoogleMaps(maps_id, maps_lat, maps_lng, maps_zoom, cur_markers ) {
	if (GBrowserIsCompatible()) {

		if ( (maps_lat==undefined) ||(maps_lng==undefined)) {
			return false;
		}

		if (maps_zoom==undefined)
			maps_zoom = 8;

		map = new GMap2(document.getElementById(maps_id));

		map.addControl(new GLargeMapControl());
		map.addControl(new GMapTypeControl());
		map.addControl(new GScaleControl()) ;
		map.addControl(new GOverviewMapControl()) ;

		map.setCenter(new GLatLng(maps_lat, maps_lng), maps_zoom);

		geocoder = new GClientGeocoder();

		if (cur_markers != undefined) {
			for (i in cur_markers) {
				cur_marker = cur_markers[i];
				var point = new GLatLng(cur_marker[0], cur_marker[1]);
				var marker = createMarker(point, cur_marker[2])
				map.addOverlay(marker);
				if (cur_marker[2].substr(0,1) != " ") {
					map.setCenter(new GLatLng(cur_markers[i][0], cur_markers[i][1]), maps_zoom);
				}
			}
		}

	//GBrowserIsCompatible()
	}
}

// A function to create the marker and set up the event window
// Dont try to unroll this function. It has to be here for the function closure
// Each instance of the function preserves the contends of a different instance
// of the "marker" and "html" variables which will be needed later when the event triggers.
function createMarker(point,html) {
	var marker = new GMarker(point);
	GEvent.addListener(marker, "click", function() {
		marker.openInfoWindowHtml(html);
	});
	return marker;
}

// addAddressToMap() is called when the geocoder returns an
// answer.  It adds a marker to the map with an open info window
// showing the nicely formatted version of the address and the country code.
function addAddressToMap(response) {
	//map.clearOverlays();
	if (!response || response.Status.code != 200) {
//		alert('Адрес «' + address + '» не найден');
//		alert('Адрес не найден');
	} else {
		place = response.Placemark[0];
		point = new GLatLng(place.Point.coordinates[1],
							place.Point.coordinates[0]);
		map.setCenter(point, 13);
		marker = new GMarker(point);
		map.addOverlay(marker);
		marker.openInfoWindowHtml(place.address// + '<br>' +
			//'<b>Country code:</b> ' + place.AddressDetails.Country.CountryNameCode);
		);
	}
	if (place != undefined) {
		$('#image').val(place.Point.coordinates[1] + "," + place.Point.coordinates[0]);
	}
}

// showLocation() is called when you click on the Search button
// in the form.  It geocodes the address entered into the form
// and adds a marker to the map at that location.
function showLocation(loc) {
	var address = loc;
	geocoder.getLocations(address, addAddressToMap);
}



function showRegionsShow() {
	$('#regionsList').slideUp();
	$('#regionsShow').show();
}

function showRegionsList(cat_url, get_only) {
	if (cat_url == undefined)
		cat_url = false;

	if (get_only == undefined)
		get_only = false;

	if ( $('#regionsList').html() == '' ) {
		$('#regionsList').html('<table cellpadding="0" cellspacing="0" border="0"  class="content" width="98%" align="center" id="regionsShow"><tr><td colspan="2" align="left" valign="top" class="maintext" height="22" style="color:black;">Регион: <img src="/front/loader.gif" style="vertical-align:-4px;" /></td></tr></table>');
		$.post('/getRegionsList.php', {cat_url: cat_url, get_only: get_only}, function(data) {
			if (data) {
				$('#regionsList').html(data);
			}
		});
	}

	$('#regionsShow').hide();
	$('#regionsList').slideDown();
}


function checkForm(curr_type, have_email, have_stars) {
	if (curr_type  == undefined)	curr_type  = false;
	if (have_email == undefined)	have_email = false;
	if (have_stars == undefined)	have_stars = false;

	err = 0;
	errtxt = '';
	$('.required').each( function() {
		if ( !$(this).val() ) {
			$('#p_'+$(this).attr('name')).css('color','red');
			err++;
		} else {
			$('#p_'+$(this).attr('name')).css('color','');
		}
	} );
	if ( err ) {
		errtxt += have_stars ? "Поля, отмеченные звездочками, обязательны для заполнения.\n" : "Все поля обязательны для заполнения.\n";
	}

	if (have_email) {
		email = $("input[name='"+have_email+"']").val();
		if ( !email || !isValidEmail(email) ) {
			$('#p_'+have_email).css('color','red');
			errtxt += 'Введен некорректный Е-Мail.\n';
		}
	}

	if (curr_type == 'video') {
		image_file = $('input[name=image]').val();
		if ($('input[name=image]').hasClass('required')) {
			if ( (image_file.indexOf('.swf') <= 0) && (image_file.indexOf('.SWF') <= 0) && (image_file.indexOf('.flv') <= 0) && (image_file.indexOf('.FLV') <= 0) )  {
				errtxt += "Вы можете загрузить только SWF или FLV файлы.\n";
			}
		}
	}
	if (curr_type == 'techcats') {
		image_file = $('input[name=image]').val();
		if ($('input[name=image]').hasClass('required')) {
			if ( image_file.indexOf('.pdf')<=0 && image_file.indexOf('.PDF')<=0 )  {
				errtxt += "Вы можете загрузить только PDF файлы.\n";
			}
		}
	}
	if (curr_type == 'maps') {
		$('#text1').val($('#text1_1').val() + '(_!_)' + $('#text1_2').val());
	}

	$('input[type=file]').each(function() {
		v = basename($(this).val());
		if ( v != '' && !v.match(/^[\w-\.]+$/i) ) {
			errtxt += "В имени файла допустимы только _латинские_буквы_.\n";
		}
	});

	if (errtxt) {
		alert(errtxt);
		return false;
	}

	return true;
}
function isValidEmail(email) {
	return (/^([a-z0-9_\-]+\.)*[a-z0-9_\-]+@([a-z0-9][a-z0-9\-]*[a-z0-9]\.)+[a-z]{2,4}$/i).test(email);
}


function symbols(f_name, max, s_name) {
	MAX = max;
	var field    = document.getElementById(f_name);
	var symbols  = document.getElementById(s_name);
	var subm_but = document.getElementById('subm_but');
	if (field.value.length > MAX) {
		color = "red";
		decor = "underline";
		subm_but.disabled = true;
	} else {
		color = "black";
		decor = "none";
		subm_but.disabled = false;
	}
	symbols.innerHTML = 'Введено: <span style="color:' + color +'; text-decoration:' + decor + ';">' + field.value.length + '</span> симв.';
}


$(document).ready(function() {
	$('#topsearch_form').submit(function() {
		if ( !$("#topsearch_field").val() || $("#topsearch_field").val() == 'Поиск по каталогу...' )
			return false;
		return true;
	});
	$('#topsearch_field').focus(function() {
		if ( $(this).val() == 'Поиск по каталогу...')
			$(this).val('');
		$(this).css('color', 'black');
	});
	$('#topsearch_field').blur(function() {
		if ($(this).val() == '')
			$(this).val('Поиск по каталогу...').css('color', '#ACA899');
	});

/*	if ($('#odnaknopka').length == 1) {
		$('#odnaknopka').html('<script src="http://odnaknopka.ru/ok2.js" type="text/javascript"></script>');
	}
*/

	if ($('.labeled_selects').length > 0) {

		$('.labeled_selects label > input[type=checkbox]').bind('change', function() {
			$(this).parent('label').parent('td').css({'font-weight':($(this).attr('checked')?'bold':'normal')}) 
		})
		
		$('.labeled_selects label > input[type=checkbox]:checked').each(function() {
			$(this).parent('label').parent('td').css({'font-weight':($(this).attr('checked')?'bold':'normal'), 
													  'backgroundColor':'#e0e0e0'}) 
		});

	}
	
});


function getCallback(){
    if(!$('input[name=phone_number]').val() || !isNumeric($('input[name=phone_number]').val())){
        alert('Введите корректный номер телефона');
        $('input[name=phone_number]').val('');
        return false;
    }

    if(!$('input[name=client_name]').val()){
        alert('Введите имя');
        return false;
    }



    $.post('/contact/getCallback/0/5/0', $('#getcallback').serialize(),
            function(e){

                $('.get_callback input').val('');
                $('.get_callback_tr').hide();
                $('.get_callback').hide();

                if(e.err == '0'){
                    $('#get_callback').hide();
                    alert('Запрос отправлен');
                }
                else
                    alert('Запрос небыл отправлен');

            }, 'json');
}

function isNumeric(n) {
  return !isNaN(parseFloat(n)) && isFinite(n);
}
