// Using object literal notation to provide a global JavaScript namespace.
// This file currently holds all bamboo javascript in a single namespace 'ban'.
var ban = {
	
	// ### General Helper Methods ###
	
	// Browser-agnostic way of getting the height of the window.
	get_window_height : function() {
		if(window.self && self.innerHeight) {
			return self.innerHeight;
		}
		if(document.documentElement && document.documentElement.clientHeight) {
			return document.documentElement.clientHeight;
			}
		return 0;
	},
	
	// ### Form Helper Methods ###
	
	// Clone an existing image upload HTML form field to allow
	// multiple image uploads.
	add_another_image_field : function() {
		var current_fields = $('pics_to_upload').getElementsByTagName('div');
		var new_field = current_fields[0].cloneNode(true);
		new_field.id = 'upload_image_' + current_fields.length;
		var input = new_field.getElementsByTagName('input')[0];
		input.id = input.name = 'new_images[' + current_fields.length + ']';
		input.value = null;
		$('pics_to_upload').appendChild(new_field);
	},

	// ### Image Gallery Methods ###

	// method to set up a thumbnail gallery
	prepareGallery : function() {
	  if (!document.getElementsByTagName) return false;
	  if (!document.getElementById) return false;
	  if (!document.getElementById("tAdDetailPhotoThumbs")) return false;
	  var gallery = document.getElementById("tAdDetailPhotoThumbs");
	  var links = gallery.getElementsByTagName("a");
	  for (var i=0; i < links.length; i++) {
			links[i].onmouseover = function() {
				return ban.showPic(this);
	    	}
			links[i].onclick = function() {
	      		return false;
			}
		}
	},
	
	// method to swap the main image in a thumbnail galleray
	showPic : function(whichpic) {
	  if (!document.getElementById("placeHolder")) return true;
	  var source = whichpic.getAttribute("href");
	  var placeholder = document.getElementById("placeHolder");
	  placeholder.setAttribute("src",source);
	  return false;
	},

	// image selection setup method
	select_primary_setup: function() {
		$A(document.getElementsByClassName('tUploadImage')).each(function(image_div){
			image_tag = image_div.getElementsByTagName('img')[0];
			Event.observe(image_tag, 'click', ban.select_primary);
		});
	},
	
	// image selection color method
	select_primary: function(e) {
		var t = e.target;
		var image_id = t.parentNode.parentNode.id.match(/\d+$/);
		var old_id = $('ad_primary_image_id').value;
		t.parentNode.addClassName('selected_uploadimage');
		$('ad_primary_image_id').value = image_id;

		if (old_id != "" && old_id != image_id) {
			var old_elem = $('imageform-image-' + old_id).getElementsByTagName('div')[0];
			old_elem.removeClassName('selected_uploadimage');
		}
	},

	// ### Modal Window Methods ###

	// Display a modal window. This requires that a document element exists with id 'modalBackground'
	show_modal : function(modal) {
		modal.style.visibility = 'visible';
		this.resize_modal_window(modal);
	},

	// Resize a modal window based on browser dimensions. We only need to move the dialog
	// based on scroll position if we're using a browser that doesn't support position: fixed, like IE
	resize_modal_window : function(modal_window) {
		var left = document.all ? document.documentElement.scrollLeft : 0;
		var top = document.all ? document.documentElement.scrollTop : 0;
		var div = modal_window;
		div.style.left = Math.max((left + (this.modal_get_window_width - div.offsetWidth) / 2), 0) + 'px';
		div.style.top = Math.max((top + (this.modal_get_window_height - div.offsetHeight) / 2), 0) + 'px';
	},
	
	// Close a modal window. This requires document elements 'modalWindow' and 'modalBackground'.
	close_modal : function(modal) {
		modal.style.visibility = 'hidden';
	},

	// Modal window utility function to get window width.
	modal_get_window_width : function() {
		var width =
			document.documentElement && document.documentElement.clientWidth ||
			document.body && document.body.clientWidth ||
			document.body && document.body.parentNode && document.body.parentNode.clientWidth ||
			0;
		return width;
	},

	// Modal window utility function to get window height.	
	modal_get_window_height : function() {
	    var height =
			document.documentElement && document.documentElement.clientHeight ||
			document.body && document.body.clientHeight ||
	  		document.body && document.body.parentNode && document.body.parentNode.clientHeight ||
	  		0;
	  	return height;
	},
	
	// ### Google Maps Methods ###
	
	// Find a page element with id "map" and create a google map object for it.
	// The google map object is returned.
	setup_google_map_element: function() {
		var map = document.getElementById("map");
		if (GBrowserIsCompatible() && map) {
			var google_map = new GMap2(map);
		}
		
		return google_map;
	},

	// Perform setup for the live visitor tracking map.
	// This includes a periodical function call to update_hit_tracker to update
	// The pushpin every time we get a hit. This method is called from an event
	// handler, so we cannot use 'this'.
	hit_tracker_setup : function() {
		var google_map = ban.setup_google_map_element();
		if (google_map) {
			google_map.setCenter(new GLatLng(39.717, -121.945), 5);
			ban.update_hit_tracker(google_map);
			new PeriodicalExecuter(function() {
				ban.update_hit_tracker(google_map);
			} , 10);
		}
	},

	// Use AJAX to fetch the latest hit from bamboo and put a pin in the
	// appropriate google map location.
	// This method is called from an event handler, so we cannot use 'this'.
	update_hit_tracker : function(google_map) {
		new Ajax.Request('tr/locate_latest_hit', {
			method:    'get',
			onSuccess: function(transport, json) {
				ban.set_map_marker_from_hit(google_map, json);
			}
		});
	},

	// Take hit information in JSON format and draw a pin on the google map for it.
	set_map_marker_from_hit : function(google_map, json) {
		var ll = new GLatLng(json.latitude, json.longitude);
		google_map.panTo(ll);
		var marker = new GMarker(ll);
		google_map.addOverlay(marker);
		var info_element = document.createElement('div');
		info_element.innerHTML = 'City: ' + json.city + '<br/>Source: ' + json.source;
		marker.openInfoWindow(info_element);
	},
	
	// Event listener that performs setup for an advertiser map. This method requires
	// that the variable ban.advertiser has been set.
	advertiser_map_setup : function() {
		var google_map = this.setup_google_map_element();
		google_map.setCenter(this.advertiser_to_point(this.advertiser), 13);
		var marker = this.place_advertiser_marker(google_map, this.advertiser);
		GEvent.trigger(marker, "click");
	},
	
	advertiser_popupless_setup : function() {
		var google_map = this.setup_google_map_element();
		google_map.setCenter(this.advertiser_to_point(this.advertiser), 13);
		var marker = this.place_advertiser_marker(google_map, this.advertiser);
	},
	
	// Take an advertiser object as argument, and return a Google Lat Long point
	advertiser_to_point : function(advertiser) {
		return new GLatLng(advertiser.latitude, advertiser.longitude);
	},
	
	// Place a marker on map for the given advertiser. This function requires that the page
	// has an element with id 'advertiser_box_<advertiser.id>'. Which is used to create the
	// info window.
	place_advertiser_marker : function(map, advertiser) {
	    var marker = new GMarker(this.advertiser_to_point(advertiser));
	    var advertiser_box = document.getElementById("ad_box_" + advertiser.id);
	    map.addOverlay(marker);
		if(advertiser.special)
			marker.setImage('http://www.google.com/uds/samples/places/temp_marker.png');
	    GEvent.addListener(marker, "click", function () {marker.openInfoWindow(advertiser_box);});
	    return marker;
	},

	// Setup for vehicle search portal page. Requires that the instance variable
	// 'ban.advertisers' has been set along with 'ban.map_center'
	setup_car_search : function() {
		var google_map = this.setup_google_map_element();
		var point = new GLatLng(this.map_center.latitude, this.map_center.longitude);
		google_map.setCenter(point, 13);
		google_map.addControl(new GSmallMapControl());
		var markers = this.google_maps_advertisers(google_map, this.ads);
		this.google_maps_mouse_overs(google_map, markers);
	},
	
	google_maps_advertisers : function(map, advertisers) {
		var bounds = new GLatLngBounds();
		var markers = new Array();
		for(var i = 0; i < advertisers.length; i++) {
			var marker = this.place_advertiser_marker(map, advertisers[i]);
			bounds.extend(marker.getPoint());
			markers[advertisers[i].id] = marker;
		}
		var zoom_level = map.getBoundsZoomLevel(bounds);
		if(zoom_level > 9)
			zoom_level = 9;
		map.setZoom(zoom_level);
		return markers;
	},

	google_maps_mouse_overs : function(map, markers) {
		ad_links = document.getElementById('content').getElementsByTagName('div');
		$A(ad_links).each(function(ad_link){
			if(ad_link.hasAttribute('ad_id')) {
				var ad_id = ad_link.getAttribute('ad_id');
				var marker = markers[ad_id];
				
				if(marker) {
					Event.observe(ad_link, 'mouseover', function(){
						if(map.getInfoWindow().getPoint() != marker.getPoint())
							GEvent.trigger(marker, "click");
					});
				}
			}
		});
	},

	resize_element_to_height : function(elem) {
		var total_height = this.get_window_height();
		var offset = elem.parentNode.offsetTop;
		var other_offset = elem.offsetTop;
		var height = total_height - offset - other_offset - 40;
		elem.style.height = height + 'px';
	},
	
	resize_map_window : function() {
            this.resize_element_to_height($('map'));
            this.resize_element_to_height($('cats_listing'));
	},
	
	submit_checkout_form : function() {
		document.BB_BuyButtonForm.submit();
	},
	
	stuffed_ads_setup : function() {
		$('lead[zip]').observe('change', this.stuff_ads);
		$('lead_make').observe('change', this.stuff_ads);
		$('lead_model').observe('change', this.stuff_ads);
		$('lead_year_from').observe('change', this.stuff_ads);
		$('lead_year_to').observe('change', this.stuff_ads);
	},
	
	stuff_ads : function(event) {
		var zip = $('lead[zip]').value;
		var make = $('lead_make').value;
		var model = $('lead_model').value;
		var year_from = $('lead_year_from').value;
		var year_to = $('lead_year_to').value;
		new Ajax.Updater(
			'stuffed_ads',
			'/findmeusedcars/ajax_search',
			{method: 'get', parameters: {zip: zip, make: make, model: model, year_from: year_from, year_to: year_to}}
		);
	},
	
	verify_zip : function(zip) {
		if(zip.match(/^\d{5}$/)) {
			return true;
		}
		window.alert('Please enter a valid Zip code.');
		return false;
	},
	
	// Removes leading and ending whitespaces
	trim : function(value) {
		return value.replace(/(^\s*)|(\s*)$/g, '');
	},
	
	verify_contact_seller_data : function() {
		var ErrMsg = ''
		
		ErrMsg += this.validator('lead_name', this.name_validator, "Name entered is not valid.\n", "Name");
		ErrMsg += this.validator('lead_phone_number', this.phone_validator, "Telephone number entered is not valid.\n", "Phone Number");
		ErrMsg += this.validator('lead_postal_code', this.zip_validator, "Zip Code entered is not valid.\n", "Zip Code");
		ErrMsg += this.validator('lead_best_time_to_call', this.dropdown_validator, "Best time to call is not selected.\n", "");
		ErrMsg += this.validator('lead_trade_in', this.dropdown_validator, "Trade in is not selected.\n", "");
		ErrMsg += this.validator('lead_down_payment', this.dropdown_validator, "Down payment is not selected.\n", "");
		ErrMsg += this.validator('lead_need_financing', this.dropdown_validator, "Financing is not selected.\n", "");
		
		return this.alert_on_error(ErrMsg);
	},

	validate_augment_lead : function() {
		var ErrMsg = ''
		
		ErrMsg += this.validator('lead_name', this.name_validator, "Name entered is not valid.\n", "");
		ErrMsg += this.validator('lead_phone_number', this.phone_validator, "Telephone number entered is not valid.\n", "");
		ErrMsg += this.validator('lead_ready_to_buy_now', this.dropdown_validator, "Ready to buy now is not selected.\n", "");
		ErrMsg += this.validator('lead_trade_in', this.dropdown_validator, "Trade in is not selected.\n", "");
		ErrMsg += this.validator('lead_financed_through', null, "Trade-in financing not specified.\n", "");
		ErrMsg += this.validator('lead_down_payment_amount', null, "Down payment not specified.\n", "");
		ErrMsg += this.validator('lead_need_financing', this.dropdown_validator, "Financing is not selected.\n", "");
		ErrMsg += this.validator('lead_bad_history', this.dropdown_validator, "Previous bankruptcy is not selected.\n", "");
		ErrMsg += this.validator('lead_address', null, "Address entered is not valid.\n", "");
		ErrMsg += this.validator('lead_city', null, "City entered is not valid.\n", "");
		ErrMsg += this.validator('lead_state', this.dropdown_validator, "State is not selected.\n", "");
		ErrMsg += this.validator('lead_postal_code', this.zip_validator, "Zip Code entered is not valid.\n", "");
		ErrMsg += this.validator('lead_service', this.dropdown_validator, "Service is not selected.\n", "");
		
		return this.alert_on_error(ErrMsg);
	},
	
	alert_on_error : function(ErrMsg) {
		if (ErrMsg.length > 0) {
			alert(ErrMsg);
			return false;
		}
		return true;
	},

	validator : function(element_id, validator, error_message, default_value) {
		var e = document.getElementById(element_id);
		if (e) {
			e.style.backgroundColor = "#FFFFFF";
			if (e.value == default_value || (validator != null && !validator.validate(e.value))) {
				e.value = default_value;
				e.style.backgroundColor = "#FFD100";
				return error_message;
			}
		}
		return '';
	},
  
	zip_validator : {validate : function(zipEntered) {
		return zipEntered.match(/^\d{5}$/);
	}},

	phone_validator : {validate : function(phone) {
		phone = phone.replace(/\D/g, '');
		if (phone.length == 10) {
			return true;
		}
	}},
	
	name_validator : {validate : function(name) {
		return !(ban.trim(name).length < 2);
	}},

	email_validator : {validate : function(str) {
		return str.match(/^.+@.+\.\w{2,3}$/);
	}},

	dropdown_validator : {validate : function(s) {
		return s != "";
	}},

	setup_preserve_text_box_content : function() {
		var inputs = $A(document.getElementsByTagName('input'));
		inputs.reject(function(i) { i.type == 'text'})		
		inputs.each(function(input) {
			ban.preserve_text_box_content(input);
		});
		
		$A(document.getElementsByTagName('textarea')).each (function(box) {
			ban.preserve_text_box_content(box);
		});
	},
	
	preserve_text_box_content : function(input) {
		input.original_text = input.value;
		Event.observe(input, 'click', ban.clear_text);
		Event.observe(input, 'blur', ban.restore_text);
	},

	clear_text : function(event) {
		control = Event.element(event);
		if (control.value == control.original_text) {
			control.value = "";
		}
	},
	
	restore_text : function(event) {
		control = Event.element(event);
		if (ban.trim(control.value) == "") {
			control.value = control.original_text;
		}
	},
	
	disableVinLookup    : function() {
        Element.show('ajax-loader');
            Element.hide('vin_lookup');
    },

    enableVinLookup    : function() {
        Element.hide('ajax-loader');
        Element.show('vin_lookup');
    },

	set_service_dropdown : function(cat) {
		var l = $('lead_service');
		var servs = cat == '' ? ban.all_services : ban.services[cat];
		ban.generic_set_dropdown(l, servs);
	},
	
	set_model_dropdown : function(make) {
		var l = $('model');
		var models = make == '' ? ban.all_models : ban.models[make];
		ban.generic_set_dropdown(l, models);
	},
	
	generic_set_dropdown : function(e, items) {
		e.options.length = 1;
		$A(items).each(function(item){
			var o = document.createElement('option');
			o.value = item;
			o.appendChild(document.createTextNode(item));
			e.appendChild(o);
		});
	},

	setup_customer_map: function(){
		var google_map = ban.setup_google_map_element();
		var center = new GLatLng(ban.center_lat, ban.center_long);
		google_map.setCenter(center, 13);
		var marker = new GMarker(center);
		google_map.addOverlay(marker);
	},
	
	carousel_next: function (){
		$('carousel_holder').morph('left: 0px');
	},

	carousel_previous: function (){
		$('carousel_holder').morph('left: 0px');
	},

        certified_toggle_init: function (){
          Event.observe($('ad_new_vehicle_true'), 'click', ban.certified_toggle);
          Event.observe($('ad_new_vehicle_false'), 'click', ban.certified_toggle);
        },

        certified_toggle: function (){
          var new_radio = $('ad_new_vehicle_true');
          var cert = $('ad_certified');
          
          cert.disabled = new_radio.checked;

          if(new_radio.checked)
            cert.checked = false;
        },
	
	swfupload_init_create_ad: function (){
          swfu = new SWFUpload({
            // debug: true,
            upload_url : "/u_images",

            flash_url : "/flash/swfupload.swf",
            flash9_url : "/flash/swfupload_fp9.swf",
            file_size_limit : "1MB",
            file_types : '*.jpg;*.png;*.jpeg;*.pjpeg;*.gif;*.x-png;',

            //Button Settings
            button_placeholder_id : "spanButtonPlaceholder",
            button_image_url : "/images/swfupload_button.png",
            button_width: "61",
            button_height: "22",

            // The event handler functions are defined in handlers.js
            file_queued_handler : fileQueued,
            file_queue_error_handler : fileQueueError,
            file_dialog_complete_handler : fileDialogComplete,
            upload_start_handler : uploadStart,
            upload_progress_handler : uploadProgress,
            upload_error_handler : uploadError,
            upload_success_handler : uploadSuccess,
            upload_complete_handler : uploadComplete,
            queue_complete_handler : queueComplete,	// Queue plugin event

            // Custom post parameters
            post_params : {
              "image[ad_id]" : ban.ad_id,
              "image[created_by]" : ban.user_id,
              "include_form_field" : 'true'
            },

            // Custom settings
            custom_settings : {
              progressTarget : "fsUploadProgress",
              cancelButtonId : "btnCancel"
            }
          })
	},

        populate_custom_template: function (){
            var body = 'Reply to: <a href="mailto:{{email}}?subject={{title | url_escape}}">{{email}}</a><br/><br/>\n\
 \n\
{{advertiser_name}}<br/>\n\
{{street}}, {{city}}  {{postal_code}}<br/>\n\
{{phone}}<br/>\n\
<br/>\n\
{{description}}<br/>\n\
 <br/>\n\
{% if {{vin}} %}\n\
   VIN: {{vin}}\n\
  {% if {{mileage}} %}\n\
    , {{mileage}} miles\n\
  {% endif %}<br/>\n\
{% endif %}\n\
 \n\
{% for imgs in image_pairs limit:2 %}\n\
  {% for i in imgs %}\n\
 <img src="{{i}}" style="width: 300px;" />\n\
  {% endfor %}\n\
<br/>\n\
{% endfor %}';

            ban.populate_custom_template_str('', '{{title}}', body);
        },

        populate_custom_template_str: function(name, title, body) {
            $('custom_post_template_title').value = title;
            $('custom_post_template_body').value = body;
            $('custom_post_template_name').value = name;
        }
}
