jQuery(document).ready(function()
{
    setTimeout(function() {
    placesForm("right_places");

    var COOKIE_NAME = 'front-ciazowy_pl';

    use_tabs("#tabframe");
//    use_tabs("#tabcalendar");

    $("#calc .cf1, #calc .cf2").click(function()
    {
        var classname = $(this).attr("class");

        $("#calc li.active").removeClass("active");
        $("#calc a.active").removeClass("active");
        $("#calc a."+classname).addClass("active");
        $("#calc a."+classname).parent().addClass("active");

        $("#calc .content div:visible").hide();
        $("#calc .content div#"+classname).show();
    });



    //top frame hiding
    $(".top_hide").click(function()
    {
            $(".topframe").toggle();

            //cooking ^^
            str = $.cookie(COOKIE_NAME);
            re = new RegExp("tpfrm=[0-9]");

            if(str) {
                replaced = str.replace(re,"tpfrm=0");
            }
            else {
                replaced = "tpfrm=0";
            }
            $.cookie(COOKIE_NAME, replaced, { path: '/', expires: 30 });
            return false;
    });


    //----------------- ajax login ----------
    addLoginActions();

    // ajax login form
    $('a.login_trigger').click(function()
    {
//    	alert("jestem tutaj");
    	var url = window.location.pathname;
    	if (url!="/logowanie.html"){
	        $($("#login_form_partial"), {close: true}).modal({});
	        window.scrollTo(0,0);
	        return false;
    	}
    });
    //----------------- eo ajax login ----------


    //----------------- ajax registration ----------
    addRegistrationActions();

    // ajax login form
    $('a.register_trigger').click(function()
    {
    	var url = window.location.pathname;
    	if (url!="/rejestracja.html"){
	        $.modal.close();
	        $($("#register_form_partial"), {close: true}).modal({});
	        return false;
    	}
    });
    //----------------- eo ajax registration ----------

    //----------------- Report an error form ----------
    addReportAnErrorActions();
    $("#rae_link").val(window.location.href);
    //----------------- eo Report an error form ----------    
        
    //----------------- poll ----------
	var polls = $("[poll_id]");
	

	
	for(var i=0; i<polls.length; i++){
		var onePoll = polls[i];
		var idPoll = $(onePoll).attr('poll_id');
		
		$.post(
			'poll/ajax-form-poll',
			{					
				id_poll: idPoll
			},
			function(response) {		
	    		var selector = '[poll_id='+response.idPoll+']';
	    		$(selector).html(response.html);
	    		var total = $(selector+" h4").attr('poll_total');
	    		var maxPercent = $(selector+" h4").attr('poll_max');
	    		var maxWidth = 237;				
				
	    		drawPollResults(selector, total, maxPercent, maxWidth);
			},
			'json'
		);		
	}
	
	$(".pollmod input[name=answer]:radio").live('click', function(e)
	{				
		var idPoll = $(this).parents(".pollmod").attr('poll_id');
		var idAnswer = $(this).val();
							
		$.post(
	    	'poll/ajax-vote-poll',
	    	{
	    		id_answer: idAnswer,
	    		id_poll: idPoll
	    	},
					
	    	function(response) {
	    		var selector = '[poll_id='+response.idPoll+']';
	    		$(selector).html(response.html);
	    		var total = $(selector+" h4").attr('poll_total');
	    		var maxPercent = $(selector+" h4").attr('poll_max');
	    		var maxWidth = 237;
	    		
	    		drawPollResults(selector, total, maxPercent, maxWidth);
	    	},
	    	'json'
		);
		return false;		
	});
		
	
	function drawPollResults(selector, total, maxPercent, maxWidth)
	{
		var onePercentInPixels = maxWidth/maxPercent;		
		$(selector+" .results").slideDown("slow", function() {
	        $(selector+" .result").each(function(i) {
	        	var votes = $(this).attr('poll_votes');
	        	$(this).animate({ width: Math.round((votes / total * 100) * onePercentInPixels) }, "slow");
	        });
	        
	        $(selector+" .result span").each(function(i) {
	        	$(this).css('display', 'block');
	        });
        });
	}		
	
	
	var staticPollContainer = $(".wynikiSonda").val();
	if (staticPollContainer!=undefined){
		var selector=".wykres";
		var total = $(selector).attr('poll_total');
		var maxPercent = $(selector).attr('poll_max');
		var maxWidth = 237;
		
		drawPollResults(selector, total, maxPercent, maxWidth);
	}
	
	
	
    //----------------- eo poll ----------
	

    //----------------- newsletter ----------
    addNewsletterActions();
    //----------------- eo newsletter ----------

    $('a.forgotten_trigger').click(function()
    {
        $.modal.close();
        $($("#forgotten_password_partial"), {close: true}).modal({});
        return false;
    });

    addRestorePasswdActions();

    setTimeout(function() {
        $('.info_box').hide(400);
    }, 5000);


    rotateSuper();
    }, 100);
    
    scrollToResultOfWeightAndSizeFetusCalculator();
   
    $("#week_of_pregnancy").click(function(){
    	$("#last_period_start_day, #last_period_start_month, #last_period_start_year").find('option:first').attr('selected', 'selected').parent('select');
    });
    
    $("#last_period_start_day, #last_period_start_month, #last_period_start_year").click(function(){
    	$("#week_of_pregnancy").find('option:first').attr('selected', 'selected').parent('select');
    });
});


