//                         Stuff should only go into this file IF and ONLY IF it cannot be filtered down to a controller-specific JS file.

//=========================================================================================================================================================
// Setup Functions - init() function and setup functions for each chunk of functionality ==================================================================

document.observe('dom:loaded', function(){init()});

function init() {          // This function should exist (with sensible namespacing) in each file, and be added to Window.onload using the Prototype helper 
	// Call setup functions here
	get_dynamic_header();
	
	setup_toggles();
	setup_tab_switchers();
        setup_view_selectors();
	setup_select_all();
        setup_unit_converters();
}

function get_dynamic_header() {
    var current_tab = $('current_tab').value;
    var url = '/public/dynamic_header';
    if(current_tab != ''){
        url = url + '/' + current_tab;
    } 
    new Ajax.Request(url, {
            method: 'get',
            onSuccess: function(response) {
                    $('dynamic_header').replace(response.responseText);
            }
    });
		
		
}

function setup_toggles() { // Takes an array of trigger/target switches (IDs), and an on/off text pair

	[['add_role_toggle', 'add_role', 'Add Role', 'Remove Role'], //Add more here as necessary
	['shoot_header', 'shoot_form', 'add', 'remove'],
	['audition_header', 'audition_form', 'add', 'remove'],
	['client_toggle', 'create_client', '', ''],
	['client_toggle', 'select_client', 'add new client', 'select new client'],
        ['notice_box_toggle', 'notice_box_content', 'view help information', 'hide help information']
	].each(function(tuplet){
		if ($(tuplet[0])) {
			$(tuplet[0]).observe('click', function(e){show_hide(tuplet); Event.stop(e);});
			// $(tuplet[1]).addClassName('hidden'); Screw that. Set the starting state yourself
		}
	});
}

function setup_tab_switchers() { // This sets up all the Javascript-based tabulators and relies on MATCHING tabs and targets
	$$('.tab_toggle_ul').each(function(el){
		var tabs = el.select('a');
		tabs.each(function(tab, index){
			tab.observe('click', function(e) {
				toggle_tab(tabs, index);
				Event.stop(e);
			});
		});
	});
}

function setup_view_selectors() {
    $$('.view_selector_container').each(function(el){
        var options = el.select('a');
        options.each(function(option, index){
            option.observe('click', function(e) {
                toggle_view(options, index);
                Event.stop(e);
            });
        });
    });
}

function setup_select_all() {
    $$('.multiselect').each(function(el) {
        var first_el = el.down('input')
        if(first_el.hasClassName('select_all')){
            first_el.observe('click', function(){select_all(el)}); //Need to wrap this call in an anonymous function, as with init.
        }
    });
}

function setup_unit_converters() {
        $$('.measure_met').each(function(el) {
                el.observe('keyup', function(){ convert_to_imperial(el) }); 
	});
        $$('.measure_imp').each(function(el) {
                el.observe('keyup', function(){ convert_to_metric(el) }); 
	});
        $$('.measure_met_height').each(function(el) {
                el.observe('keyup', function(){ convert_to_imperial_height(el) }); 
	});
        $$('.measure_imp_height').each(function(el) {
                el.observe('keyup', function(){ convert_to_metric_height(el) }); 
	});
        $$('.measure_met_weight').each(function(el) {
                el.observe('keyup', function(){ convert_to_imperial_weight(el) }); 
	});
        $$('.measure_imp_weight').each(function(el) {
                el.observe('keyup', function(){ convert_to_metric_weight(el) }); 
	});
}



//=========================================================================================================================================================
// Functional Functions - Functions that do stuff, interact with the DOM, etc =============================================================================

function show_hide(tuplet) { 
	//First, switch the text in the trigger: Eg show/hide
	var trigger = $(tuplet[0]);
	if (trigger.innerHTML == tuplet[2]) {
		trigger.innerHTML = tuplet[3];
	} else {
		trigger.innerHTML = tuplet[2];
	}
	
	//next: Toggle the visbility of the target
	var target = $(tuplet[1]);
	target.toggleClassName('hidden');
	
	//Now clean disable any input fields, and write to an .adding input field if relevant. '.adding' inputs are used server-side and are important!
	if (target.hasClassName('hidden')) {
		target.select('input').each(function(inp){
			inp.disable();
		});
		target.select('.adding').each(function(inp){
			inp.value = "n";
			inp.enable(); //reverse the evil the previous loop committed. Cheaper and cleaner than an 'if' block.
		});
	} else  {
		target.select('input').each(function(inp){
			inp.enable();
		});
		target.select('.adding').each(function(inp){
			inp.value = "y";
		});
	}
}

function toggle_tab(tabs, index) { //Displays the appropriate tab target, and makes the clicked tab active
	// console.log('Event handler worked'); These break versions of Fx missing Firebug. Comment out when done.

	tabs.each(function(tab) {
		tab.up(1).removeClassName('active');
	});
	tabs[index].up(1).addClassName('active');
	
	$$('.tab_target').invoke('addClassName', 'hidden');
	$$('.tab_target')[index].removeClassName('hidden');
}

function toggle_view(options, index) { //Displays the appropriate view target, and makes the clicked view active
	//console.log('Event handler worked');
/*	options.each(function(option) {
		option.up().removeClassName('active');
	});
	options[index].up().addClassName('active');
*/
	
	options.each(function(el) {
		el.removeClassName('active');
	});
	
	options[index].addClassName('active');
	
	$$('.view_target').invoke('addClassName', 'hidden');
	$$('.view_target')[index].removeClassName('hidden');
}

function select_all(el) {
	el.select('input').each(function(e){
		if (el.down('input').checked) {
			e.checked = true;
		} else {
			e.checked = false;
		}
	});
}

