var XMLFirmware =  XMLDir+'firmware.xml';

showUpdateHistory = Class.create();
Object.extend(showUpdateHistory.prototype, {
	initialize: function(elementInput, elementError, elementButton, elementOutput){
		this.elementInput = ($(elementInput) || elementInput);
		this.elementError = ($(elementError) || elementError);
		this.elementButton = ($(elementButton) || elementButton);
		this.elementOutput = ($(elementOutput) || elementOutput);
		this.regex = new RegExp("^[0-9a-f]{12}$", "i");
		this.elementButton.disable();
		this.eventKeyPress  = this.keyPress.bindAsEventListener(this);
		Event.observe(this.elementInput, "keyup", this.eventKeyPress);

		this.eventButton  = this.buttonPress.bindAsEventListener(this);
		Event.observe(this.elementButton, "mousedown", this.eventButton);

		this.currentprotocol = 'fortin';

		var fragment = window.location.toString().split('#')[1];
		if(typeof fragment != 'undefined' && fragment != ''){
			this.elementInput.value = fragment;
			if(this.check()){
				this.elementButton.enable();
				this.show();
			};
		}else if(readCookie('serial')){
			this.elementInput.value = readCookie('serial');
			if(this.check()){
				this.elementButton.enable();
				this.show();
			};
		};

	},

	keyPress: function(event){
		if(event.keyCode == Event.KEY_RETURN && this.check()){
			this.verbose = true;
			this.show(event);
		};
		if(this.check()){
			this.elementButton.enable();
		}else{
			this.elementButton.disable();
		}
	},

	buttonPress: function(event){
		this.show();
	},

	check: function(event){
		return this.regex.test(this.elementInput.value.toLowerCase());
	},

	show: function(event){

		this.elementError.domRCN();
		this.elementError.hide();

		this.elementOutput.domRCN();
		this.elementOutput.domAC(
			domCE('div').domSA({ className: 'loading' }).domAC(
				domCE('img').domSA({
					src: '/images/icons/wait.gif',
					align: 'left'
				})
			).domAC(
				domCE('span').domCTN(String.nbsp+'Loading...')
			)
		);

		this.ajax = new Ajax();
		this.ajax.url = XMLFirmware+'?serial='+this.elementInput.value;
		this.ajax.caching = true;
		this.ajax.requestXML(function(response){
			if(
				response.responseJSON == undefined
				|| response.responseJSON.product == undefined
			) return;
			this.XML = response.responseJSON.product;

			this.elementOutput.domRCN();

			if(
				(this.XML['-id'] == null || this.XML['-id'] == 0)
				&& this.XML.firmware == undefined
			){
				//alert(lang('The serial number is invalid.','Le numéro de série n\'est pas valide.'));
				this.elementError.domCHTN(lang('The serial number is invalid.','Le numéro de série n\'est pas valide.'));
				this.elementError.setStyle({ display: 'block' });
				return;
			};

			createCookie('serial', this.elementInput.value);

			this.elementOutput.domAC(
				this.elementInfo = domCE('div').domSA({ className: 'grid_8 alpha omega sep-before' })
			).domAC(
				this.elementUpdates = domCE('div').domSA({ className: 'grid_8 alpha omega sep-before' })
			).domAC(
				domCE('div').domSA({ className: 'clear' })
			);

			this.preload = this.XML.preload;
			this.currentversion = this.preload['-version'];
			this.currentprotocol = this.preload['-protocol_rs232'];

			//updates
			if(typeof this.XML.updates == 'undefined'){
				this.updates = false;
			}else{
				this.updates = (typeof this.XML.updates.update.length == 'undefined')
					? [this.XML.updates.update]
					: this.XML.updates.update;

				//forward order
				this.updates.sort(function(a,b){
					return ( a['-timestamp'] > b['-timestamp'] ) ? 1 : -1;
				});
				this.updates.each(function(update, index){
					if(this.currentversion == update['-version']){
						update.type = 'rewrite';
					}else if(isCompat('0.0'+update['-version'], '0.0'+this.currentversion)){
						update.type = 'upgrade';
					}else{
						update.type = 'downgrade';
					}
					this.currentversion = ((update['-success'] == 1) ? update['-version'] : this.currentversion );
					this.currentprotocol = ((update['-success'] == 1) ? update['-protocol_rs232'] : this.currentprotocol );
				}.bind(this));

				//forward order
				this.updates.each(function(update, index){
					this.currentversion = ((update['-success'] == 1) ? update['-version'] : '0.0' );
					this.currentprotocol = ((update['-success'] == 1) ? update['-protocol_rs232'] : 'unknown' );
				});

				//reverse order
				this.updates.reverse();
				this.updates.each(function(update, index){
					this.elementUpdates.domAC(
						domCE('div').domSA({
							className: 'firmwareupdate '+((update['-success'] == 1) ? 'success' : 'error' )+' m15-top'
						}).domAC(
							domCE('div').domSA({ className: 'grid_1 alpha version shadow' }).domAC(
								domCE('strong').domCTN(update['-version'])
							).domAC(
								domCE('p').domSA({ className: 'protocol' }).domCTN(update['-protocol_rs232'])
							)
						).domAC(
							domCE('div').domSA({ className: 'grid_2 omega date' }).domCTN(update['-datetime'])
						).domAC(
							domCE('div').domSA({ className: 'grid_5 text' }).domAC(
								function(){
									switch(update.type){
										case 'upgrade':
											return domCTN((update['-success'] == 1) ? lang('Firmware upgrade successful','Logiciel mis à jour avec succès') : lang('Firmware upgrade failed','Échec à la mise à jour du logiciel'));
											break;
										case 'downgrade':
											return domCTN((update['-success'] == 1) ? lang('Firmware downgrade successful','Logiciel mis à jour avec succès') : lang('Firmware downgrade failed','Échec à la mise à jour du logiciel'));
											break;
										case 'rewrite':
											return domCTN((update['-success'] == 1) ? lang('Firmware rewrite successful','Écriture du Logiciel réussie') : lang('Firmware rewrite failed','Échec à l\'écriture du logiciel '));
											break;
									}
								}
							)
						).domAC(
							domCE('div').domSA({ className: 'clear' })
						)
					);
				}.bind(this));
			};

			//preload
			this.elementUpdates.domAC(
				domCE('div').domSA({
					className: 'firmwareupdate preload m15-top'
				}).domAC(
					domCE('div').domSA({ className: 'grid_1 alpha version shadow' }).domAC(
						domCE('strong').domCTN(this.preload['-version'])
					).domAC(
						domCE('p').domSA({ className: 'protocol' }).domCTN(this.preload['-protocol_rs232'])
					)
				).domAC(
					domCE('div').domSA({ className: 'grid_2 omega date' }).domCTN(this.preload['-datetime'])
				).domAC(
					domCE('div').domSA({ className: 'grid_5 text' }).domCTN(lang('Firmware preloaded', 'Logiciel préchargé'))
				).domAC(
					domCE('div').domSA({ className: 'clear' })
				)
			);


			//product
			this.elementInfo.domAC(
				domCE('h2').domAC(
					domCE('sup').domCTN(this.XML.partnumber)
				).domAC(
					domCE('a').domSA({ name: this.elementInput.value }).domCHTN(String.nbsp)
				)
			).domAC(
				domCE('p').domCHTN('Service No: <strong>'+this.elementInput.value.toUpperCase()+'</strong>')
			).domAC(
				domCE('p').domCHTN(lang('Hardware version','Version matériel')+': <strong>'+this.XML.hardware['-version']+'</strong>')
/*
			).domAC(
				domCE('p').domCHTN(lang('Preloaded firmware','Logiciel')+': '+this.XML.preload['-version'])
*/
			).domAC(
				domCE('p').domCHTN(lang('Firmware version','Verison logiciel')+': <strong>'+this.currentversion+'</strong>')
			).domAC(
				domCE('p').domCHTN('Preload date: <strong>'+this.XML.preload['-date']+'</strong>')
			).domAC(
				domCE('p').domCHTN(lang('RS232 protocol','Protocol RS232')+': <strong>'+this.currentprotocol.toUpperCase()+'</strong>')
			);

			window.location.href='#'+this.elementInput.value;

		}.bind(this));
	}

});

