
// used to get values as floats - a value of 10 means it will be rounded to the nearest tenth
var SLIDER_DECIMALS = $H({display_size: 10});

// global variable to store slider objects
var SLIDERS = new Hash();


/***
    SLIDER FUNCTIONS
***/

// key_arr can be an array of keys to initialize. if specified only sliders matching those keys will be initialized
function initSliders() {
	$$(".track").each(function(slider) {
		SLIDERS.set(slider.id, startSlider(slider.id));
	});
}

function resetSearch() {
	new Ajax.Updater('search_form', '/compare/reset_search', {
	  method: 'post',
		onComplete: function(transport) {
			initAccordion();
      initSliders();
      updateCompare();
      initCheckBoxes();
		}
	})
}

function startSlider(id) {
    var max_slider_val = $(id+"_max").value;
    var mult = SLIDER_DECIMALS.get(id) || 1;
    var input1 = $(id+"_lower");    // form input controls
    var input2 = $(id+"_upper");
    var val1 = input1.value;        // form input values
    var val2 = input2.value;
    
    // instantiate new slider
    var _range = $R(0, max_slider_val);
    var _values = $R(0, (max_slider_val * mult)).collect(function(n) { return n / mult }); // use the collect function for values to get "stepping effect"
    var slider = new Control.Slider([id+'_handle1', id+'_handle2'], id, { range: _range, values: _values });
		
    // use numerical id of handle, although documentation suggests otherwise
    slider.setValue(val1, 0);
    slider.setValue(val2, 1);
    
    // textual info
    var slider_value = $(id+"_value");
    var slider_upper_value = $(id+"_upper_value");
    input1.value = slider_value.innerHTML = val1;
    input2.value = slider_upper_value.innerHTML = val2;
    
    // value comes in as an array when slider has multiple handles
    slider.options.onChange = slider.options.onSlide = function(value) {
        // swap values if one slider passes the other
        var lower = (value[0] < value[1]) ? value[0] : value[1]
        var upper = (value[1] > value[0]) ? value[1] : value[0]
        
        input1.value = slider_value.innerHTML = lower;
        input2.value = slider_upper_value.innerHTML = upper;
    }
    
    return slider;
}


/***
    FORM HELPER FUNCTIONS
***/

function initCheckBoxes() {
	var check_alls = $$(".check_all");
	check_alls.each(function(obj) {
	  obj.onclick = function() { checkAll(this); };
	  
	  var boxes = $$("." + obj.id);
	  boxes.each(function(box){
      box.onclick = function() { obj.checked = false; };
	  });
	});
}

// helper function to check all checkboxes in a group
function checkAll(el) {
    var boxes = $$("." + el.id);
    boxes.each(function(obj) {
				obj.checked = el.checked;
    });
}

function initCompareButtons() {
  var links = $$(".compare_player");
	links.each(function(el) {
		el.observe('click', updateCompare);
	});
}

function updateCompare(e) {
    Event.stop(e);
		
    var el = Event.element(e); // el may be an "add/remove" button or the remove icon in the compare_list 
    var id = el ? el.id.split("_")[1] : "-99";   // get mysql id number from element id attribute
    var button = $('player_' + id); // button is the corresponding "add/remove" button for el
    var params = {player_id: id};
		
    if (button) { // button may not exist on the page
        if(button.hasClassName("disabled"))
            return false;
        else if(button.hasClassName("remove")) {     // update button background image and innerHTML
            button.removeClassName("remove");
            button.addClassName("add");
            button.update("Add");
        } else {
            button.removeClassName("add");
            button.addClassName("remove");
            button.update("Remove");
        }
    }
    
    new Ajax.Updater('compare_box', '/compare/update_compare_list', {
			parameters: params,
			onComplete: function() {
				disableCompareBoxes($('compare_list'));
				initCompareButtons();
			}
		});
}

function disableCompareBoxes(list) {
    var compares = $$(".compare_player");
    var selected = list.immediateDescendants();
    
    if (selected.length >= 4) {
        compares.each(function(obj) {
            if (obj.hasClassName("add")) {
                obj.disabled = true;
                obj.addClassName("disabled");
            }
        });
    } else {
        compares.each(function(obj) {
            if(obj.disabled) {
                obj.disabled = false;
                obj.removeClassName("disabled");
            }
        });
    }
}

