var fields = [
	{ name: 'firstname',
		required: true,
		requiredText: lang('First name required','Prénom requis'),
		validate: function(form, value){ return true; }
	},
	{ name: 'lastname',
		required: true,
		requiredText: lang('Last name required','Nom de famille requis'),
		validate: function(form, value){ return true; }
	},
	{ name: 'email',
		required: true,
		requiredText: lang('Email address required','Adresse courriel requise'),
		validate: function(form, value){
			var objRegExp = /^([a-z0-9]+)([a-z0-9_\-\.\+]*)([a-z0-9]+)@([a-z0-9]+)([a-z0-9_\-\.]*)(\.[a-z]{2,4}(\.[a-z]{2}){0,2})$/i;
			return objRegExp.test(value);
		},
		validateText: lang('A valid email address is required','Une adresse courriel valide requise')
	},
	{ name: 'businessname',
		required: true,
		requiredText: lang('Business name required','Nom de l\'Entreprise requis'),
		validate: function(form, value){ return true; }
	},
	{ name: 'position',
		required: false,
		validate: function(form, value){ return true; }
	},
	{ name: 'country',
		required: true,
		requiredText: lang('Country required','Pays requis'),
		validate: function(form, value){ return true; }
	},
	{ name: 'province',
		required: false,
		requiredText: lang('Province/State/Region required','Province/État/Region requise'),
		validate: function(form, value){
			if(typeof form.province.length != 'undefined' && form.province.length > 0){
				return (form.province.selectedIndex != 0);
			};
		},
		validateText: lang('Province/State/Region required','Province/État/Region requise')
	},
	{ name: 'city',
		required: true,
		requiredText: lang('City required','Ville requise'),
		validate: function(form, value){ return true; }
	},
	{ name: 'address1',
		required: false,
		requiredText: lang('Address required','Adresse requise'),
		validate: function(form, value){ return true; }
	},
	{ name: 'address2',
		required: false,
		requiredText: lang('Address required','Adresse requise'),
		validate: function(form, value){ return true; }
	},
	{ name: 'postalcode',
		required: false,
		validate: function(form, value){ return true; }
	},
	{ name: 'phone',
		required: false,
		requiredText: lang('Phone Number required','Numéro de téléphone requis'),
		validate: function(form, value){ return true; }
	},
	{ name: 'fax',
		required: false,
		requiredText: lang('Fax number required','Numéro de fax requis'),
		validate: function(form, value){ return true; }
	},
	{ name: 'website',
		required: false,
		requiredText: lang('Website required','Site Internet requis'),
		validate: function(form, value){ return true; }
	},
	{ name: 'businesstype',
		required:false,
		validate: function(form, value){
			return (form.isretail.checked || form.isdistributor.checked || form.isexpeditor.checked || form.ismanufacturer.checked);
		},
		validateText: lang('Business type required','Type d\'affaires requis')
	},{ name: 'numstores',
		required: true,
		requiredText: lang('Number of stores required','Nombre de magasins requis'),
		validate: function(form, value){ return true; }
	},{ name: 'numdealers',
		required: true,
		requiredText: lang('Number of car dealers required','Nombre de concessionnaires automobiles requis'),
		validate: function(form, value){ return true; }
	},{ name: 'numsold',
		required: true,
		requiredText: lang('Number of units sold required','Nombre d\'unités vendues requis'),
		validate: function(form, value){ return true; }
	},{ name: 'interestedin',
		required: true,
		requiredText: lang('Units of interest required','Unités intéressées requises'),
		validate: function(form, value){ return true; }
	},{ name: 'buyfrom',
		required: true,
		requiredText: lang('Current purchasing required','Achat courant requis'),
		validate: function(form, value){ return true; }
	},{ name: 'brands',
		required: true,
		requiredText: lang('Other brands required','D\'autres marques requises'),
		validate: function(form, value){ return true; }
	}
];