checkSerial = function(elementSerial, elementButton){
	var re = /^[0-9a-f]{12}$/;
	if(re.test(elementSerial.value.toLowerCase()) == false){
		elementButton.disable();
	}else{
		elementButton.enable();
	};
};

isCompat = function(isVersion, reqVersion){
	if(reqVersion == '0.0.0.0' || reqVersion == '') return true;
	if(isVersion == '0.0.0.0' || isVersion == '') return false;
	var iVersion = isVersion.split('.');
	var rVersion = reqVersion.split('.');
	for(var i=0; i<=3; i++){
		if(parseInt(iVersion[i]) > parseInt(rVersion[i])){
			return true;
		}else if(parseInt(iVersion[i]) < parseInt(rVersion[i])) {
			return false;
		};
	};
	return true;
};


registerDatalinkProduct = function (element, datalinkproductid){
	try{
		element.onmouseover = function(){ };
		element.domRA('onMouseOver');
	}catch(e){ };
	new DatalinkProduct(element, datalinkproductid);
};

DatalinkProduct = Class.create();
Object.extend(DatalinkProduct.prototype, {

	initialize: function(element, datalinkproductid){
		this.element = element;
		this.datalinkproductid = datalinkproductid;
		this.focus = true;

		this.eventMouseOver  = this.over.bindAsEventListener(this);
		Event.observe(this.element, "mouseover", this.eventMouseOver);
		this.eventMouseOut   = this.out.bindAsEventListener(this);
		Event.observe(this.element, "mouseout", this.eventMouseOut);

		this.ajax = new Ajax();
		this.ajax.url = XMLDatalinkProduct+'?datalinkproductid='+this.datalinkproductid;
		this.ajax.caching = true;
		this.ajax.requestXML(function(response){
			var product = response.responseJSON.datalink.products.product;

			this.tooltip = new Tooltip();
			this.tooltip.initTooltip();
			this.tooltip.registerTooltipElement(this.element);
			this.element.setStyle('cursor:help;');
			this.tooltip.registerTooltipTitle(
				domCE('div').domAC(
					domCE('h4').setStyle({ width: '235px' }).domSA({
						className: 'tooltiptitle'
					}).domCTN(product.name)
				)
			);
			this.tooltip.registerTooltipBody(
				domCE('div').setStyle({
					clear: 'both'
				}).domSA({
					align: 'center'
				}).domAC(
					domCE('img').domSA({
						src: '/images/140x140_datalink_'+product.status+'.png',
						height: 140,
						width: 140
					}).setStyle({
						align: 'center',
						background: 'url('+product.image+') no-repeat'
					})
				).domAC(
					domCE('p').setStyle({
						width: '235px',
						textAlign: 'left'
					}).domSA({
						className: 'tooltipbody'
					}).domAC(
						domCE('p').domCHTN(lang(product.description_en, product.description_fr)+String.nbsp)
					)
				)
			);

			if(this.focus) this.tooltip.showTooltip();

			Event.stopObserving(this.element, "mouseover", this.eventMouseOver);
			Event.stopObserving(this.element, "mouseout", this.eventMouseOut);

		}.bind(this));
	},

	over: function(event){
		this.focus = true;
	},

	out: function(event){
		this.focus = false;
	}

});