function convert_to_imperial(el) {
    var parent = el.up();

    met_val = parseInt(el.value);
    if(isNaN(met_val))
        met_val = 0;
    
    imp_val = Math.round(met_val * 0.3937 * 10) / 10;
    parent.select('[class="measure_imp"]').each(function(other_el) {
        if(imp_val == 0)
            other_el.value = '';
        else
            other_el.value = imp_val;
    });
}

function convert_to_imperial_height(el) {
    var parent = el.up();
    
    met_val = parseFloat(el.value);
    if(isNaN(met_val))
        met_val = 0;
    
    imp_val = Math.round(met_val * 0.3937 * 1000);
    imp_inches = (imp_val % 120) / 10;
    imp_feet = Math.floor(imp_val / 120);

    parent.childElements().each(function(other_el) {
        if(other_el.hasClassName('imp_feet')) {
            if(imp_feet == 0)
                other_el.value = '';
            else
                other_el.value = imp_feet;
        }
        if(other_el.hasClassName('imp_inches')) {
            if(imp_inches == 0)
                other_el.value = '';
            else
                other_el.value = imp_inches;
        }
    });
}

function convert_to_imperial_weight(el) {
    var parent = el.up();

    met_val = parseInt(el.value);
    if(isNaN(met_val))
        met_val = 0;
    
    imp_val = Math.round(met_val * 2.205);
    parent.select('[class="measure_imp_weight"]').each(function(other_el) {
        if(imp_val == 0)
            other_el.value = '';
        else
            other_el.value = imp_val;
    });
}

function convert_to_metric(el) {
    var parent = el.up();

    var imp_val = parseFloat(el.value);
    if(isNaN(imp_val))
        imp_val = 0;
        
    var met_val = Math.round(imp_val * 2.54);
    parent.select('[class="measure_met"]').each(function(other_el) {
        if(met_val == 0)
            other_el.value = '';
        else
            other_el.value = met_val;
    });
}

function convert_to_metric_height(el) {
    var parent = el.up();
    var imp_feet = 0;
    var imp_inches = 0.0;
    parent.childElements().each(function(other_el) {
        if(other_el.hasClassName('imp_feet')) {
            if(!isNaN(parseInt(other_el.value)))
                imp_feet = other_el.value;
        }
        else if(other_el.hasClassName('imp_inches')) {
            if(!isNaN(parseInt(other_el.value)))
                imp_inches = other_el.value;
        }
    });

    var inches = parseFloat(imp_inches) + (12 * parseInt(imp_feet));
    var met_val = Math.round(inches * 2.54) / 100;

    parent.childElements().each(function(other_el) {
        if(other_el.hasClassName('measure_met_height')) {
            if(met_val == 0)
                other_el.value = '';
            else
                other_el.value = met_val;
        }
    });
}

function convert_to_metric_weight(el) {
    var parent = el.up();

    imp_val = parseInt(el.value);
    if(isNaN(imp_val))
        imp_val = 0;
        
    met_val = Math.round(imp_val * 0.454);
    parent.select('[class="measure_met_weight"]').each(function(other_el) {
        if(met_val == 0)
            other_el.value = '';
        else
            other_el.value = met_val;
    });
}


//=========================================================================================================================================================
// Process Functions - these functions process data and return values, but do not edit or interact with the DOM in any way ================================



//=========================================================================================================================================================
// Socket Functions - These functions are called by RJS templates, used when they get bulky and writing a socket becomes more elegant =====================





// Sort these out! 

//HAHA! PWNED!
// function display_brief_subform(el_type){
//     var hidden_el = $('adding_' + el_type);
//     var form_el = $(el_type + '_form');
//     var link_el = $(el_type + '_header');
//     if(form_el && hidden_el && link_el){
//         form_el.style.display = '';
//         hidden_el.value = 'y';
//         link_el.innerHTML = 'remove ' + el_type;
//         link_el.writeAttribute('onclick', "hide_brief_subform('" + el_type + "'); return false;");
//     }
// }
// function hide_brief_subform(el_type){
//     var hidden_el = $('adding_' + el_type);
//     var form_el = $(el_type + '_form');
//     var link_el = $(el_type + '_header');
//     if(form_el && hidden_el && link_el){
//         form_el.style.display = 'none';
//         hidden_el.value = 'n';
//         link_el.innerHTML = 'add ' + el_type;
//         link_el.writeAttribute('onclick', "display_brief_subform('" + el_type + "'); return false;");
//     }
// }

function change_details_tab(this_tab, el){
    var parent = $('talent_edit_details_form');
    var children = parent.getElementsByClassName('talent_edit_details_tab');
    
    children.each(
        function(item, index) {
            if(item.readAttribute('id') == 'talent_edit_' + this_tab){
                item.style.display = '';
            } else {
                item.style.display = 'none';
            }
        }
    )
	$('talent_edit_form_tabset_second').down().immediateDescendants().each(
		function(item) {
			item.className = "";
		}
	)
	el.up().className = "active";
}

function change_brief(el, dest, page){
    var id = el.value;
    var url = dest.replace("%25s", id);
    var options = {asynchronous:true, evalScripts:true}
    new Ajax.Updater(page, url, options);
}

function resubmit_search(el, value_input_id, form_id){
    var submit_val = el.value;
    $(value_input_id).value = submit_val;
    $(form_id).submit();
}

function change_country(el){
    location.href = "?country=" + el.value;
}

function update_available_areas(el, url_prefix, target){
    var submit_val = el.value;
    var options = {asynchronous:true, evalScripts:true}
    new Ajax.Updater(target, url_prefix + '/' + submit_val, options);
}