initForm = function(){
	ajax = new Ajax();
	ajax.url = XMLCountries;
	ajax.caching = true;
	ajax.requestXML(function(response){
		XMLCountries = response.responseJSON.countries;
		theCountry = $('country');
		theCountry.domRCN();
		theProvince = $('province');
		theProvince.domRCN();
		$('province-row').hide();
		theCountry.onchange = function(){
			if(theCountry[0].value == '') theCountry.remove(0);

			theCountry.setStyle({ backgroundImage: 'url(/images/flags/'+theCountry[theCountry.selectedIndex].value.toLowerCase()+'.png)' });

			theProvince.length = 0;
			createCookie(COOKIECountry, theCountry[theCountry.selectedIndex].value);
			if(typeof XMLCountries.country[theCountry.selectedIndex].provinces != 'undefined' && typeof XMLCountries.country[theCountry.selectedIndex].provinces.province != 'undefined'){
				theProvince[0] = new Option('--- choose ---', '', true, true);
				XMLProvinces = XMLCountries.country[theCountry.selectedIndex].provinces;
				XMLProvinces.province.each(function(province){
					var selected = (readCookie(COOKIEProvince) == province.abbr) ? true : false;
					theProvince[theProvince.length] = new Option(province.name, province.abbr, selected, selected);
				});
				$('province-row').show();
			}else{
				$('province-row').hide();
			}
		};
		theCountry[0] = new Option('--- choose ---', '', true, true);
		XMLCountries.country.each(function(country){
			var selected = (readCookie(COOKIECountry) == country.abbr) ? true : false;
			theCountry[theCountry.length] = new Option(country.name, country.abbr ,selected, selected);
		});
		$('country-row').show();
		if(theCountry.selectedIndex > 0) theCountry.onchange();
		theProvince.onchange = function(){
			if(theProvince[0].value == '') theProvince.remove(0);
			createCookie(COOKIEProvince, theProvince[theProvince.selectedIndex].value);
		};
	});
};

submitForm = function(form){
	var form = (form || $('formSignup'));
	$('signup').addClassName('wait');
	var errors = 0;
	fields.each(function(field){
		$('error.'+field.name).hide();
		if(form[field.name] != undefined){
			form[field.name].disable();
			$(form[field.name]).removeClassName('error');
			if(field.required && form[field.name].value == ''){
				errors++;
				$('error.'+field.name).show();
				$('error.'+field.name).innerHTML = field.requiredText;
				$(field.name).addClassName('error');
			}else if(typeof(field.validate) == 'function'){
				if(false == field.validate(form, form[field.name].value)){
					errors++;
					$('error.'+field.name).show();
					$('error.'+field.name).innerHTML = field.validateText;
					$(field.name).addClassName('error');
				}
			}
		};
	});

	if(errors > 0){
		$('signup').removeClassName('wait');
		fields.each(function(field){
			if(form[field.name] != undefined){
				form[field.name].enable();
			};
		});
		return false;
	};

	this.httppost = new HttpPost();
	this.httppost.requestXML(function(response){
		var errors = 0;
		if(response.responseJSON == undefined || response.responseJSON.httppost == undefined){
			$('signup').removeClassName('wait');
			fields.each(function(field){
				if(form[field.name] != undefined){
					form[field.name].enable();
				};
			});
			alert('An unhandled error occurred.\n\nPlease try again shortly.');
			return;
		};
		var XML = response.responseJSON.httppost;
		if(response.responseJSON.httppost['-errors'] == 0){
			//success
			$('signup').removeClassName('wait');
			Object.keys(XML).each(function(key){
				if(form[key] != undefined){  form[key].enable(); };
			});
			$('form-input').hide();
			$('form-message').show();
			window.location.href = '#';

		}else{
			//failed
			$('signup').removeClassName('wait');
			Object.keys(XML).each(function(key){
				if(form[key] != undefined){ form[key].enable(); };
				if(XML[key].error){
					errors++;
					if($('error.'+key) == undefined) return;
					$('error.'+key).show();
					$('error.'+key).innerHTML = XML[key].error;
					$(form[key]).addClassName('error');
				};
			}.bind(this));
		};
		if(errors > 0){
			return false;
		};
	}.bind(this), [], form);
};

populateForm = function(){
	var form = $('formSignup');
	//form.userid.value = session.user.userid;
	form.firstname.value = session.user.firstname;
	form.lastname.value = session.user.lastname;
	form.businessname.value = session.user.businessname;
	if(form.country.length > 1){
		for(var i=0; i<form.country.length; i++){
			if(form.country[i].value == session.user.country){
				form.country.selectedIndex = i;
				form.country.onchange();
			};
		};
	};
	if(form.province.length > 1){
		for(var j=0; j<form.province.length; j++){
			if(form.province[j].value == session.user.province){
				form.province.selectedIndex = j;
				form.province.onchange();
			};
		};
	};
	//country
	//province/state
	form.city.value = session.user.city;
	form.address1.value = session.user.address1;
	form.address2.value = session.user.address2;
	form.postalcode.value = session.user.postalcode;
	form.phone.value = session.user.phone;
	form.fax.value = session.user.fax;
	form.email.value = session.user.email;
};

