function closeFacebox() {
    jQuery(document).trigger('close.facebox');
    return true;
}

function initSelectAll(){
	$('.select-all a').each(function(){
		if($(this).closest('.select-all-cont').nextAll('.has-checkboxes:first').find('input[type=checkbox]:not(:checked)').length <= 0){
			$(this).text('Deselect all');
		}
		else
			$(this).text('Select all');
	});
}
$(document).ready(
    function() {
        var log_error = function(error) {
            // firebug only
            if (typeof(console) !== "undefined" &&
                typeof(console.log) === "function") {
                console.log(error);
            }
        };

        $(document).pngFix();

        if(!$.browser.msie)
            $('.rounded').corners();

        $(".cancel-fullpage-form").click(
            function(event) {
                location.href = $("#back-to-tickets-view").attr("href");
                return false;
            }
        );
	$('.select-all a').click(function(){
		if($(this).text() == 'Select all'){
		$(this).closest('.select-all-cont').nextAll('.has-checkboxes:first').find('input[type=checkbox]').attr('checked', 'checked');
		$(this).text('Deselect all');
		}
		else if($(this).text() == 'Deselect all'){
		$(this).closest('.select-all-cont').nextAll('.has-checkboxes:first').find('input[type=checkbox]').removeAttr('checked');
		$(this).text('Select all');
		}
	})

		if ($.browser.msie && $.browser.version < 9)
		{
			$(".select1, .select2, .select3, .select4, .select5, .select6, .select7, .select8, .select9, .select0")
			.live('focus', function(){
				$(this)
				.data("origWidth", $(this).css("width"))
				.css("width", "auto");
				this.style.position='relative';this.style.zIndex='100';this.style.width='auto'
			})
			.live('change', function(){
				$(this).css("width", $(this).data("origWidth"));
				this.style.zIndex='0'
			})
			.live('blur', function(){
				$(this).css("width", $(this).data("origWidth"));
				this.style.zIndex='0'
			});
		}

		$(function() {
              // setTimeout() function will be fired after page is loaded
              // it will wait for 5 sec. and then will fire
              // $("#successMessage").hide() function
              setTimeout(function() {
                             $("._error_box").fadeOut();
                         }, 5000);
          });

        $('._error_box a.hide-link').click(
            function() {
                $(this).parents('._error_box').fadeOut();
            });

        $('.date-pick').datePicker({clickInput:true, createButton:false});

        $('a.add-new-notification').click(
            function() {
                $('#add-new-notification').slideToggle(
                    1,
                    function() {
                        $.scrollTo('#add-new-notification', 800);
                        $('#add-new-notification input:first').focus();
                    });
                return false;
            });

        $('.close-form').click(
            function() {
                $(this).parents(
                    "#add-new-category, #add-new-staff, #add-new-role, " +
                        "#add-new-notification, " +
                        "#add-new-custom-field, " +
                        "#add-new-macro, #add-new-sla, #add-new-smart-rule, " +
                        "#add-new-workschedule, #add-kb-category, #add-kb-article, " +
                        "#add-response, #add-private-note, " +
                        "#add-new-contact, #add-new-embeddable").slideUp(
                            1,
                            function() {
                                $.scrollTo('#header', 400);
                            });
                return false;
            });

        $('.ellipsis').ThreeDots({ max_rows:1, alt_text_t: true });


        // forms which use ajax post, must be marked with xhr="xhr"
        $('form[xhr="xhr"]').submit(ajaxifyFormSubmit);

        $(document).bind(
            'reveal.facebox',
            function() {
                $('#facebox form[xhr="xhr"]').submit(ajaxifyFormSubmit);
            });
    }
);

function ajaxifyFormSubmit(event) {
    var form = $(this);
    var action = form.attr('action');
    if (action === '')
        action = window.location.href;
    else if (action.indexOf('/') == 0)
        action = window.location.protocol + '//' + window.location.host + action;

    ajaxFormSubmit(form, action, handleFormResult);

    event.preventDefault();
    event.stopPropagation();
    return false;
}

function ajaxFormSubmit(form, url, resultHandler) {
    // disable submit button for 2 seconds
    $('input[type="submit"]').attr('disabled', true);
    var reenable = setTimeout(
        function() {
            $('input[type="submit"]').attr('disabled', false);
        },
        2000);

    form.ajaxSubmit(
        {
            url: url,
            success: function(data) {
                // reenable submit buttons NOW
                clearTimeout(reenable);
                $('input[type="submit"]').attr('disabled', false);

                resultHandler(form, data);
            },
            dataType: 'json',
            iframe: true
        }
    );

    return false;
}

function handleFormResult(form, result) {
    updateFormErrors(form, result);
    if (result.status === 'ok') {
        window.location = result.data;
    }
}

function updateFormErrors(form, result) {
    form.find('.xhr_errors').html('');

    if (result.status === 'error') {
        for (key in result.errors)
            if (result.errors.hasOwnProperty(key))
                form.find('.errors_' + key).html(result.errors[key]);
        form.find('.form-errors').html(result.form_errors);
    }
}

// http://docs.djangoproject.com/en/1.2/ref/contrib/csrf/#ajax
$('html').ajaxSend(function(event, xhr, settings) {
    function getCookie(name) {
        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;
    }
    if (!(/^http:.*/.test(settings.url) || /^https:.*/.test(settings.url))) {
        // Only send the token to relative URLs i.e. locally.
        xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
    }
});

function insertText(selector, text) {
    var input = $(selector)[0];
    if (document.selection) {
        input.focus();
        var selection = document.selection.createRange();
        selection.text = text;
        input.focus();
    }
    else if (input.selectionStart || (input.selectionStart=='0')) {
        var start = input.selectionStart;
        var end = input.selectionEnd;
        var inputText = input.value;
        input.value = inputText.substring(0,start) + text +
                    inputText.substring(end,inputText.length);
        input.focus();
        var newPos = start + text.length;
        input.selectionStart = newPos;
        input.selectionEnd = newPos;
    }
    else {
        input.val(input.val + text);
        input.focus();
    }
}

function deleteTag(ticket_id, tag_id) {
    var message = {
        'ticket_id' : ticket_id,
        'tag_id' : tag_id,
        'action' : 'delete'
    };
    $.post(
        '/staff/ticket/tags/'+ticket_id+'/', message,
        function(data, textStatus, xhr) {
            if (data.hasOwnProperty('error')) {
                //TODO: report the error
                return;
            }
            $('.tag-element-'+tag_id).each(
                function() {
                    $(this).hide('slow').remove();
                }
            );
            if ($('.tag-element').length == 0) {
                $('#tags-list').prepend('<span>No tags set for this ticket.</span>');
            }
        }
    );
    return false;
}

(function($) {
     $.fn.blurHandler = function(klass) {
         var obj = this;
         obj.focus(
             function() {
                 obj.removeClass(klass);
             }).blur(
             function() {
                 if (obj.val() == '') {
                     obj.addClass(klass);
                 }
             });
         return obj;
     };
 })(jQuery);