registerDatalinkFeature = function (element, datalinkfeatureid, datalinkmanufacturername, datalinkproductname){
	try{
		element.onmouseover = function(){ };
		element.domRA('onMouseOver');
	}catch(e){ };
	new DatalinkFeature(element, datalinkfeatureid, datalinkmanufacturername, datalinkproductname);
};

DatalinkFeature = Class.create();
Object.extend(DatalinkFeature.prototype, {

	initialize: function(element, datalinkfeatureid, datalinkmanufacturername, datalinkproductname){
		this.element = element;
		this.datalinkfeatureid = datalinkfeatureid;
		this.datalinkmanufacturername = datalinkmanufacturername;
		this.datalinkproductname = datalinkproductname;
		this.focus = true;

		this.eventMouseOver  = this.over.bindAsEventListener(this);
		Event.observe(this.element, "mouseover", this.eventMouseOver);
		this.eventMouseOut   = this.out.bindAsEventListener(this);
		Event.observe(this.element, "mouseout", this.eventMouseOut);

		this.ajax = new Ajax();
		this.ajax.url = XMLDatalinkFeature+'?datalinkfeatureid='+this.datalinkfeatureid;
		this.ajax.caching = true;
		this.ajax.requestXML(function(response){
			var feature = response.responseJSON.datalink.features.feature;

			if(
				typeof product != 'undefined'
				&& typeof product.partnumber != 'undefined'
			){
				switch(lang('en','fr')){
					case 'en':
						if(typeof feature.description_en == 'undefined' || feature.description_en.length == 0) break;
						feature.description_en = feature.description_en.replace(/bypass or interface module/g, product.partnumber);
						feature.description_en = feature.description_en.replace(/interface module/g, product.partnumber);
						break;
					case 'fr':
						if(typeof feature.description_fr == 'undefined' || feature.description_fr.length == 0) break;
						feature.description_fr = feature.description_fr.replace(/module d'interface/g, product.partnumber);
						break;
				};
			};

			if(typeof this.datalinkproductname != 'undefined'){
				switch(lang('en','fr')){
					case 'en':
						if(typeof feature.description_en == 'undefined' || feature.description_en.length == 0) break;
						feature.description_en = feature.description_en.replace(/remote-starter/g, this.datalinkproductname);
						break;
					case 'fr':
						if(typeof feature.description_fr == 'undefined' || feature.description_fr.length == 0) break;
						feature.description_fr = feature.description_fr.replace(/démarreur à distance/g, this.datalinkproductname);
						break;
				};
			};

			this.tooltip = new Tooltip();
			this.tooltip.initTooltip();
			this.tooltip.registerTooltipElement(this.element);
			this.element.setStyle('cursor:help;');
			this.tooltip.registerTooltipTitle(
				domCE('div').domAC(
					domCE('h4').setStyle({ width: '235px' }).domSA({
						className: 'tooltiptitle'
					}).domCTN(lang(feature.name_en, feature.name_fr))
				)
			);
			this.tooltip.registerTooltipBody(
				domCE('div').domAC(
					domCE('p').setStyle({width: '235px'}).domSA({
						className: 'tooltipbody'
					}).domAC(
						domCE('p').domCHTN(lang(feature.description_en, feature.description_fr)+String.nbsp)
					)
				)
			);

			if(this.focus) this.tooltip.showTooltip();

			Event.stopObserving(this.element, "mouseover", this.eventMouseOver);
			Event.stopObserving(this.element, "mouseout", this.eventMouseOut);

		}.bind(this));
	},

	over: function(event){
		this.focus = true;
	},

	out: function(event){
		this.focus = false;
	}

});



var onPVCompatEvent = new YAHOO.util.CustomEvent("PVCompat");

ProductVehicleCompat = Class.create();
Object.extend(ProductVehicleCompat.prototype, {

	initialize: function(vehicle, product, elementCell, elementLink){
		this.vehicle = vehicle || { makeid:0, modelid:0, vehicleid:0 };
		this.product = product || { productid:0 };
		this.elementCell = elementCell || false;
		this.elementLink = elementLink || false;

		this.loaded = false;
		this.shown = false;
		this.features = new Array();
		this.firmwares = new Array();
		this.files = new Array();
		this.solutions = new Array();

		onPVCompatEvent.subscribe(this.eventDispatch, this, true);

		this.eventMouseClick   = this.click.bindAsEventListener(this);
		Event.observe(this.elementCell, "mousedown", this.eventMouseClick);
		Event.observe(this.elementCell, "touchstart", this.eventMouseClick);

		this.eventMouseOver   = this.over.bindAsEventListener(this);
		Event.observe(this.elementCell, "mouseover", this.eventMouseOver);

		this.eventMouseOut   = this.out.bindAsEventListener(this);
		Event.observe(this.elementCell, "mouseout", this.eventMouseOut);
		Event.observe(this.elementCell, "touchend", this.eventMouseClick);
	},

	eventDispatch: function(type, args){
		if(args[1] !== this){
			this.hide();
		};
	},

	over: function(event){
		if(this.shown){
			$(this.elementLink.firstChild).domSA({
				src: '/images/icons/24x24_close.png'
			});
		}else{
			$(this.elementLink.firstChild).domSA({
				src: '/images/icons/24x24_info.png'
			});
		};
	},

	out: function(event){
		if(this.shown){
			$(this.elementLink.firstChild).domSA({
				src: '/images/icons/24x24_info.png'
			});
		}else{
			$(this.elementLink.firstChild).domSA({
				src: '/images/icons/24x24_blackdot.png'
			});
		};
	},

	click: function(event){
		if(!this.shown){
			this.show();
		}else{
			this.hide();
		}
	},

	show: function(event){
		if(this.shown) return;
		$(this.elementCell).addClassName('show');
		onPVCompatEvent.fire(event, this);
		if(!this.loaded){
			this.load(this.show);
			return;
		};
		this.elementRowInfo.show();
		this.compat.scroll();
		this.elementDivContainer.setStyle({ overflow:'hidden' });
		this.showanim = new YAHOO.util.Anim(this.elementDivContainer, {
			height: { from: 0, to: this.elementDiv.getDimensions().height },
			opacity: { from: 0 , to: 1 }
		}, 0.50, YAHOO.util.Easing.easeInStrong);
		this.showanim.onComplete.subscribe(function(){
			this.elementDivContainer.style.removeProperty('overflow');
			this.elementDivContainer.style.removeProperty('height');
			$(this.elementLink.firstChild).domSA({
				src: '/images/icons/24x24_info.png'
			});
			window.location.href='#'+this.vehicle.makeid+','+this.vehicle.modelid+','+this.vehicle.vehicleid;
			this.shown = true;
		}.bind(this));
		this.showanim.animate();
	},

	hide: function(event){
		if(!this.loaded) return;
		if(!this.shown) return;
		this.elementDivContainer.setStyle({ overflow:'hidden' });
		this.hideanim = new YAHOO.util.Anim(this.elementDivContainer, {
			height: { to: 0, from: this.elementDiv.getDimensions().height },
			opacity: { from: 1 , to: 0 }
		}, 0.50, YAHOO.util.Easing.easeOutStrong);
		this.hideanim.onComplete.subscribe(function(){
			this.elementDivContainer.style.removeProperty('overflow');
			this.elementDivContainer.style.removeProperty('height');
			$(this.elementCell).removeClassName('show');
			this.elementRowInfo.hide();
			$(this.elementLink.firstChild).domSA({
				src: '/images/icons/24x24_blackdot.png'
			});
			this.shown = false;
		}.bind(this));
		this.hideanim.animate();

	},

	load: function(onload){
		this.onload = ( onload || function(){} );
		this.elementRow = $(this.elementCell.parentNode);
		this.colSpan = $(this.elementRow.childNodes).length;
		this.elementTbody = $(this.elementRow.parentNode);
		this.elementTbody.domIA(
			this.elementRowInfo = domCE('tr').domSA({
				className: 'i noprint'
			}).domAC(
				domCE('td').domSA({
					className: 'i',
					colSpan: this.colSpan
				}).domAC(
					this.elementDivContainer = domCE('div').domSA({
						className: 'grid_12 alpha omega'
					}).domAC(
						this.elementDiv = domCE('div').setStyle({
							padding:'0px 0px'
						}).domAC(
							domCE('span').domSA({
								className: 'm15'
							}).setStyle({
								display: 'block',
								textAlign: 'center'
							}).domAC(
								this.icon = domCE('img').domSA({
									src: '/images/icons/wait.gif',
									height: 16,
									width: 16
								})
							).domAC(
								domCTN(' Loading Solution...')
							)
						)
					)
				)
			),
			this.elementRow
		);

		this.compat = new Compat(this.elementDiv, {
			productid: this.product.productid,
			vehicleid: this.vehicle.vehicleid,
			modelid: this.vehicle.modelid,
			makeid: this.vehicle.makeid,
			onload: (function(XML){
				$(this.compat.elementTHeadRow.firstChild).domSA({
					className: 'focus'
				}).domAC(
					domCE('div').domAC(
						domCE('img').setStyle({
							margin:'0px 15px'
						}).domSA({
							src:(
								(XML.vehicle['-image_front'] != undefined)
								? '/images/gen/vehicle/'+XML.vehicle['-image_front']+'-100x100.jpg'
								: '/images/gen/make/'+XML.vehicle['-makeid']+'.png'
							),
							width:100,
							height:100,
							align:'left'
						})
					).domAC(
						domCE('h2').domAC(
							domCE('a').domSA({
								href: lang('/en/', '/fr/')+'vehicles/'+XML.vehicle['-make'].cleanurl()+'/',
								className: 'hilight arrow'
							}).domCTN(XML.vehicle['-make'])
						).domAC(
							domCE('br')
						).domAC(
							domCE('a').domSA({
								href: lang('/en/', '/fr/')+'vehicles/'+XML.vehicle['-make'].cleanurl()+'/'+XML.vehicle['-model'].cleanurl()+'/',
								className: 'hilight arrow'
							}).domCTN(XML.vehicle['-model'])
						).domAC(
							domCE('br')
						).domAC(
							domCE('a').domSA({
								href: lang('/en/', '/fr/')+'vehicles/'+XML.vehicle['-make'].cleanurl()+'/'+XML.vehicle['-model'].cleanurl()+'/'+XML.vehicle['-year']+((XML.vehicle['-trim'] != undefined)?'-'+XML.vehicle['-trim'].cleanurl():'')+'/',
								className: 'hilight arrow'
							}).domCTN(XML.vehicle['-year']+(
								(XML.vehicle['-trim'] != undefined)
								? ' '+XML.vehicle['-trim']
								: ''
							))
						)
					)
				);
				this.loaded = true;
				this.onload();
			}.bind(this))
		});
	}

});

