jQuery.ajaxSetup({contentType: "application/x-www-form-urlencoded; charset=utf-8"});

var valid = 0;
$(document).ready(function(){
	// menu
	$('div#menu a').click(function(){
		var index = $('div#menu > a').index(this);
		return get_page(index+1);
	})
	
	$('div.special').click(function(){
		return get_page(1);
	})
	
	// menu oferta
	$('ul.ul_oferta > li span').click(function(){
		$('ul.ul_oferta li ul').hide();
		$('ul.ul_oferta > li').removeClass('selected');
		$(this).parent().addClass('selected');
		$(this).parent().children('ul').slideDown();
	})
	
	// form request
	$('a#request_send').click(function(){
		valid = 0;
		var regEmail = /^.+\@.+\..+$/;
		
		var request_name = $('input[name="request[name]"]');
		var request_company = $('input[name="request[company]"]');
		var request_email = $('input[name="request[email]"]');
		var request_phone = $('input[name="request[phone]"]');
		var request_text = $('textarea[name="request[text]"]');

		$('span.error').remove();
		// validation form
		if(request_name.val().length == 0) error("Wymagane!", request_name);
		if(request_company.val().length == 0) error("Wymagane!", request_company);
		if(request_email.val().length == 0) error("Wymagane!", request_email); else if(!regEmail.test(request_email.val())) error("Niepoprawny e-mail!", request_email);
		if(request_text.val().length == 0) error("Wymagane!", request_text);
		
		// send
		if(valid == 0){
			$.ajax({
				type: "POST",
				url: "/inc/ajax_send_request.php",
				data: "name="+encodeString(request_name.val())+"&company="+encodeString(request_company.val())+"&email="+request_email.val()+"&phone="+encodeString(request_phone.val())+"&text="+encodeString(request_text.val()),
				success: function(msg){
					$('span.msg').html(msg);
					$('input, textarea').val('');
					get_view('4b');
				}
			})
		}
		return false;
	})
	
	// change backgrounds
	$('div#backgrounds a').click(function(){
		$('div#backgrounds a').removeClass('selected');
		$(this).addClass('selected');
		
		$('#background').css("background-image", "url('" + $(this).attr("href") + "')");
		
		return false;
	})
});

function get_view(id){
	$('#box_02_wrap div.text').hide();
	$('#view_'+id).show();
	$('#box_02_wrap').hide().slideDown();
	return false;
}

function get_page(index){
	$('#box_02_wrap').slideUp();
	$('div#box_01 div.content').hide();
	$('div#box_01 > div.content').eq(index).show();
	return false;
}

function error(msg, el){
	valid = 1;
	el.parent().children('label').append('<span class="error">'+ msg +'</span>');
	$('span.error').fadeIn();
}

function encodeString(text) {
	encoded = text.replace("///g","%2F");
	encoded = encoded.replace("/?/g","%3F");
	encoded = encoded.replace("/=/g","%3D");
	encoded = encoded.replace("/&/g","%26");
	encoded = encoded.replace("/#/g","%23");
	encoded = encoded.replace("/@/g","%40");
	encoded = encoded.replace("/r/g","");
	encoded = encoded.replace("/n/g","%0A");
	
	return encodeURIComponent(encoded);
}