function trim(str) {
    return str.replace(/^\s+|\s+$/g, '');
}

/*
	keyg: temporarily removed from top_bar.tpl,
	should be placed in one object that takes care of animation, validation, form generation etc
    

	TODO: submiting function should be out of keypress event handler - other events also can cause form to submit! (like pressing button)
*/

// show category tree
function toggle_category_browser() {                                        
    if ($('#category_browser_container').is(':visible')) {
        $('.search .button_browse').addClass('rolled_up').removeClass('selected');
        $('#category_browser_container').slideUp('fast' , function() {
            $('.advanced_search_button').css('width' , '144px');
            $('.advanced_search_button .button_browse a').html('Zaawansowane');
        });
    } else {
        $('.search .button_browse').removeClass('rolled_up').addClass('selected');
        $('.advanced_search_button').css('width' , '230px');
        $('#category_browser_container').slideDown('fast');
        $('.advanced_search_button .button_browse a').html('Wyszukiwanie zaawansowane');  
    }                 
}

function show_main_menu() {
    $('#header .dashboard .menu_show_button').hide();
    $('#header .dashboard .fields').show();
}

// toggling subcategories in the tree
$(function() {
	$('.button_open_subcategory').bind('click', function() {
		if ($(this).hasClass('open')) {
			$(this).removeClass('open').addClass('closed').parent().removeClass('selected');
			$('#subcategory_for_' + $(this).attr('id').substr(20)).slideUp();
		}
		else {
            $('#category_browser li').each( function() {
                if($(this).attr('id') != 'last_element') {
                    $(this).removeClass('selected');
                }
            });
			$('.button_open_subcategory.open').removeClass('open').addClass('closed');
			$('.subcategory_list').slideUp();
			$(this).removeClass('closed').addClass('open').parent().addClass('selected');
			$('#subcategory_for_' + $(this).attr('id').substr(20)).slideDown();
		}
		return false;
	});
});

function toggle_login_form()
{
    if (!$('#form_login .fields').is(':visible')) {
        $('#success').hide();
		$('.incorrect4').hide();
        $('#form_resetpassword').hide();
        $('#form_login_resetpassword').hide();
        $('#form_login_info_incorrect').hide();
		if (!$("#form_login").is(':visible')) {
			$('#form_login .fields').hide();
			$("#form_login").show();
        }
        $('#form_login .fields').fadeIn('normal');
        $('#form_login_email').focus();
    } else {
        $('#form_login .fields').fadeOut('normal');
    }
    return false;
}

function onkeydown_login_form(event)
{
    var obj = $(event.currentTarget);
    // enter pressed?
    if (event.keyCode == 13) { // ENTER
        switch (obj.attr('id')) {
            case 'form_login_email':
                // move focus to password field
                //$('#form_login_password').focus(); - we use fake password field
				$('#form_login_password').next().focus();
                break;

            case 'form_login_password':
                // login
                $('#form_login').submit();
                break;
        }
		return false;
    } else if (event.keyCode == 27) {   // ESC
        toggle_login_form();
        $(obj).blur();
    } else if (event.keyCode == 9 && obj.attr('id') == 'form_login_password') {  // TAB
		obj.blur();
		$('#form_login_email').focus();
		return false;
    }

}

function onkeydown_reset_password_form(event)
{
		return; 

	// enter pressed?
    if (event.keyCode == 13) { // ENTER
		return; 

        var email = $('#password-reset').val()
        $.post(config.api_url + 'reset_password',
		   {email: email},
		   function(json) {
				var res = eval(json);
				if (res.result == 'ok') {
					$('#form_resetpassword').fadeOut('fast', function() {
						$('#success').fadeIn('fast');
					});
				} else {
					$('.incorrect4').fadeIn('fast');
				}
		   });
    } else if (event.keyCode == 27) {   // ESC
        /*  toggle_login_form();
        $(obj).blur(); */
    }
}

// display reset password form
function reset_password()
{
    $('#form_login').fadeOut('fast', function() {
        $('#form_resetpassword').fadeIn('fast');
    });
//    $('#password-reset').focus(function() { if(this.value=='E-MAIL') this.value=''; });
//    $('#password-reset').keydown(onkeydown_reset_password_form);
}

// perform AJAX login, refresh site if succeed
function login_user(event)
{
	var email = $('#form_login_email').val();
	var password = $('#form_login_password').val();
	$.post(
		config.api_url + 'user_login',
		{email: email, password: password, remember_me: $('#remember-me').val()},
		(function (res) {
			if (res.result == 'ok') {
				// successful login
				var login_destination = config.base_url; 
				if (typeof(res.login_destination) == 'string') {
					login_destination = res.login_destination;
				}
				window.location = login_destination;
			}
			else {
				// invalid login
				$('#form_login_info_incorrect').fadeIn('fast');
				setTimeout( function()  { $('#form_login_resetpassword').fadeIn('fast');}, 500);
			}
		}),
		'json'
	);
	event.preventDefault();
	return false;
}

$(document).ready(function() {
    $('#form_login').bind('submit', login_user);
    $('#form_login_email').keydown(onkeydown_login_form);
    $('#form_login_password').keydown(onkeydown_login_form);
	$('form.login').submit(function() { return false; });	// temporary
//    $('.search #query').focus(function() { if(this.value=='SEARCH') this.value=''; });
//    $('.search #query').blur(function() { if(this.value == '') this.value='SEARCH';});

    $("a.checkbox-login").click( function(event) {
		event.preventDefault();
		if($(this).hasClass("selected-checkbox")) {
			$(this).removeClass("selected-checkbox");
			$(this).addClass("checkbox-select");
			$(this).siblings(".categories-checkbox").attr('checked', false);
			$('#remember-me').val(0);
		} 
		else {
			$(this).removeClass("checkbox-select");
			$(this).addClass("selected-checkbox");
			$(this).siblings(".categories-checkbox").attr('checked', true);
			$('#remember-me').val(1);
		}
	});

	$('#form_resetpassword').bind('submit', function(event) {
		var email = $('#form_resetpassword_email').val();
		$.ajax({
			url: config.api_url + 'reset_password',
			type: 'POST',
			data: {email: email},
			dataType: 'json',
			error: function(request, status, error) {
				return;
			},
			success: function(data, status, request) {
				if (data.result == 'ok') {
					$('#form_resetpassword').fadeOut('fast', function() {
						$('#success').fadeIn('fast');
					});
				} else {
					$('.incorrect4').fadeIn('fast');
				}
			}
		});

		event.preventDefault();
		return false;
	});
});

jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        // CAUTION: Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};

function switch_view_mode() {
	var pvm = $.cookie('photo_view_mode');
	if (isNaN(pvm)) {
		pvm = 0;
	}
	if (pvm == 0) {
		pvm = 1;
	}
	else {
		pvm = 0;
	}

	$.cookie('photo_view_mode', pvm, {expires: 30});

	window.location = window.location;
	return false;
}


/*** top notifications ***/
$(function() {
	$('.top_notification a.button_close').bind('click', function() {
		$(this).parents('.top_notification').eq(0).slideUp(200, function() {
			$(this).remove();
		});
		return false;
	});
});
