var _wh;
var _ww;
var opts;

var _updateIndigenous;

_updateLabels = function() {
    /* add classes to icons to indicate that they have informational labels */
    $(".empty_embedded, .empty_inline").each(function() {
        if (! $(this).attr('title')) {
            $(this).attr("title", "Click the cross to remove this section");
        }
        $(this).addClass("has_label");
    });

    $(".add-item a.ico-big,.add-another a.ico-big").each(function() {
        //	if there is no title add one
        if (! $(this).attr('title') && $(this).html()) {
//            _t = $(this).html();
            _t = "Add"; /* as per GF 18/10/2011 */
            $(this).attr('title', _t);
        }
        $(this).addClass("has_label");
    });

    //	all other icons
    $(".ico-big").addClass("has_label");
    $("#sidebar .buttons a.ico").addClass("has_label");

    //	display the tooltip
    $(".has_label").tipTip({"defaultPosition" : "right", delay: 0, fadeIn: 100});
};

$(document).ready(function() {
    var max_help_length = 120;
    _wh = $(window).height();
    _ww = $(window).width();

    /* lightbox colorbox */
    opts = {
        current : "",
        close : "Close",
        previous : "Previous",
        next : "Next",
        photo : true,
        scalePhotos : true,
        maxWidth : _ww,
        maxHeight : parseInt(_wh * 0.9)
    };

    /* Datepicker */
    $("#datepicker, .datepicker").datepicker({
        changeMonth: true,
        changeYear: true,
        dateFormat: 'dd/mm/yy',
        yearRange: '1600:2050'
    });

	/* Precision dates
	 * Issue 595
	 * birth, death, burial, exhibition yyyy-mm-dd
	 * all others yyyy
	*/
	var precise_dates = Array("birth", "death", "burial", "exhibition");

  _updatePrecision = function(ele) {
   	var precision_id = $(ele).attr("id");
//  @todo we need checking in there . does this element exist ?

//	if this element refers to one of our precise dates do nothing (defaults are precise)
		for (var i = 0; i < precise_dates.length; i++ ) {
			if ( precision_id.toLowerCase().indexOf(precise_dates[i]) > -1 ) {
				return;
			}
		}

//  detect step 1 - parent li is labelled precise
    if ( $(ele).parents("li").hasClass("precise") ) {
      return;
    }
		
//	find the catchall fieldname id_birth__coverage__date__precision
//  the id of the select element is id_residences__0__coverage_range__date_range__start__precision
//  the ids of the text fields are  id_residences__0__coverage_range__date_range__start___date_[n]
		var base_id = precision_id.split("precision")[0] + "_date_";

//	find the text fields and check if they're non empty id_residences__0__coverage_range__date_range__start___date_2
    var value_set = false;
		$(":text[id^=" + base_id + "]").each(function(){
//  check for non empty values and return
			if ( $(this).val() || $(this).val() !== "" ) {
			  value_set = true;
				return false;
			}
		});

//	another guess - if val is non zero return
//		if ( $(":text[id^=" + base_id + "]").val() ) return;
		
//	if we get this far we are *not* a precise_date and we *are* empty
//	trigger any events
    if ( ! value_set ) {
      $("#" + precision_id).val("2").trigger("change").trigger("select");
    }
	}
	$("select.precision").each(function() {
		_updatePrecision(this);
	});

/* when adding-another the zebra class is copied from the first element 
 * reset to alternating instead 
 */
	_updateZebra = function(ele) {
	  var odd = false;
	  $(ele).children(".inline").removeClass("odd even").each(function() {
	    if ( odd ) {
	      $(this).addClass("odd");
	      odd = false;
      } else {
	      $(this).addClass("even");
	      odd = true;        
	    }
	  });
	}
	

    /* Homepage tabs */
    $("#home-page_content div.tabs").tabs();

    /* Search results */
    $(".sr_header.roll-up").css("cursor", "pointer");
    $(".sr_header.roll-up").append('<span class="roll-up_arrow"></span>');

    _updateLabels();

    /* edit form empty_embedded - make labels behave like labels - ie: when you click the label it toggles the checkbox */
    $(".empty_embedded span.label").click(function() {
        $(this).next('input:checkbox').click();

        //	mark the parent for removal
        if ($(this).parent().parent().hasClass('empty_removal')) {
            $(this).parent().parent().removeClass('empty_removal');

            //	remove any title so that updateLabels does its work
            $(this).parent().attr("title", "");
        } else {
            $(this).parent().parent().addClass('empty_removal');

            //	add the reverse label - click to restore
            $(this).parent().attr("title", "Click the tick to restore this section");
        }
        _updateLabels();
    });

    /* run updateLabels when add-another is clicked */
    $(".add-another").click(function() {
        //	@todo we might need a delay
        // to make sure that the add-another live runs first
        _updateLabels();
        
        $(this).parents(".mongoform").each(function() {
          _updateZebra(this);
        });
// @todo we should be able to narrow this to only look at what has been added
      	$(this).parents(".mongoform").find("select.precision").each(function() {
      		_updatePrecision(this);
      	});
    });

    /* toggle indigenous fields based on checkbox */
    _updateIndigenous = function() {
        if ($("#id_is_indigenous:checked").size()) {
            $("li.indigenous").show();
        } else {
            $("li.indigenous").hide();
        }
    };
    _updateIndigenous();

    $("#id_is_indigenous").click(
            function() {
                _updateIndigenous();
            }
    );
    
    /* look for all modified fields, style their parent, jump to the first one 
    this probably fires too soon. wait until after all the sections have opened (if they are going to)
    */
    $("#createform .modified").closest("li").addClass("modified-container");
    if ( $(".modified-container").size() > 0 ) {
//  only jump if we're not already scrolled
      if ( $(window).scrollTop() == 0 ) {
//  wait for a bit until the page has loaded a bit
          t = setTimeout( '_focus_element(jQuery(".modified-container").first())', 500);
      }
    }

    
    /* Issue 632 look for all notes fields and set their max length to 430*/
    $("#createform input:text[name$='_note']").not("[maxlength]").attr("maxlength", 430).addClass("length-limited");

    /* show help text unless its very long */
    var transform_helptexts = function() {
        $(".helptext").each(function() {
            var _s = $(this).html().length;
            if (_s < max_help_length + 1) {
                //	show and set as a block or the span wraps badly
                $(this).css('display', 'block');
            } else {
                $(this).addClass('helptext-long');
                //	watch for hover events on the parent container
                //	ideally this would be the parent, parent ul .
                // unfortunately gender is unparented and
                // therefore causes all help
                //	texts in that block to display
                $(this).parent().find('input, select').hover(
                        function() {
                            $(this).parent().find('.helptext-long').slideDown('fast',
                                    function() {
                                        //	as helptext is a span it reflows
                                        // badly after the animation unless
                                        // we control the display type
                                        $(this).css('display', 'block');
                                    }
                            );
                        },
                        function() {
                            $(this).parent().find('.helptext-long').slideUp('fast');
                        }
                );
            }
        });
    };
    transform_helptexts();


    /* External image links */
    $('.works .photo a img').each(
            function() {
                var link = $(this).parent();
                if ($(link).attr('href').indexOf(location.hostname) < 0) {
                    link.addClass('external');
                    link.append('<div class="external-icon">&nbsp;</div>');
                }
            }
    );

    /* Search results alive between */
    var alive_min = 1600;
    var current_year = new Date().getFullYear();
    var alive_max = current_year + 10;
    var current_value = $("#id_date_range").val();
    var slider_values;
    if (current_value) {
        slider_values = current_value.split('-');
        slider_values = [parseInt(slider_values[0]), parseInt(slider_values[1])];
    } else {
        slider_values = [1750, current_year];
    }
    $("#id_date_range_slider-range").slider({
        range: true,
        min: alive_min,
        max: alive_max,
        values: slider_values,
        slide: function(event, ui) {
            $("#id_date_range").val(ui.values[0] + "-" + ui.values[1]);
            $("#id_date_range_slider-range .ui-slider-handle:eq(0)").html('<span>' + ui.values[0] + '</span>');
            $("#id_date_range_slider-range .ui-slider-handle:eq(1)").html('<span>' + ui.values[1] + '</span>');
        }
    });

    $("#id_date_range").val($("#id_date_range_slider-range").slider("values", 0) +
            "-" + $("#id_date_range_slider-range").slider("values", 1));
    $("#id_date_range_slider-range .ui-slider-handle:eq(0)").css({
        "background-position" : "0 -36px",
        "top" : "15px"
    });
    $("#id_date_range_slider-range .ui-slider-handle:eq(0)").html(
        '<span>' + $("#id_date_range_slider-range").slider("values", 0) + '</span>'
    );
    $("#id_date_range_slider-range .ui-slider-handle:eq(1)").html(
        '<span>' + $("#id_date_range_slider-range").slider("values", 1) + '</span>'
    );


    /* Accordion */
    var accordion_icons = {
        header: "ico btn_08",
        headerSelected: "ico btn_08"
    };

    $(".daao-accordion").accordion({
        autoHeight: false,
        icons: accordion_icons
    });

    //	if there is only one item to accordion remove the title row
    if ($(".daao-accordion .cb_title").size() == 1) {
        $(".daao-accordion .cb_title").hide();
    }

    /* Search results */
    $(".sr_header.roll-up").click(function () {
        $(this).next(".sr_body").slideToggle("150");
        $("span.roll-up_arrow", this).toggleClass("down");
    });

    /* if the query string shows advanced then show the advanced box */
    if (location.search.toLowerCase().indexOf("advanced=true") >= 0 && $(".sr_body:hidden").size() > 0) {
        $(".sr_header.roll-up").click();
    }

    /* Login */
    var $title_login = $('.login-title');
    var $title_signup = $('.signup-title');
    var $l_login = $('.l_login');
    var $l_signup = $('.l_signup');

    function select_login() {
        $title_login.addClass('selected');
        $title_signup.removeClass('selected');

        $l_login.removeClass('hideme');
        $l_login.css('display', 'block');
        $l_signup.css('display', 'none');
    }

    function select_signup() {
        $title_login.removeClass('selected');
        $l_signup.removeClass('hideme');

        $title_signup.addClass('selected');
        $l_signup.css('display', 'block');
        $l_login.css('display', 'none');
        $("#regform_captcha").load(
            "/registration/captcha"
        );
    }

    $l_login.css('display', 'none');
    $l_signup.css('display', 'none');
    $title_login.click(select_login);
    $title_signup.click(select_signup);
    $('#or-signup').click(select_signup);
    $('#or-login').click(select_login);


    var autocomplete_list;
    $('.autocomplete input.writehere').live('keydown',
        function(event) {
            var $this = $(this);
            var name = $this.parent().attr('name');
            $this.autocomplete({
                source: "/autocomplete/" + name + "/",
                select: function(event, ui) {
                    $(event.target).prev().val(ui.item.id);
                },
                change: function(event, ui) {
                    if (ui.item == null) {
                        alert('"' + $(this).val() + '" is not a valid value. ' +
                                'Please select an existing option from the list ' +
                                'or create a new one.');
                        $('.add_new', $this.parent()).click();
                    }
                },
                open: function(event, ui) {
                    if ($(this).parent().hasClass('add')) {
                        var add_new_li = $('<li class="li_add_new ui-menu-item"><a href="#" class="add_new_inner">Item not found: add new</a></li>');
                        autocomplete_list = $('.add-item ul', $(this).parent());
                        autocomplete_list.prepend(add_new_li);
                        autocomplete_list.show();
                    }
                },
                appendTo:$('.add-item', $(this).parent())
            });
        }
    ).live('focus',
        function(event) {
            if ($(this).parent().hasClass('add')) {
                if ($('ul.extra-menu-for-add-new', $(this).parent()).length == 0) {
                    var extra_menu = $('<ul class="extra-menu-for-add-new ui-autocomplete ui-menu ui-widget ui-widget-content ui-corner-all"><li class="li_add_new ui-menu-item"><a href="#" class="add_new_inner">Item not found: add new</a></li></ul>');
                    $(this).parent().append(extra_menu);
                    $(extra_menu).position(
                            { my: "left top", at: "left bottom", of: $(this)});
                }
            }
        }
    ).live('blur', function(event) {
        $('ul.extra-menu-for-add-new', $(this).parent()).remove();
    });

    function person_inline_HACK() {
        // fix properly in mongoforms_rendering_fixes branch
        var empty = $('#simplemodal-data input[name=roles__0__EMPTY_INLINE]');
        empty.attr('checked', false);
        empty.parent().hide();
        $('#simplemodal-data label').each(function(index, element) {
            $(element).html($(element).html().replace('Roles  0  ', ''));
        });
    }

    var modal_target = null;
    $('a.add_new').live('click', function(event) {
        if (autocomplete_list) {
            autocomplete_list.hide();
        }
        var span = $('.autocomplete', $(this).parent().parent());
        var name = span.attr('name');
        modal_target = span;
        $.get('/createform/' + name + '/',
                function(data) {
                    $.modal(data, {'position': ['5%', '33%']});
                    person_inline_HACK();
                });
        //transform_helptexts();
        return false;
    });
    $('a.add_new_inner').live('click', function(event) {
        if (autocomplete_list) {
            autocomplete_list.hide();
        }
        var span = $('.autocomplete', $(this).parent().parent().parent().parent().parent());
        var name = span.attr('name');
        modal_target = span;
        $.get('/createform/' + name + '/',
                function(data) {
                    $.modal(data, {'position': ['5%', '33%']});
                    person_inline_HACK();
                });
        return false;
    });
    
    $('#simplemodal-data form:not(.no_ajax)').live('submit', function() {
        $.ajax({
            type: "POST",
            url: $(this).attr('action'),
            data: $(this).serialize(),
            success: function(data, textStatus, jqXHR) {
                // TODO: make me generic using a callback or similar
                if (jqXHR.status == 201) {
                    var obj = $.parseJSON(data)[0];
                    $(modal_target).find(
                            'input[type=hidden]').val(obj.id);
                    $(modal_target).find(
                            'input[type=text]').val(obj.__unicode__);
                    $.modal.close();
                }
                else {
                    $("#simplemodal-data .body").html($('.body', data));
                    person_inline_HACK();
                }
            },
            error: function(request, status, error) {
                alert("Error communicating with server.");
            }
        });
        return false;
    });
    
    var form_container = false;
    $("#create_favouriteset").live('click', function() {
        if (!form_container) {
            form_container = $('form', $(this).parent().parent()).parent();
            form_container = form_container.detach();
        }
        $('form', form_container).removeClass('hideme').addClass('no_ajax');
        var modal_form = '<div id="modal_search_export" class="modal participate default"><a class="btn btn_03 close simplemodal-close" href="javascript: void(0)"></a><div class="title">Create new favourite set</div><div class="body">' + form_container.html() + '</div><span class="arrow"></span></div>';
        $.modal(modal_form);
        return false;
    });

    /* disappear field groups where the empty inline checkbox is checked (on initial doc load)
     * this could happen when there's a form validation error and the form gets redisplayed
     */
    // causes the work form to disappear
    //$('.empty_inline input[name$="EMPTY_INLINE"][checked="checked"]', this).parents("[id^=field-group-]").hide();

    /* disappear field groups marked for removal */
    $(".empty_inline").live('click', function() {
        var checkbox = $('input[name$="EMPTY_INLINE"]', this);
        checkbox.attr("checked", "checked");
        $(this).parent().hide();
    });

    /* indicate which fields in a field group will be removed */
    /* this is jquery 1.4.1 syntax–1.4.3 allows a different syntax */
    $(".empty_inline, .empty_embedded").live("mouseover mouseout",
            function(event) {
                if (event.type == "mouseover") {
                    $(this).parent().addClass("scope empty");
                } else {
                    $(this).parent().removeClass("scope empty");
                }
            }
    );

    $('.add_record_to_project .submit_link').click(function() {
        $(this).parent().submit();
        return false;
    });

    $('.remove_record_from_project .submit_link').click(function() {
        $(this).parent().submit();
        return false;
    });

    $('.edit_member .submit_link').click(function() {
        $(this).parent().parent().submit();
        return false;
    });

    // search form autocomplete
    $('.search_form input').live('keydown', function(event) {
        var $this = $(this);
        var name = $this.parent().attr('name');
        $this.autocomplete({
            source: "/search/autocomplete/",
            appendTo: $this.parent()
        });
    });

    // advanced search button
    $('#adv_search_button').click(function(event) {
        event.preventDefault();
        var f = $(this).parents("form.search_form");
        if (f.size() > 0) {
            f = f[0];
            $(f).find("input[name='advanced']").val("true");
            var q = $(f).find("input[name='q']");
            if ($(q).val() == 'Search')
                $(q).val("");
            $(f).submit();
            return false;
        }
//		return false;
    });


    // search form hide/show medium
    $("#advanced_search_form input[value='Person']").change(function() {
        if ($(this).attr('checked')) {
            $(".medium", $("#advanced_search_form")).removeClass('hideme');
        }
        else {
            $(".medium", $("#advanced_search_form")).addClass('hideme');
        }
    });

    // search form submit on quantity change
    $(".quantity select").change(function() {
        window.location.search = $.query.set('results_per_page', $(this).attr('value'));
    });

    // advanced search criteria form
    var form_list;
    var displayed_form_count;
    var max_forms = 10;
    $("#add_form_link").click(function(event) {
        event.preventDefault();
        if (displayed_form_count < max_forms) {
            var hidden_list = $(".a_form:hidden");
            // just show the first hidden one
            if (hidden_list.length) {
                $(hidden_list[0]).show();
                displayed_form_count++;
                if (displayed_form_count == max_forms) {
                    $(this).html("You can only specify 10 advanced search criteria at one time.");
                }
            }
        }
    });
    
    $(".remove_formset").click(function() {
        var form_to_hide = $(this).closest('.a_form');
        // empty the form's value.value
        $('input:[type="text"]', form_to_hide).attr('value', '');
        form_to_hide.hide();
    });
    
    form_list = $(".a_form");
    displayed_form_count = form_list.length;
    $(".a_form").each(function(i) {
        if (i > 0) {
            var hide_this_form = true
            $(this).find('input').each(function() {
                if ($(this).val() != "") {
                    if (this.type != 'checkbox' && this.type != 'radio' && this.type != 'hidden') {
                        // don't hide checkboxes unless they are checked
                        hide_this_form = false;
                    }
                    else if (this.type == 'checkbox' && this.checked) {
                        hide_this_form = false;
                    }
                    else if (this.type == 'radio' && this.checked) {
                        hide_this_form = false;
                    }
                }
            });
            if (hide_this_form) {
                $(this).hide();
                displayed_form_count--;
            }
        }
    });
    // we never hide the first form


    // inspired by: http://pypi.python.org/pypi/django-classfaves/0.1
    var add_favourite_handlers = function(base_create, base_delete) {
        $('a.favourite.fave').live('click', function(e) {
            var url = $(this).attr('href');
            var id = $(this).attr('id');
            $.ajax({
                url: url,
                context: this,
                type: "GET",
                success: function(data) {
                    var favourite_link = $("#" + id);
                    favourite_link.parent().html(favourite_link.text().substr(7));
                }
            });
            return false;

        });
        $('a.favourite.unfave').live('click', function(e) {
            var url = $(this).attr('href');
            var id = $(this).attr('id');
            $.ajax({
                url: url,
                context: this,
                type: "GET",
                success: function(data) {
                    var favourite_link = $('#' + id);
                    favourite_link.parent().html('Removed');
                }
            });
            return false;
        });
        $('a.favourite.delete').live('click', function(e) {
            var url = $(this).attr('href');
            var id = $(this).attr('id');
            $.ajax({
                url: url,
                context: this,
                type: "GET",
                success: function(data) {
                    var favourite_link = $('#' + id);
                    favourite_link.closest('.result').hide('slow');
                }
            });
            return false;
        });

    };
    // needs to update the count in the sidebar, and to reactivate the menu items to work properly
    //add_favourite_handlers();

    /* edit form - hide fields if 'no full record required' */
    var toggle_full_record_fields = function(){
        if($("#createform #id_is_shadow").attr('checked')){
            $("#createform .full_record").hide();
            // special case
            $("#createform [id$='__detailed_role']").parent().hide();
        }else{
            $("#createform .full_record").show();
            // special case
            $("#createform [id$='__detailed_role']").parent().show();
        }
    };
    // call once on load
    toggle_full_record_fields();
    // and thereafter on click
    $("#createform #id_is_shadow").change(toggle_full_record_fields);

});

$(document).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;
    }

    function sameOrigin(url) {
        // url could be relative or scheme relative or absolute
        var host = document.location.host; // host + port
        var protocol = document.location.protocol;
        var sr_origin = '//' + host;
        var origin = protocol + sr_origin;
        // Allow absolute or scheme relative URLs to same origin
        return (url == origin || url.slice(0, origin.length + 1) == origin + '/') ||
                (url == sr_origin || url.slice(0, sr_origin.length + 1) == sr_origin + '/') ||
            // or any other URL that isn't scheme relative or absolute i.e relative.
                !(/^(\/\/|http:|https:).*/.test(url));
    }

    function safeMethod(method) {
        return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
    }

    if (!safeMethod(settings.type) && sameOrigin(settings.url)) {
        xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
    }
});

//  jump to near the top of a given element
    var _focus_element = function(ele) {
      $(window).scrollTop($(ele).offset().top - 10);
    }