/***
    ADD / EDIT FUNCTIONS
***/

function addVariant(e) {

    new Ajax.Updater('variants',
        '/compare/admin/players/add_variant',
        {   method: 'post',
            insertion: Insertion.Bottom,
            onComplete: function() {
                var links = $$(".remove_variant");
                var remove = links.pop();
                Event.observe(remove, 'click', removeVariant.bindAsEventListener(remove));
            }});
            
    Event.stop(e);
}

function removeVariant(e) {
    if(confirm("Are you sure you want to remove this variant?\nThis cannot be undone!")) {
        var id = this.href.split("?").pop();
        var variant = $(id);
        var variant_id = $("id_"+id).value;
        
        if(variant_id != "-1") {
            var params = $H({id: variant_id});
            
            new Ajax.Request('/compare/admin/players/remove_variant',
            {   method: 'post',
                parameters: params,
                onComplete: function() { variant.remove(); }});
        }
        else
            variant.remove();
    }
    
    Event.stop(e);
}

function initVariants() {
    Event.observe('variant_link', 'click', addVariant);
    
    var links = $$(".remove_variant");
    links.each(function(remove) {
        Event.observe(remove, 'click', removeVariant.bindAsEventListener(remove));
    });
}

function addLink() {
  new Ajax.Updater('player_links',
    '/compare/admin/players/add_link', {
			method: 'post',
			insertion: Insertion.Bottom
    });
}

function removeLink(el) {
    el.parentNode.remove();
}


/***
    MISCELLANEOUS FUNCTIONS
***/

function updateModels(brand) {
    var params = "search[brand]=" + brand
    new Ajax.Updater('model', '/compare/filter_models', { parameters: params });
}

function orderResults(order, compare_page) {
    var params = $H({order_by: order});
    var url = '/compare/search';
    url += compare_page ? '/compare_search_results' : '';
    
    new Ajax.Updater('results', url, {
			parameters: params,
			onComplete: function() {
				initCompareButtons();
			}
		});
}

function initAccordion(){
    var tmp_stretchers = $$('.accordion');
    var tmp_togglers = $$('.toggler');
    var togglers = [];
    var stretchers = [];
    
    // loop through all togglers to see if an onclick event is already attached.
    // necessary to keep some togglers from having a new unrelated event attached to them
    // after a partial page refresh which breaks the functionality
    for(i = 0; i < tmp_togglers.length; i++) {
        if(!tmp_togglers[i].onclick) {
            tmp_stretchers[i].style.display = "block";  // the style is initially set to "hidden" in the style sheet. doing this keeps elements from flashing open, then closed
            togglers.push(tmp_togglers[i]);
            stretchers.push(tmp_stretchers[i]);
        }
    }

    var myAccordion = new Fx.Accordion(togglers, stretchers, { opacity: false, alwaysHide: true});
    
    // overwrite existing showThisHideOpen() function to allow for more than one slider to be open at a time
    myAccordion.showThisHideOpen = function(iToShow){
		if (iToShow != this.previousClick || this.options.alwaysHide){
            this.previousClick = iToShow;
			var objObjs = {};
			var err = false;
			var madeInactive = false;
			this.elements.each(function(el, i){
				this.now[i] = this.now[i] || {};
				if (i == iToShow){
					if (el.offsetHeight == el.scrollHeight){
						this.hideThis(i);
						madeInactive = true;
					} else if (el.offsetHeight == 0){
						this.showThis(i);
					} else {
						err = true;
					}
				} else if (this.options.wait && this.timer){
					this.previousClick = 'nan';
					err = true;
				}
				objObjs[iToShow+1] = Object.extend(this.h, Object.extend(this.o, this.w));
			}.bind(this));
			if (err) return;
			if (!madeInactive) this.options.onActive.call(this, this.togglers[iToShow], iToShow);
			this.togglers.each(function(tog, i){
				if (madeInactive) this.options.onBackground.call(this, tog, i);
			}.bind(this));
			return this.custom(objObjs);
		}
	}
}


/***
    INSERT INIT FUNCTIONS HERE
***/
document.observe("dom:loaded", function() {
    initCompareButtons();
    initPopup();

    if($('filter_bar')) {
        initAccordion();
        initSliders();
        initCheckBoxes();
    }
    
    if($('player_form'))
        initVariants();

    if($('add_player'))
        initSliders();
});