// $Id: main.js 1422 2007-12-14 12:38:14Z kfoo $

// CONFIGURATION

var config = {

	filter_form_element: "skirepublic_filter_form", // the element that stores the form holding the various search filter checkboxes 
	filter_results_element: "filter_results",       // the element the results get rendered into

	person_picker_element: "basket_contents",       // the select element that sets the "active" person (and is linked to the search filter)
	person_picker_class: "person_picker",           // the class of select elements that persent a drop-down list of people to select from
	
	duration_picker_element: "select-duration-choose",
	boots_picker_element: "boots-choose", 

	person_panel_element: "person_panel",           // the person panel element itself
	person_panel_class: "add_person_panel",			// clicking on any element with this class pops up the person panel

	tooltip_class: "tooltip",

	reservation_form_element: "basket_filter",      // the select element that determines the basket filter
	reservation_results_element: "basket_contents",	// the element the reservation (basket) gets rendered into

	rest_api_url: null                              // set to locale-specific version in header 

};

document.ajax = Ajax;

// NAMESPACE, GLOBAL VARIABLES

var skirepublic = {

	locale: null,

	reservation_array: null, // holds get_reservation_line_array()
	reservation_array_onchange: [ ],

	person_array: null, // holds get_person_array()
	person_array_onchange: [ ],
	dropdown_activated: null, //store the dropdown id which activated person panel
	person_added: false,	// check whether any person has been added when person panel open, if its set to true, it will update the dropdown box
	dropdown_pos: null,
	resort_array: null,
	
	ajax_requests_active: 0 // number of active Ajax requests
};

// COOKIE FUNCTION (from jslog)

(function() {

    Cookie = {
        
        get: function(k) {
        	var search = k + "=";
        	var cookie = document.cookie;
        	var result = null;
        	if (cookie.length > 0) {
        		offset = cookie.indexOf(search);
        		if (offset != -1) {
        			offset += search.length;
        			end = cookie.indexOf(";", offset);
        			if (end == -1) {
        				end = cookie.length;
        			}
        			result = decodeURI(cookie.substring(offset, end));
        		} 
        	}
        	return result;                                
        },
        
        set: function(k, v) {
            document.cookie = k + "=" + encodeURI(v) + "; expires=Sun, 17 Jan 2038 20:14:08 UTC; path=/";
        }
        
    };

})();

// "translate" function, analogous to the t() function in PHP

function t(k) {
	if ( typeof skirepublic.strings[k] == 'undefined' ){
		return k;
	} else {
		return skirepublic.strings[k];
	}	
}

// TOOLTIP OBJECT

if (typeof skirepublic.tooltip == 'undefined') { skirepublic.tooltip = { }; }

Event.observe(window, "load", function () {

	if (document.getElementsByClassName(config.tooltip_class)) {
		//alert("load");
		skirepublic.tooltip.overlay = new YAHOO.widget.Overlay("tooltip", { iframe:true, visible:false, width:"200px" } );
		skirepublic.tooltip.overlay.setHeader('');
		skirepublic.tooltip.overlay.setBody('');
		skirepublic.tooltip.overlay.render(document.body);
		
		document.getElementsByClassName(config.tooltip_class).each(function (e) {
			Event.observe(e, "mouseover", function (e) {
				var el = Event.element(e);
				var s = el.up("span").id;
				var msg = skirepublic.tooltip.messages[el.up("span").id];
				skirepublic.tooltip.overlay.setHeader("<h2>" + t("EXPLANATION") + ":</h2><div class=\"hr\"><hr /></div>");
				skirepublic.tooltip.overlay.setBody(msg.body);
				skirepublic.tooltip.overlay.cfg.setProperty("context", [ el, "tl", "tr" ]);
				skirepublic.tooltip.overlay.show(); 
			});
			Event.observe(e, "mouseout", function (e) { skirepublic.tooltip.overlay.hide(); });
		});
		
	}
	
});


// RESERVATION (BASKET) OBJECT

if (typeof skirepublic.reservation == 'undefined') { skirepublic.reservation = { }; }

Event.observe(window, "load", function () {

	if ($(config.reservation_results_element)) {
		skirepublic.person_array_onchange.push(skirepublic.reservation.render);
		skirepublic.reservation_array_onchange.push(skirepublic.reservation.render);
	}
	
	if ($(config.reservation_form_element)) {
		Event.observe($(config.reservation_form_element), "change", function () {
			skirepublic.reservation.render();
		});
	}
	
});