/* **************************************************
*
* GOOGLEMAP
*
************************************************** */
GoogleMap = Class.create();
Object.extend(GoogleMap.prototype, {
	initialize: function(parent, element, centerLat, centerLng, zoom) {
		this.parent = parent;
		this.element = element;
		this.centerLat = (centerLat) ? centerLat : 47.9;
		this.centerLng = (centerLng) ? centerLng : -97.0;
		this.zoom = (zoom) ? zoom : 4;

		if (GBrowserIsCompatible()) {
			this.map = new GMap2(this.element);
			//this.directions = new GDirections(this.map, this.directionselement);
      			this.map.addControl(new GLargeMapControl());
      			//this.map.addControl(new GMapTypeControl());
			this.map.addControl(new GScaleControl(250));
			this.map.enableDoubleClickZoom();
			this.map.enableScrollWheelZoom();
			this.point = new GLatLng(this.centerLat, this.centerLng, false);
			this.map.setCenter(this.point, this.zoom);

			this.eventScrollWheel  = this.scrollWheel.bindAsEventListener(this);
			GEvent.addDomListener(this.map.getContainer(), "DOMMouseScroll", this.eventScrollWheel);
			this.map.getContainer().onmousewheel = this.eventScrollWheel;
		};
	},

	scrollWheel: function(event){
		if (!event){
			event = window.event
		}
		if (event.preventDefault){
			event.preventDefault();
		}
		event.returnValue = false;
	}

});