function scrollToResultOfWeightAndSizeFetusCalculator()
{
	var result = $(".kalkulatorWagiPlodu_wynikMiara").attr('class');
	
	if (result) {
		window.location.hash = "#kalkulatormiary";
	}
}

function rotateSuper()
{
    setTimeout(function() {
        if ($('#supertemat_box > div.act').next('div').length) {
            $('#supertemat_box > div.act').next('div').find('h2 a').click();
        }
        else {
            $('#supertemat_box').children(':first').find('h2 a').click();
        }
        rotateSuper();
    }, 12000);
}


function placesForm(element){
    var form = $("#"+element);

    // load cities for regions
    $.get(
            'places/ajax-cities',
            {},
            function(response){
                CITIES = response.regions;
            },
            'json'
    )

//    // places (rights side bar)
    form.find(".region").change(function ()
    {
        var reg_id = $(this).val();
        if(reg_id == '-1'){
            form.find(".city").attr("disabled", true);
            form.find(".city").attr("value", "-1");
        } else {
            var html = "<option value=\"-1\">" + translate["all"] + "</option>";
            for(var i=0; i<CITIES[reg_id].cities.length; i++){
                html += "<option value=\"" + CITIES[reg_id].cities[i].city_id + "\">" + CITIES[reg_id].cities[i].city_name + "</option>"
            }
            form.find(".city").html(html);
            form.find(".city").removeAttr("disabled");
        }
    });

    form.find(".fsearch").click(function()
    {
        var reg_id = form.find(".region").val();
        var city_id = form.find(".city").val();
        var plc_type = form.find(".type").val();

        // ROUTER
        var url = "placowki,%reg_id%,%city_id%,%plc_type%,strona-1.html";
        var new_url = url;

        re_reg_id = new RegExp("%reg_id%");
        re_city_id = new RegExp("%city_id%");
        re_plc_type = new RegExp("%plc_type%");

        new_url = new_url.replace(re_reg_id, reg_id);
        new_url = new_url.replace(re_city_id, city_id);
        new_url = new_url.replace(re_plc_type, plc_type);

        window.location = base_host + base_url + new_url;
    });
}

/*
 * Add default value do input if equals ''
 *
 * @param selector
 * @param defaultValue
 * @param active_class class which will be added after focus on element
 * @param inactive_class class which will be added after element blur
 */
function addDefaultValue(selector, defaultValue, active_class, inactive_class)
{
    $(selector).addClass(inactive_class);

    $(selector).each(function() {
        if ($.trim(this.value) == ''){
            this.value = defaultValue;
        }
    });

    $(selector).focus(function() {
        $(this).removeClass(inactive_class).addClass(active_class);
        if ($.trim(this.value) == defaultValue){
            this.value = '';
        }
    });

    $(selector).blur(function() {
        $(this).removeClass(active_class).addClass(inactive_class);
        if ($.trim(this.value) == ''){
            this.value = defaultValue;
        }
    });
}


// block submit on ajax sing up newsletter form
// add onclick action to submit button

function addNewsletterActions() {
    $('#newsletter_form  #submit').click(function (){
        var email = $("#newsletter_form #email").val();

        $.post(
                'right-bar/ajax-join-newsletter',

                {email: email},
                function(response) {
                    $('#newsletter_form').replaceWith(response.html);
                    addNewsletterActions();
                },
                'json'
            );

        return false;
    });
}

function use_tabs(element)
{

    $(element+" li a").click(function()
    {
        $(element+" .active").removeClass("active");
        $(element+" .active").parent().removeClass("active");
        $(this).addClass("active");
        $(this).parent().addClass("active");

        var classname = $(this).attr("class");

        $("div#tabs div.text_tab:visible").hide();
        $("div#tabs div#full_"+$(this).attr("id")).show();

        return false;
    });
}