skirepublic.reservation.render_items = function(person_id) {

	var el = $("person_id_" + person_id + "_items");
	
	if (el) {
		el.update(skirepublic.format_items(skirepublic.reservation_array.findAll(function (l) { return l.person_id == person_id; }).size()));
	}

};

skirepublic.reservation.render_subtotal = function(person_id) {

    var el = $("person_id_" + person_id + "_subtotal");
    
    if (el) {

	    var subtotal = skirepublic.reservation_array.findAll(function (l) {
	    	return l.person_id == person_id;
	    }).inject(0, function(acc, l) {
	    	return acc + l.product_price;
	    });
	    
	    el.update(skirepublic.format_price(subtotal));
	    var e = new Effect.Highlight(el, { duration: 2 });

	}
    
};

skirepublic.reservation.render_total = function() {

	var subtotal_price_el = $("subtotal_price");
	var discount_price_el = $("discount_price");
	var total_price_el = $("total_price");
	
	if (subtotal_price_el && discount_price_el && total_price_el) {
	
    	var subtotal = 0;
    	var discount = 0;
		
		var ajax = new Ajax.Request(config.rest_api_url + "/calculate_cost", {
        			onSuccess: function(res) {
        			 			var json = eval('(' + res.responseText + ')');
        							subtotal = json.subtotal;
        							discount = json.discount;
									subtotal_price_el.update(skirepublic.format_price(subtotal));
									var h1 = new Effect.Highlight(subtotal_price_el, { duration: 2 });
									
									discount_price_el.update(skirepublic.format_price(discount));
									var h2 = new Effect.Highlight(discount_price_el, { duration: 2 });
									
									total_price_el.update(skirepublic.format_price(subtotal - discount));
									var h3 = new Effect.Highlight(total_price_el, { duration: 2 }); 
         							
        					}});        
	} 

};