/*
YAHOO.util.Event.onDOMReady(function(){
	GPolyline.prototype.Bounds = function() {
		var bounds = new GLatLngBounds();
		for (var i=0; i < this.getVertexCount(); i++) {
			bounds.extend(this.getVertex(i));
		};
		return bounds;
	};
});
*/
/* **************************************************
*
* DISTRIBUTOR
*
************************************************** */
Distributor = Class.create();
Object.extend(Distributor.prototype, GOverlay.prototype);
Object.extend(Distributor.prototype, {
	initialize: function(googlemap, distributor, showTip) {
		this.googlemap = googlemap;
		this.map = this.googlemap.map;
		this.distributor = distributor;

		this.distributorid = (distributor['-id']) ? distributor['-id'] : null ;
		this.name = (distributor.name) ? distributor.name : null ;
		this.url = (distributor.url) ? distributor.url : null ;
		this.city = (distributor.city) ? distributor.city : null ;
		this.province = (distributor.province) ? distributor.province : null ;
		this.country = (distributor.country) ? distributor.country : null ;
		this.postal_code = (distributor.postal_code) ? distributor.postal_code : null ;
		this.latitude = (distributor.latitude) ? distributor.latitude : null ;
		this.longitude = (distributor.longitude) ? distributor.longitude : null ;
		this.phone1 = (distributor.phone1) ? distributor.phone1 : null ;
		this.phone2 = (distributor.phone2) ? distributor.phone2 : null ;
		this.fax = (distributor.fax) ? distributor.fax : null ;
		this.email = (distributor.email) ? distributor.email : null ;
		this.website = (distributor.website) ? distributor.website : null ;
		this.address1 = (distributor.address1) ? distributor.address1 : null ;
		this.address2 = (distributor.address2) ? distributor.address2 : null ;
		this.description_en = (distributor.description_en) ? distributor.description_en : null ;
		this.description_fr = (distributor.description_fr) ? distributor.description_fr : null ;
		this.logo = (distributor.logo) ? distributor.logo : null ;
		this.subdistributors = (distributor.subdistributors) ? distributor.subdistributors : null ;

		this.showTip = (showTip) ? true : false ;

		this.baseicon = new GIcon();
		this.baseicon.image = '/images/icons/pin24.png';
		this.baseicon.size = new GSize(24, 30);
		this.baseicon.shadow = '/images/icons/pin24s.png';
		this.baseicon.shadowSize = new GSize(48, 48);
		this.baseicon.iconAnchor = new GPoint(12, 30);
		this.baseicon.infoWindowAnchor = new GPoint(16, 0);

		this.point = new GLatLng(this.latitude, this.longitude, true);
		//this.marker = new GMarker(this.point, -this.distributorid);
		this.marker = new GMarker(this.point, { icon:this.baseicon, zIndexProcess:this.getIndex });
		this.map.addOverlay(this.marker);

		if(this.showTip){
			this.elementTitle = domCE('span').domAC(
				domCE('img').domSA({
					src: '/images/icons/32x32_map.png',
					align: 'left',
					height: 32,
					width: 32
				})
			).domAC(
				domCE('strong').domCTN(this.name)
			);
			this.elementSubTitle = domCE('em').domSA({ className: 'op50' }).domCTN('Main Warehouse');
			this.elementBody = domCE('div').domSA({
				align: 'center'
			});

			if(this.address1 || this.address2 || this.city || this.province || this.country || this.postalcode){
				this.address = domCE('p')
				if(this.address1) this.address.domAC( domCTN(this.address1) );
				if(this.address2) this.address.domAC(domCE('br')).domAC( domCTN(this.address2) );
				if(this.city || this.province || this.country) this.address.domAC(domCE('br'));
				if(this.city) this.address.domAC( domCTN(this.city) );
				if(this.province) this.address.domAC( domCTN(', '+this.province) );
				//if(this.country) this.address.domAC( domCTN(', '+this.country) );
				if(this.postal_code) this.address.domAC(domCE('br')).domAC( domCTN(this.postal_code) );
				this.elementBody.domAC(
					this.address
				);
			};

			this.element = domCE('div').domSA({
				className: 'tooltip-container'
			}).domAC(
				domCE('div').domSA({
					className: 'tooltip'
				}).domAC(
					this.tool_tip_head = domCE('div').domSA({
						className: 'tooltip-head'
					}).domAC(
						this.elementTitle
					).domAC(
						domCE('br')
					).domAC(
						this.elementSubTitle
					)
				).domAC(
					this.tool_tip_body = domCE('div').domSA({
						className: 'tooltip-body'
					}).domAC(
						this.elementBody
					)
				)
			);

			this.element.className = 'tooltip-container';
			this.element.style.position = 'absolute';
			this.element.style.visibility = 'hidden';

			this.map.getPane(G_MAP_FLOAT_PANE).appendChild(this.element);

			this.eventMouseOver  = this.show.bindAsEventListener(this);
			GEvent.addListener(this.marker, "mouseover", this.eventMouseOver);
			this.eventMouseOut   = this.hide.bindAsEventListener(this);
			GEvent.addListener(this.marker, "mouseout", this.eventMouseOut);

			this.eventClick  = this.clickMapMarker.bindAsEventListener(this);
			GEvent.addListener(this.marker, "click", this.eventClick);
		};

		if(this.subdistributors){
			if(typeof(this.subdistributors.subdistributor.length) == 'undefined') this.subdistributors.subdistributor = [this.subdistributors.subdistributor];
			this.subdistributors.subdistributor.each(function(subdistributor){
				new SubDistributor(this.googlemap, this.distributor, subdistributor, true);
			}.bind(this));
		};
	},

	clickMapMarker: function(){
		window.location.href=lang('/en','/fr')+this.url;
	},

	remove: function(){
		this.element.parentNode.removeChild(this.element);
	},

	redraw: function(force){
		if (!force) return;
		var markerPos = this.map.fromLatLngToDivPixel(this.marker.getPoint());
		var iconAnchor = this.marker.getIcon().iconAnchor;
		var xPos = Math.round(markerPos.x + 3);
		var yPos = markerPos.y - iconAnchor.y - this.element.clientHeight + 3;

		var tDim = this.element.getDimensions();
		var posNE = this.map.fromLatLngToDivPixel(this.map.getBounds().getNorthEast());
		if(xPos > posNE.x - tDim.width - 10) xPos -= (tDim.width + 25);
		if(yPos < posNE.y) yPos += (tDim.height + 25);

		this.element.style.top = yPos + 'px';
		this.element.style.left = xPos + 'px';
	},

	show: function(){
		this.redraw(true);
		this.element.style.visibility = 'visible';
	},

	hide: function(){
		this.element.style.visibility = 'hidden';
	},

	getIndex: function(marker, b){
		return GOverlay.getZIndex(marker.getPoint().lat()) + 100000000;
	}
});