// block submit on ajax login form
// add onclick action to submit button on cancel button
function addRegistrationActions() {
    //$("#register_form_ajax").submit(function(){return false});
	 $("#modalContainer #register_form").live('submit', function(e) {
        var user_login = $("#register_form #user-user_login").val();
        var user_password = $("#register_form #user-user_password").val();
        var user_password_confirmation = $("#register_form #user-user_password_confirmation").val();
        var user_email = $("#register_form #user-user_email").val();
        var user_email_confirmation = $("#register_form #user-user_email_confirmation").val();
        var user_fname = $("#register_form #user-user_fname").val();
        var user_surname = $("#register_form #user-user_surname").val();
        var sex = null;
        if ($("#register_form #user-user_sex-0").attr("checked") == true)
        {
            var sex = 0;
        }
        if ($("#register_form #user-user_sex-1").attr("checked") == true)
        {
            var sex = 1;
        }
        var newsletter = 0;
        if ($("#register_form #user-user_newsletter").attr("checked") == true)
        {
            var newsletter = 1;
        }

        var accept = 0;
        if ($("#register_form #user-accept").attr("checked") == true)
        {
            var accept = 1;
        }

        $.post(
            'registration/ajax-register',
            {user_login: user_login,
            user_password: user_password,
            user_password_confirmation: user_password_confirmation,
            user_email: user_email,
            user_email_confirmation: user_email_confirmation,
            user_fname: user_fname,
            user_surname: user_surname,
            user_newsletter: newsletter,
            user_sex: sex,
            accept: accept},
            function(response) {
                $('#register_form_partial').html(response.html);
                if(response.result == true) {
                    window.location = response.redirect_to;
                }
                addRegistrationActions();
            },
            'json'
        );
        e.preventDefault();
        return false;
    });

    $(".modalClose").click(function () {
        $.modal.close();

    });

}


// block submit on ajax login form
// add onclick action to submit button on cancel button
function addLoginActions() {
    $("#login_form_ajax").submit(function(){return false});
    $("#login_form_ajax #user-auth_user_login").keydown(function(e) {
        if (e.keyCode == 13) {
            $("#login_form_submit").click();
        }
    });
    $("#login_form_ajax #user-passwd").keydown(function(e) {
        if (e.keyCode == 13) {
            $("#login_form_submit").click();
        }
    });

    $("a.send_act_mail_trigger").click(function(){
        var login = $("#user-user_login").val();

        if (login == false) {
            login = $("#login_form_ajax #user-auth_user_login").val();
        }

        $.post(
                'authorization/ajax-send-activation-mail',
                {user_login: login},
                function(response) {
                    if(response.result) {
                        $.modal.close();
                        $('<div>'+response.result+'</div>').modal({});
                    }
                },
                'json'
            );
        return false;
    });


    //$("#submit").click(function () {
    $("#modalContainer form#login_form").live('submit', function(e) {
        $("#login_form_partial .login_msg").html(translate["loging_in_progress"]);
        var login = $("#login_form #user-auth_user_login").val();
        var passwd = $("#login_form #user-passwd").val();
        
        $.post(
            'authorization/ajax-login',
            {auth_user_login: login,
            passwd: passwd},
            function(response) {
                $('#login_form_partial').html(response.html);
                
                if(response.result) {

                    var redirect_to = $("#redirect_to").attr("href");
                    if (redirect_to) {
                        window.location = redirect_to;
                    }
                    else {
                        location.reload(true)
                    }
                }
                addLoginActions();
            },
            'json'
        );
        e.preventDefault();
        return false;
    });

    $(".modalClose").click(function () {
        $.modal.close();

    });

}


function switchSearchAction(system_addr, forum_addr){
    var form = $("#search_form");

//    // places (rights side bar)
    form.children(".search_place").change(function ()
    {
        var reg_id = $(this).val();
        if(reg_id == 1){
            form.attr("action", system_addr)
        } else {
            form.attr("action", forum_addr)
        }
    });

}


function addRestorePasswdActions() {
    $("#restore_trigger").click(function () {
        var email = $("#forgotten_email").val();
        $.post(
            'authorization/ajax-restore',
            {email: email},
            function(response) {
                $('#forgotten_password_partial').html(response.html);
                if(response.success == 1) {
                    $("#message_box .msg").html(response.msg);
                    $.modal.close();
                    $($("#message_box"), {close: true}).modal({});
                }
                addRestorePasswdActions();
            },
            'json'
        );
    });
}


function addReportAnErrorActions(){
	$('a.report_an_error_trigger').click(function(){
    	        $($("#report_an_error_partial"), {close: true}).modal({});
    	        window.scrollTo(0,0);
    	        return false;
	});

	$("#report_an_error_form_submit").click(function(){
		$.post(
				'index/ajax-report-an-error',
				{
					rae_title: $("#rae_title").val(),
					rae_error_type: $("#rae_error_type").val(),
					rae_link: $("#rae_link").val(),
					rae_description: $("#rae_description").val(),
					rae_email: $("#rae_email").val()
				},
				function (response, status){
					window.scrollTo(0,0);
					if(status == "success"){
						if(response['status'] == 'error'){
							$("#form_report_an_error").replaceWith(response['form']);
						}else{
							$("#form_report_an_error").replaceWith(response['message']);
							$("#report_an_error_form_submit").replaceWith('');
							setTimeout(function(){$.modal.close();}, 2000);
						}
					}
				},
				'json'
		);
	});

}