skirepublic.reservation.render = function() {

	var head = new Template([
		'<dt class="a-m-t" id="person_id_#{person_id}"><div class="name">#{name}</div> (<span id="person_id_#{person_id}_items">#{n_items}</span>) <span class="open">' + t("[accordion] open") + ' <img src="/img/window-open-button.gif" alt="' + t("[accordion] open") + '" /></span><span class="close">' + t("[accordion] close") + ' <img src="/img/basket-window-close-button.gif" alt="' + t("[accordion] close") + '" /></span></dt>',
		'<dd class="a-m-d">',
			'<div class="bd">',
		        '<table class="basket">'
	].join("\n"));
	
    var body = new Template([
            '<tr id="reservation_line_#{reservation_line_id}_1">',
                '<td colspan="2">',
                    '<div class="basket-item" style="background-image: url(#{image1});"></div>',
                '</td>',
            '</tr>',
            '<tr id="reservation_line_#{reservation_line_id}_2">',
	            '<td valign="bottom" align="left" width="200">',
    	           '<span class="#{category_class}">#{category}</span><br/><span class="brand">#{brand}</span><br/><span>#{name}</span>',
        		   '</td>',
				   '<td valign="bottom" align="right">',
						'<span><label><strong>' + t('boots?') + '</strong><input id="#{wants_boots_id}" type="checkbox"/></label></span>',
					'</td>',
			'</tr>',
            '<tr id="reservation_line_#{reservation_line_id}_3">',
					'<td valign="bottom" align="left">',
						'<span id="#{remove_id}" class="pointer"><img align="top" src="/img/delete-mark.gif"/> ' + t('remove this item') + '</span>',
					'</td>',                                            
					'<td valign="bottom" align="right">',
						'<span id="reservation_line_#{reservation_line_id}_price" class="price">#{price}</span>',
					'</td>',
			'</tr>',
			'<tr id="reservation_line_#{reservation_line_id}_4">',
				'<td colspan="2"><div class="hr"><hr /></div></td>',
			'</tr>'
    ].join("\n"));
    
	var foot = new Template([
				'</table>',
            '</div>',
        '</dd>'
	].join("\n"));

    var html = "";
	var closure_array = [ ]; // array of functions to run after the HTML has been inserted into the DOM
	
	var count = 0;
	var total = 0;

    skirepublic.person_array.each(function (p) {
    
    	var products = skirepublic.reservation_array.findAll(function (r) { return r.person_id == p.id });
    	
		html += head.evaluate({
			name: p.first_name,
			person_id: p.id,
			n_items: skirepublic.format_items(products.size())
		});
				
	    var subcount = 0;
	    var subtotal = 0;
	    
		products.each(function (r) {
    	
		    count += 1;
		    total += r.product_price;  
	    	
	    	subcount += 1;
	    	subtotal += r.product_price;
	    
	        var reservation_line_id = "reservation_line_" + r.reservation_line_id;
	        var remove_id = "remove_" + r.reservation_line_id;
	        var wants_boots_id = "wants_boots_" + r.reservation_line_id;
	        
	        closure_array.push(function () {
	        
	        	$(wants_boots_id).checked = r.wants_boots;
	
	        	Event.observe(remove_id, "click", function() { skirepublic.reservation.remove_reservation_line(r.reservation_line_id); });
	
			    Event.observe(wants_boots_id, "click", function() {
			    
			        var ajax = new Ajax.Request(config.rest_api_url + "/update_reservation_line", {
			        
			            parameters: { 
			            	reservation_line_id: r.reservation_line_id, 
			            	wants_boots: $(wants_boots_id).checked ? 1 : 0 
			            },
			            
			            onSuccess: function(res) {

				            var json = eval('(' + res.responseText + ')');
				            skirepublic.reservation_array = json;
				            
				            var product_price = skirepublic.reservation_array.find(function (l) { 
				            	return l.reservation_line_id == r.reservation_line_id 
				            }).product_price;
				            
				            var el = $("reservation_line_" + r.reservation_line_id + "_price");
				            el.update(skirepublic.format_price(product_price));
				            var e = new Effect.Highlight(el, { duration: 2 });
				            
				            skirepublic.reservation.render_subtotal(p.id);
				            skirepublic.reservation.render_total();
				            
			            }
			        });
			    });
	
	        });
	        
			html += body.evaluate({ 
				image1: r.product_image1,
				category_class: r.product_category.toLowerCase(),
				category: r.product_category,
				brand: r.product_brand,
				name: r.product_name,
				price: skirepublic.format_price(r.product_price),
				remove_id: remove_id,
				wants_boots_id: wants_boots_id,
				reservation_line_id: r.reservation_line_id
			});
				
    	});
    	
		html += foot.evaluate({ 
			name: p.first_name,
			subtotal: skirepublic.format_price(subtotal),
			person_id: p.id
		});
					
    });

    if ( (skirepublic.reservation_array.length > 0) && (!$(config.reservation_form_element) || ($(config.reservation_form_element).value == "everyone")) ){

    	var price = skirepublic.reservation_array.collect(function (r) { return r.product_price; }).sort(function(a, b) { return b - a; });
    	var total = 0;
    	var discount = 0;

    	$R(0, price.length, true).each(function (i) {
    		total += price[i];
    		if (i % 2 == 1) { discount += price[i]; } 	
    	});
    	
	}
	
	// ... save the open element
	
    var dt = $(config.person_picker_element).getElementsBySelector(".a-m-t-expand").first();
    
    // ... redraw the person picker
    
    $(config.reservation_results_element).update(html);
    
    // ... restore the open element
    
    if (dt) {
	    AccordionMenu.openDtById(dt.id);
	}
	else {
		AccordionMenu.openDtById($(config.person_picker_element).getElementsBySelector("dt").first().id); // should really open the "active" dt ...
	}
	
    $("items").update(skirepublic.format_items(count));
    
	closure_array.each(function (fn) { fn(); });
	
	skirepublic.reservation.render_total();
    
};

skirepublic.reservation.remove_reservation_line = function(reservation_line_id, redirect) {

	var person_id = skirepublic.reservation_array.find(function (l) { return l.reservation_line_id == reservation_line_id; }).person_id;

    var ajax = new Ajax.Request(config.rest_api_url + "/remove_reservation_line", {

        parameters: { reservation_line_id: reservation_line_id },

        onSuccess: function(res) {
        
        	if ($("reservation_line_" + reservation_line_id + "_1")) {
	        	var f1 = new Effect.Fade($("reservation_line_" + reservation_line_id + "_1"));
	        	var f2 = new Effect.Fade($("reservation_line_" + reservation_line_id + "_2"));
	        	var f3 = new Effect.Fade($("reservation_line_" + reservation_line_id + "_3"));
	        	var f3 = new Effect.Fade($("reservation_line_" + reservation_line_id + "_4"));
	        }
	        
	        // remove the removed reservation line from the reservation_array

            skirepublic.reservation_array = skirepublic.reservation_array.reject(function (i) { return i.reservation_line_id == reservation_line_id; });
            
            skirepublic.reservation.render_subtotal(person_id);
            skirepublic.reservation.render_items(person_id);
            skirepublic.reservation.render_total();
            
            if ( typeof redirect != 'undefined' ){
	            if ( redirect != '' ){
					document.location=redirect;
				}			
			}

        }
        
    });
    
};