SubDistributor = Class.create();
Object.extend(SubDistributor.prototype, GOverlay.prototype);
Object.extend(SubDistributor.prototype, {
	initialize: function(googlemap, distributor, subdistributor, showTip) {
		this.googlemap = googlemap;
		this.map = this.googlemap.map;
		this.distributor = distributor;
		this.subdistributor = subdistributor;

		this.subdistributorid = (subdistributor['-id']) ? subdistributor['-id'] : null ;
		this.name = (subdistributor.name) ? subdistributor.name : null ;
		this.city = (subdistributor.city) ? subdistributor.city : null ;
		this.province = (subdistributor.province) ? subdistributor.province : null ;
		this.country = (subdistributor.country) ? subdistributor.country : null ;
		this.latitude = (subdistributor.latitude) ? subdistributor.latitude : null ;
		this.longitude = (subdistributor.longitude) ? subdistributor.longitude : null ;

		this.showTip = (showTip) ? true : false ;

		this.baseicon = new GIcon();
		this.baseicon.image = '/images/icons/pin16.png';
		this.baseicon.size = new GSize(16, 20);
		this.baseicon.shadow = '/images/icons/pin16s.png';
		this.baseicon.shadowSize = new GSize(36, 36);
		this.baseicon.iconAnchor = new GPoint(8, 20);
		this.baseicon.infoWindowAnchor = new GPoint(16, 0);

		this.point = new GLatLng(this.latitude, this.longitude, true);
		//this.marker = new GMarker(this.point, -this.id);
		this.marker = new GMarker(this.point, { icon:this.baseicon, zIndexProcess:this.getIndex });
		this.map.addOverlay(this.marker);

		if(this.showTip){
			this.elementTitle = domCE('span').domAC(
				domCE('img').domSA({
					src: '/images/icons/32x32_map.png',
					align: 'left',
					height: 32,
					width: 32
				})
			).domAC(
				domCE('strong').domCTN(this.distributor.name)
			);
			this.elementSubTitle = domCE('em').domSA({ className: 'op50' }).domCTN(this.name);
			this.elementBody = domCE('div').domSA({
				align: 'center'
			});

			if(this.address1 || this.address2 || this.city || this.province || this.country || this.postalcode){
				this.address = domCE('p')
				if(this.city) this.address.domAC( domCTN(this.city) );
				if(this.province) this.address.domAC( domCTN(', '+this.province) );
				this.elementBody.domAC(
					this.address
				);
			};

			this.element = domCE('div').domSA({
				className: 'tooltip-container'
			}).domAC(
				domCE('div').domSA({
					className: 'tooltip'
				}).domAC(
					this.tool_tip_head = domCE('div').domSA({
						className: 'tooltip-head'
					}).domAC(
						this.elementTitle
					).domAC(
						domCE('br')
					).domAC(
						this.elementSubTitle
					)
				).domAC(
					this.tool_tip_body = domCE('div').domSA({
						className: 'tooltip-body'
					}).domAC(
						this.elementBody
					)
				)
			);

			this.element.className = 'tooltip-container';
			this.element.style.position = 'absolute';
			this.element.style.visibility = 'hidden';

			this.map.getPane(G_MAP_FLOAT_PANE).appendChild(this.element);

			this.eventMouseOver  = this.show.bindAsEventListener(this);
			GEvent.addListener(this.marker, "mouseover", this.eventMouseOver);
			this.eventMouseOut   = this.hide.bindAsEventListener(this);
			GEvent.addListener(this.marker, "mouseout", this.eventMouseOut);

			this.eventClick  = this.clickMapMarker.bindAsEventListener(this);
			GEvent.addListener(this.marker, "click", this.eventClick);

		};

	},

	clickMapMarker: function(){
		window.location.href=lang('/en','/fr')+this.distributor.url+'#'+this.subdistributorid;
	},

	remove: function(){
		this.element.parentNode.removeChild(this.element);
	},

	redraw: function(force){
		if (!force) return;
		var markerPos = this.map.fromLatLngToDivPixel(this.marker.getPoint());
		var iconAnchor = this.marker.getIcon().iconAnchor;
		var xPos = Math.round(markerPos.x + 3);
		var yPos = markerPos.y - iconAnchor.y - this.element.clientHeight + 3;

		var tDim = this.element.getDimensions();
		var posNE = this.map.fromLatLngToDivPixel(this.map.getBounds().getNorthEast());
		if(xPos > posNE.x - tDim.width - 10) xPos -= (tDim.width + 25);
		if(yPos < posNE.y) yPos += (tDim.height + 25);

		this.element.style.top = yPos + 'px';
		this.element.style.left = xPos + 'px';
	},

	show: function(){
		this.redraw(true);
		this.element.style.visibility = 'visible';
	},

	hide: function(){
		this.element.style.visibility = 'hidden';
	},

	getIndex: function(marker, b){
		return GOverlay.getZIndex(marker.getPoint().lat());
	}
});
