
if(typeof Z1RHELMETS == 'undefined') {
	Z1RHELMETS = {};
}


/**
 * Controller
 * @author Ebobbitt
 * @classDescription This is the Controller class for the Z1R Helmets site.
 */
(function() {
	// CONTROLLER CONSTRUCTOR
	Z1RHELMETS.Controller = function(model) {
		this.Model = model;
        this.View = new Z1RHELMETS.View();
		this.init();
	};
	
	
	// PROTOTYPE REFERENCES
	// Setup Prototype Object Reference
	var Controller = Z1RHELMETS.Controller.prototype;
	
	
	// TEST FOR IE6
	// Is IE6 Browser In Use?
	Controller.is_ie6 = false;
	
	
	// ALL OTHER CONTROLLOERS
	Controller.init = function() {
		// VIEWPORT CONTROL
		// Re-scale content on window resize.
		$(window).bind('resize', this, this.resize_window);
		
		
		// CLEAR INPUT VALUE
		$('input#search_field').bind('click', this, this.clear_value);
		$('input#newsletter_field').bind('click', this, this.clear_value);
		
		
		// PAGE ACTIONS
		$('input#newsletter_submit').bind('click', this, this.submit_newsletter); // Newsletter Submit
		$('input#dealerLocatorSubmit').bind('click', this, this.search_dealers); // Dealer Search Submit
		$('.colorway').bind('click', this, this.swap_colorway); // Swap the current colorway imagery.
		$('#colorways .colorway').bind('mouseover', this, this.show_color); 
		$('#colorways .colorway').bind('mouseout', this, this.show_default_color);
		// TODO: These need to be re-factored
		
		
		// MODAL POP-UP FUNCTIONALITY
		// Product Detail Modal Pop-ups
		$('#pnLink').bind('click', this, this.parts_modal); // Open Part Numbers Modal
		$('#fcLink').bind('click', this, this.fit_modal); // Open Fit Chart Modal
		
		
		// ZIP CODE FUNCTIONALITY
		// If the Zip Code Field Exists, Provide Functionality.
		if($('input#zipCode')[0]) {
			$('input#zipCode').bind('keydown', this, this.allow_digits);
			$('input#zipCode').bind('click', this, this.clear_value);
		}
		
		
		// GOOGLE MAPS BINDS
		this.map_actions();
		
		
		// TEST MODAL EVENT
		$('#video_modal').bind('click', this, this.video);
		
		
		// FIX PNG GRAPHICS
		var browser=navigator.appName;
		var b_version=navigator.appVersion;
		var version=parseFloat(b_version);
		if (browser == "Microsoft Internet Explorer" && version <= 4 && document.all && !window.XMLHttpRequest) {
			this.is_ie6 = true;
			if ($('.z1rPNG').length > 0) {
				this.View.update_png_crop(null);
			}
			if ($('.z1rPNG_scale').length > 0) {
				this.View.update_png_scale(null);
			}
			if ($('#z1rPageTitlePNG').length > 0) {
				this.View.update_title(null);
			}
			if($('#fcLink img').length > 0) {
				this.View.update_fit_graphic(null);
			}
		}
	};
	
	
	// GOOGLE MAPS ACTIONS
	// Sets up any actions associated with google maps.
	// Set in a function as to make these actions reusable. 
	Controller.map_actions = function() {
		if($('#map_canvas').length > 0) {
			if($('#dealerResults a').length > 0) {
				$('#map_canvas').show(); // #map_canvas is hidden by default
				this.load_google_maps();
				$('#dealerResults a').bind('click', this, this.handle_dealer_click);
			}
		}
	};
	
	
	// CLEAR INPUT VALUE FUNCTIONALITY
	// Clears an input value on a target (Bind to Element)
	Controller.clear_value = function(e) {
		var el = $(e.target);
		var t = e.data;
		var id = $(el)[0].id;
		var fields = t.Model.form_fields;
		
		for(var i=0; i<fields.length; i++) {
			if(id == fields[i].name && $(el)[0].value == fields[i].value) {
				t.View.clearInput(e.target);
			}
		}
	};
	
	
	// SHOW PRODUCTS SUB-NAV
	// Shows sub navigation elements for Street / Accessories Links
	//TODO: Re-enable this functionality as sideNav had been refactored since this was written
	/*Controller.toggle_nav_item = function(e) {
		e.preventDefault();
		var v = e.data.View;
		v.toggle_navigation($(e.target).parent().next('ul')[0]);
	};*/
	
	Controller.show_color = function(e) {
		var v = e.data.View;
		var color = $(this).attr('title');
		v.show_color(color);
	};
	
	Controller.show_default_color = function(e) {
		var v = e.data.View;
		v.show_default_color();
	};
	
	Controller.swap_colorway = function(e) {
		
		if(e.target.firstChild) { //clicked on link attach event to image (next child)
			e.target=e.target.firstChild
		}
		e.preventDefault();
		var v = e.data.View;
		var rank = e.target.id.split('_')[1];
		v.swap_colorway(this, rank);
	};
	
	// DISPLAY VIDEO MODAL
	// Display a video feature in a modal window.
	Controller.video = function(e) {
		var c = e.data;
		e.preventDefault();
		c.View.modal({
			width: '358px',
			height: '264px',
			url: 'assets/inc/modal/videoViewer.jsp',
			params: { 
				'width': '385px',
				'height': '264px',
				'videoConfigFile': 'z1rVideo.xml',
				'documentRoot': 'http://assets-static.lemansnet.com/sites/z1rhelmets/assets/flash/',
				'videoFile': 'roleModel.flv'
			}
		});
	};

	
	// NEWSLETTER AJAX REQUEST
	// Fire off an ajax request for a newsletter submission.
	Controller.submit_newsletter = function(e) {
		e.preventDefault();
		var v = e.data.View;
		$.ajax({
			type: 'post',
			url: 'assets/inc/submitNewsletter.jsp',
			data: { 'email': $('input#newsletter_field').val() },
			before: v.processing_newsletter(),
			success: function(o) { v.update_newsletter(o); },
			error: function(o) { v.newsletter_error(o) },
			complete: function(o) { }
		});
	};
	
	// SEARCH FOR DEALERS
	Controller.search_dealers = function(e) {
		e.preventDefault();
		var c = e.data;
		var v = e.data.View;
		$.ajax({
			type: 'post',
			url: 'assets/inc/searchDealers.jsp',
			data: { 
				'zipCode': $('input#zipCode').val(),
				'distance': $('select#distance').val(),
				'searchedDealers': true
			},
			before: v.loading_dealers(),
			success: function(o) { v.update_dealers(o); c.map_actions(); },
			error: function(o) { v.dealers_error(o) },
			complete: function(o) { v.clear_loading_dealers(); }
		});
	};
	

	// PART NUMBERS MODAL
	// Open the Part Number Modal
	Controller.parts_modal = function(e) {
		e.preventDefault();
		var c = e.data;
		var product_id = $('#parameters .product_id')[0];
		
		c.View.modal({
			width: '705px',
			height: '370px',
			style: 'part_numbers_modal',
			url: 'assets/inc/modal/partNumbers.jsp',
			params: { 
				'id': $(product_id).html()
			}
		});
	};
	
	
	// FIT CHART MODAL
	// Open the Fit Chart Modal
	Controller.fit_modal = function(e) {
		e.preventDefault();
		var c = e.data;
		var img = new Image();
		
		img.onload = function(){
			c.View.modal({
            width: String(img.width + 10) + 'px', //dynamic image width
            height: String(img.height + 55) + 'px', //dynamic image height
            style: 'fit_chart_modal',
            url: 'assets/inc/modal/fitCharts.jsp',
            params: { 
                'imgName': $('#fit_detail_img').html(),
                'fit_chart_title': $('#fit_chart_title').html()
            },
            callback: function() {
                if (c.is_ie6) {
                    c.View.update_fit_modal(null);
                }
            }
            });
		};
		
		img.src = $('#fit_detail_img').html();
		
	};
	
	
	// ADJUST VIEWPORT
	// When the window resizes, adjust the user's viewport
	Controller.resize_window = function(e) {
		var v = e.data.View;
		v.center($('#modal')[0]);
		v.center($('#messages')[0]);
		v.scale_mask();
	};
	
	
	// ALLOW DIGITS
	// http://tlt.its.psu.edu/suggestions/international/web/encoding/02ascii.html
	// http://webonweboff.com/tips/js/event_key_codes.aspx
	// Only allow digits to be entered.
	Controller.allow_digits = function(e) {
		var prevent = false;
		var key = e.keyCode; 
		
		// Check for 0...9 Input		
		if(key < 48 || key > 57) { prevent = true; };
		
		// Check for Numpad 0...9 Input
		if(key >= 96 && key <= 105) { prevent = false; };
		
		// Check for Backspace, Tab, Delete, Left - Right Arrows, home and end key
		if (key == 8 || key == 9 || key == 46 || key == 37 || key == 39 || key == 36 || key == 35) { prevent = false; };
		
		// Check for common key sequences: a, x, c, v, with ctrl (and/or Left and Right Windows keys for Mac's Command key???)	
		//		ctrl		l win		r win
		if (key == 17 || key == 91 || key == 92) {
			//			a			x			c			v				A			X			C				V
			if (key == 65 || key == 88 || key == 67 || key == 86 || key == 97 || key == 120 || key == 99 || key == 118) { prevent = false; };
		};
			
		if(prevent === true) {
			e.preventDefault();
		};
	};
	
	
	// GOOGLE MAPS FUNCTIONALITY
	Controller.handle_dealer_click = function(e) {
		var target = e.target;
		if($(target).hasClass('pan')) {
			e.preventDefault();
			var id = target.id.split('_')[1];
			if(gmap_dealers[id].point) {
				map.setZoom(15);
				map.panTo(gmap_dealers[id].point);
				GEvent.trigger(markers[id], "click");
			}
		}
	}
	
	// Load Google Maps
	Controller.load_google_maps = function() {
	  if (GBrowserIsCompatible() && gmap_dealers != null) {
		window.unload = GUnload();
		map = new GMap2(document.getElementById("map_canvas"));
		var offset = { x: -28, y: -125 };
		var anchor = { x: 0, y: -20 };
		gXMap = new xMap(anchor, offset);
		map.addOverlay(gXMap);

		var geocoder = new GClientGeocoder();
		var count = 0;
		
		// Controls
		map.addControl(new xSlider(52,17));
		map.addControl(new xNav());
		
		// Base Icon Properties
		var baseIcon = new GIcon();
		baseIcon.iconSize = new GSize(20, 29); //Dimensions of marker icon (29, 40)
		baseIcon.iconAnchor = new GPoint(10, 30); //Offset for overlay graphic (15, 40)
		baseIcon.infoWindowAnchor = new GPoint(15, 30);
		baseIcon.infoShadowAnchor = new GPoint(15, 30);
		baseIcon.image = "http://assets-static.lemansnet.com/sites/z1rhelmets/assets/img/graphics/icons/maps/marker.png";
		
		function createIcon(point, id) {
			if(point) { 
				// Set Map Center
				count++;
				if(count == 1) { map.setCenter(point, 9);	}
				
				// Add Point to Dealers Object
				gmap_dealers[id].point = point;
				
				// Set up our GMarkerOptions object
				markerOptions = { icon:baseIcon, title:gmap_dealers[id].name };
				var marker = new GMarker(point, markerOptions);	
				
				// Set Event Listener, Return Marker Object
				GEvent.addListener(marker, "click", function() {
					var dealer = gmap_dealers[id];
					var data =	'<h3>' + dealer.name + '</h3>' + 
								'<p>' + dealer.address1 + '<br />' + dealer.city + ',' + dealer.state + ' ' + dealer.zip + '</p>';					
					map.panTo(marker.getPoint());
					gXMap.markerWindow(marker, data, null);
				});
			  return marker;
			}
		}
				
		for(var i=0; i<gmap_dealers.length; i++) {
			var address = gmap_dealers[i].address1 + ' ' + gmap_dealers[i].address2 + ' ' + gmap_dealers[i].city + ', ' + gmap_dealers[i].state + ' ' + gmap_dealers[i].zip;
			var latLng = new GLatLng(gmap_dealers[i].latitude, gmap_dealers[i].longitude);
			var id = i;
			var gcode = function(id, latLng) {
				//console.log(latLng);
				
				var marker = createIcon(latLng, id);
				if(marker) { markers.push(marker); map.addOverlay(marker); }
				}
				gcode(id, latLng);
			}
	  	}
	}
	

})();