skirepublic.reservation.add_reservation_line = function(product_id) {

    var ajax = new Ajax.Request(config.rest_api_url + "/add_reservation_line", {

        parameters: { product_id: product_id },

        onSuccess: function(res) {
        
            var json = eval('(' + res.responseText + ')');
            
            skirepublic.reservation_array = json;
            skirepublic.reservation_array_onchange.each(function (fn) { fn(); });
            
        }
        
    });

};

// PERSON PICKER OBJECT

if (typeof skirepublic.personpicker == 'undefined') { skirepublic.personpicker = { }; }

Event.observe(window, "load", function() {

	if (document.getElementsByClassName(config.person_picker_class)) {
		skirepublic.person_array_onchange.push(skirepublic.personpicker.render);
	}

	// Annotate all elements of config.person_picker_class.  These aren't identical!
	// There are at least three types: (1) the "choose equipment for" drop-down on 
	// filter page; (2) the "display equipment for" drop-down on the filter page; 
	// (3) the "equipment is for" drop-down on the chekcout page.
	
	document.getElementsByClassName(config.person_picker_class).each(function (e) {
	
		// Get the currently-selected value, and store it as last_value.  select.last_value
		// is like select.value, except that it stores the "real" selected value of the 
		// select list (i.e. it doesn't get mashed every time the add_person option is
		// selected).  (last_value must be "manually" synchronised.)
		//debugger;
		e.last_value = $A(e.options).find(function (o) { return o.selected; }).value;
		
		
	    // do these things when the active person changes
    
    	e.observe("change", function(f) {
    		skirepublic.person_added = false; // reset person has been added status, used for person_panel to determine whether add a new person successfu, if so transfer item 
	    	var select = Event.element(f);
	    
	    	if (select.value == "add_person") {
	    		// store
	    		skirepublic.dropdown_activated = select.id; 
	    		skirepublic.dropdown_pos = null;
	    		skirepublic.personpanel.panel.show();
	    		//skirepublic.personpanel.show();
	    	}else if (select.value == "_") {
	    		$A(select.options).find(function (o) { return o.value == e.last_value; }).selected = true;
	    	}
	    	
	    	if (!isNaN(parseInt(select.value, 10))) {
	    		select.last_value = select.value; // keep the "real" selected value updated
		    }

	    	if (select.hasClassName("has_everyone")) {
		        var ajax2 = new Ajax.Request(config.rest_api_url + "/set_basket_filter_active", {
		            parameters: { person_id: select.value }
		        });
	    	}		    
	    });
        
    });
    
});

skirepublic.personpicker.render = function() {

	document.getElementsByClassName(config.person_picker_class).each(function (e) {
	
		// Re-create options list
		
		var options = [ ];
	
       	if (e.hasClassName("has_everyone")) {
       		options.push(new Option(t("Everyone"), "everyone"));
       	}
       	
       	var length = skirepublic.person_array.length;
       	
        for (var i = 0; i < length; i++) {
        	var o = skirepublic.person_array[i];
        	options.push(new Option(o.first_name, o.id));
        	if (o.id == e.last_value) {
        		options[options.length-1].selected = true;
        	}
       	}
       	
       	if (e.hasClassName("has_add_person")) {
       	
	       	options.push(new Option('__________', '_'));
	       	options.push(new Option(t("Add a person"), 'add_person'));
	       	
	    }
	    
		e.options.length = 0; // delete existing options
		$R(0, options.length, true).each(function (i) { e.options[i] = options[i]; }); // add the options collected on the "options" array

	}.bind(this));

};

function get_viewport_y(){
	return (window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop)+'px';
}

Ajax.Responders.register({
                onCreate: function() {
                		$('throbber').style.marginTop = get_viewport_y();                		
                        if ($('throbber')) { $('throbber').show(); }
                },
                onComplete: function() {      		
                        if ($('throbber')) { $('throbber').hide(); }
                }
        });
