if(location.host != "jeep.co.uk" ) {

                document.domain = "jeep.co.uk";

}


/*	Script: jsonp.js
		Creates a Json request using a script tag include and handles the callbacks for you.
		
		Dependencies:
		Mootools - <Moo.js>, <Array.js>, <String.js>, <Function.js>, <Utility.js>, <Element.js>, <Common.js>, <Assets.js>
		
		Author:
		Aaron Newton <aaron [dot] newton [at] cnet [dot] com>
		
		Class: JsonP
		Creates a Json request using a script tag include and handles the callbacks for you.
		
		Arguments:
		url - the url to get the json data
		options - an object with key/value options
		
		Options:
		onComplete - (optional) function to execute when the data returns; it will be passed the data and the 
			instance of jsonp that requested it.
		callBackKey - (string) the key in the url that the server uses to wrap the Json results. 
				So, for example, if you used "callBackKey: 'callback'" then the server is expecting
				something like http://..../?q=search+term&callback=myFunction
				defaults to "callback". This must be defined correctly.
		queryString - (string, optional) additional query string values to append to the url
		data - (object, optional) additional key/value data to append to the url
		
	*/
var JsonP = new Class({
	options: {
		onComplete: Class.empty,
		callBackKey: "callback",
		queryString: "",
		data: {},
		timeout: 5000,
		retries: 0
	},
	initialize: function(url, options){
		this.setOptions(options);
		this.url = this.makeUrl(url).url;
		this.fired = false;
		this.scripts = [];
		this.requests = 0;
		this.triesRemaining = [];
	},
/*	Property: request
		Executes the Json request.
	*/
	request: function(url, requestIndex){
		var u = this.makeUrl(url);
		if(!$chk(requestIndex)) {
			requestIndex = this.requests;
			this.requests++;
		}
		if(!$chk(this.triesRemaining[requestIndex])) this.triesRemaining[requestIndex] = this.options.retries;
		var remaining = this.triesRemaining[requestIndex]; //saving bytes

		var dl = (window.ie)?50:0; //for some reason, IE needs a moment here...
		(function(){
			var script = new Asset.javascript(u.url, {id: 'jsonp_'+u.index+'_'+requestIndex});
			this.fired = true;
			this.addEvent('onComplete', function(){
				try {script.remove();}catch(e){}
			}.bind(this));

			if(remaining) {
				(function(){
					this.triesRemaining[requestIndex] = remaining - 1;
					if(script.getParent() && remaining) {
						script.remove();
						this.request(url, requestIndex);
					}
				}).delay(this.options.timeout, this);
			}
		}.bind(this)).delay(dl);
		return this;
	},
	makeUrl: function(url){
		var index = (JsonP.requestors.contains(this))?
								JsonP.requestors.indexOf(this):
								JsonP.requestors.push(this) - 1;
		if(url) {
			var separator = (url.test('\\?'))?'&':'?';
			var jurl = url + separator + this.options.callBackKey + "=JsonP.requestors[" +
				index+"].handleResults";
			if(this.options.queryString) jurl += "&"+this.options.queryString;
			jurl += "&"+Object.toQueryString(this.options.data);
		} else var jurl = this.url;
		return {url: jurl, index: index};
	},
	handleResults: function(data){;
		this.fireEvent('onComplete', [data, this]);
	}
});
JsonP.requestors = [];
JsonP.implement(new Options);
JsonP.implement(new Events);



var jeep = {

	modelID: null,
	modelDirectory: null,

	init: function() {

		jeep.getModel();
		jeep.registerPostcodeValidation();

		if(jeep.modelID != null) {
			
			// mootools domready event is triggered too early by ie
			// so our element may not actually be in the DOM at this stage
			// so defer until page load event
			if(window.ie) {
				window.addEvent('load', function() {
	                    		jeep.JSON.getModelPrice(jeep.modelID);
                        	});
			}
			else {
                        	jeep.JSON.getModelPrice(jeep.modelID);
			}
		}
		else {
			// if we have flyout divs
			// we're on the homepage so make call for
			// flyout price population
			if($ES('div.flyout') != 0) {

				jeep.JSON.getFlyoutPrices();
			}

		}

		// if offerPanel exists on page
		// populate it with offers
		if($('offerPanel')) {
			
			// if we have a model ID then use this
			// otherwise use the homepage model ID
			jeep.JSON.getModelOffers((jeep.modelID != null) ? jeep.modelID : jeep.config.homepageModelID);
		}


		jeep.featuresOverlay.init();
		jeep.eBrochure.init();
	},

	// redirect to dealer search
	// using postcode specified 
	searchDealers: function(postcode) { 
		
		var dealerSearchURL = 'http://' + location.host + '/dealer/index.html';

		if(postcode)
			dealerSearchURL += '?postcode=' + postcode;

		window.location = dealerSearchURL;
	},

	getModel: function() {

		var url = location.pathname.toLowerCase();

		if(url.indexOf('wrangler') != -1) {
			jeep.modelID = 2;
			jeep.modelDirectory = 'wrangler';
		}
		else if(url.indexOf('grandcherokee') != -1) {
			jeep.modelID = 18;
			jeep.modelDirectory = 'grandcherokee';
		}
		else if(url.indexOf('cherokee') != -1) {
			jeep.modelID = 44;
			jeep.modelDirectory = 'cherokee';
		}
		else if(url.indexOf('commander') != -1) {
			jeep.modelID = 32;
			jeep.modelDirectory = 'commander';
		}
		else if(url.indexOf('compass') != -1) {
			jeep.modelID = 35;
			jeep.modelDirectory = 'compass';
		}
		else if(url.indexOf('patriot') != -1) {
			jeep.modelID = 37;
			jeep.modelDirectory = 'patriot';
		}
	},

	// redirect to dealer search
	// using email specified 
	registerEmail: function(email) { 
		
		var newsletterURL = 'http://' + location.host + '/newsletter/index.html';

		if(email)
			newsletterURL += '?email=' + email;

		window.location = newsletterURL;
	},

	registerPostcodeValidation: function() {

		if($E('form#form_dealer_find')) {

			$E('form#form_dealer_find a.form_button').addEvent('click', function(event) {

				event.preventDefault();
    
				var postcodeRegEx = /[A-Z]{1,2}[0-9]{1,2} ?[0-9][A-Z]{2}/i;
				$postcode = $E('form#form_dealer_find input[name=postcode]').value;	

		        	if(!postcodeRegEx.test($postcode)) {
		        		alert("Please enter a full and valid UK postcode");
		        	}
				else {
					jeep.searchDealers(document.form_dealer_find.postcode.value);
				}
			});
		}
	}
}

jeep.config = {

	servicesDomain: (location.host == "test.jeep.co.uk") ? "http://jeep.services.cdj.sdev.net" : "http://services.jeep.co.uk",

	// homepage has it's own modelID. this is used for sourcing homepage offers
	homepageModelID: 20,

	disclaimerEntity: "&dagger;"

}

jeep.config.JSON = {
    eBrochurePopup: jeep.config.servicesDomain + "/providers/eBrochurePopup.ashx",
    modelPrice: jeep.config.servicesDomain + "/providers/startingPrice.ashx",
    modelOffers: jeep.config.servicesDomain + "/providers/offers.ashx"
}


jeep.pageLoad = {

	// method populates iframe named by iframeName variable
	// with the URL specified in the iframeSrc variable.

	// querystring variables specifed in the qsTransfer array
	// will be pulled from the page and added to iframeSrc
	loadIframe: function(iframeName, iframeSrc, qsTransfer) {
		
		if( $(iframeName) && iframeSrc) {

			var iframeQS = '';

			// loop through qsTransfer array to build querystring
			for(var i = 0; i < qsTransfer.length; i++) {
				
				if(qsTransfer[i]) {
					var sourceKey = qsTransfer[i]['sourceKey'];
					var qsValue = request.queryString(sourceKey);
					var targetKey = qsTransfer[i]['targetKey'];

					if(qsValue)
					{
						if(iframeQS != '')
							iframeQS += "&";	

						iframeQS += targetKey + "=" + qsValue;
					}
				}
			}

			if(iframeQS != '') {

				$(iframeName).src = iframeSrc + "?" + iframeQS;
			}
			else {

				$(iframeName).src = iframeSrc;
			}
			
			// finally show the iframe
			$(iframeName).style.display = '';

			return true;		
		}	
		
		return false;
	}
}

jeep.JSON = {

	getModelPrice: function(modelID) {

		if($('modelStartingPrice')) { 
			
			// make JSON request for model prices
			new JsonP(jeep.config.JSON.modelPrice, {

        			queryString: 'mid=' + modelID,
				onComplete: function(data) { jeep.JSON.callback.getModelPrice(data) }

			}).request();
		}
	},

	getFlyoutPrices: function() {

		// make JSON request for model prices
		new JsonP(jeep.config.JSON.modelPrice, {

			onComplete: function(data) { jeep.JSON.callback.getFlyoutPrices(data) }

		}).request();
	},

	getModelOffers: function(modelID) {

		if($('offerPanel')) { 
			
			// make JSON request for offer info
			new JsonP(jeep.config.JSON.modelOffers, {

        			queryString: 'mid=' + modelID,
				onComplete: function(data) { jeep.JSON.callback.getModelOffers(data) }

			}).request();
		}
	}
}

// handles JSON request callbacks
jeep.JSON.callback = {

	getModelPrice: function(price) {

		if(!price["offerPrice"] && !price["startingPrice"])
			return;

    		priceHTML = "";

    		// if offer price is less than starting price
    		// then display offer price along with disclaimer HTML entity
    		if(price["offerPrice"] < price["startingPrice"]) {
        		priceHTML = formatPrice(price["offerPrice"]) + jeep.config.disclaimerEntity;
    		}
    		else {
        		priceHTML = formatPrice(price["startingPrice"]);
    		}

    		// populate price
    		$('modelStartingPrice').innerHTML += priceHTML;

    		// finally show price element
   		$('modelStartingPrice').style.display = '';		
	},

	getFlyoutPrices: function(result) {

		if(result["models"]) {
			
			result["models"].each(function(model) {

				priceHTML = "";

				if(model["modelId"] && model["offerPrice"] && model["startingPrice"]) {
					
					// if offer price is less than starting price
    					// then display offer price along with disclaimer HTML entity
    					if(model["offerPrice"] < model["startingPrice"]) {
        					priceHTML = formatPrice(model["offerPrice"]) + jeep.config.disclaimerEntity;
    					}
    					else {
        					priceHTML = formatPrice(model["startingPrice"]);
    					}

					modelTag = model["modelName"].toLowerCase().replace(' ','_');
					priceElement = 'div#flyout-' + modelTag + ' div.flyoutMSRP span';

					if($E(priceElement)) {
						
						// populate price and show element
						$E(priceElement).innerHTML = "Starting From: " + priceHTML + " OTR";
						$E(priceElement).style.display = '';	

					}	
				}

			});
		}
	},

	getModelOffers: function(result) {

		offerHTML = "";

		if(result["offers"]) {

			result["offers"].each(function(offer) {
			
				if(offer["url"] && offer["id"])
				{
					// target new window if the link is to an external site
					if( offer["url"].indexOf('.pdf') != -1 || ((offer["url"].indexOf('http://') != -1 || offer["url"].indexOf('https://') != -1) 
						&& offer["url"].indexOf('chrysler.co.uk') == -1
						&& offer["url"].indexOf('dodge.co.uk') == -1
						&& offer["url"].indexOf('jeep.co.uk') == -1))			
					{
						target = "_blank";
					}
					else
					{
						target = "_self";
					}
					
					offerHTML += "<a href=\"" + offer["url"] + "\" target=\"" + target + "\"><img src=\"" + jeep.config.servicesDomain + "/offers/images/" + offer["id"] + ".gif\"></a>";			
				}
			});

			// if we have some content, show offer panel
			if(offerHTML != "") {
				$('offerPanel').innerHTML = offerHTML;
				$('offerPanel').style.display = '';
			}
		}
	}
}

// handles eBrochure popup functionality
jeep.eBrochure = {

	cookied: false,
	postcode: null,
	isActive: false,

	init: function() {
	
		var keyCode;

		// proceed to load and setup eBrochure popup
		// only if we are on a model-specific page
		// and the ebrochure link exists on the page
		if(jeep.modelID != null && $('ebrochure'))
			jeep.eBrochure.requestPopupHTML(jeep.modelID);	

		document.addEvent('keypress', function(e){
			if ( window.event ){
				keyCode = window.event.keyCode;
			}else{
				keyCode = e.keyCode ? e.keyCode : e.which ? e.which : e.charCode;
			}
			// Hide DropBox on Escape key
			if( keyCode == 27 ) if( jeep.eBrochure.isActive ) jeep.eBrochure.closePopup();
		}.bind(this));	
	},
	
	// pulls in eBrochure Popup HTML
	requestPopupHTML: function(modelID) {

		new JsonP(jeep.config.JSON.eBrochurePopup, {
        		queryString: 'mid=' + modelID,
			onComplete: function(data) { jeep.eBrochure.requestCallback(data) }
		}).request();

	},

	validateForm: function() {

		var bError = false;
        	var sMessage = "Please complete the following fields:\r\n";

        	if($('firstname').value == "") {
        		bError = true;
        		sMessage += "First name\r\n";
        	}

	        if($('surname').value == "") {
        		bError = true;
		        sMessage += "Surname\r\n";
        	}

	        if($('email').value == "") {
		        bError = true;
		        sMessage += "Email address\r\n";
        	}

	        if($('postcode').value == "") {
		        bError = true;
		        sMessage += "Postcode\r\n";
        	}

	        if(bError) {
	        	alert(sMessage);
			return false;
		}
        	else {
			jeep.eBrochure.formSubmitted();
          		return true;
        	}
	},

	formSubmitted: function() {

		jeep.eBrochure.cookied = true;
		jeep.eBrochure.postcode = $('postcode').value;
		jeep.eBrochure.showThanks();
	},

	// handles callback for requestPopupHTML method
	requestCallback: function(HTML) {
            		
		// create new popup element to hold popup HTML	
		var popupElement = new Element('div', {   'id': 'ebrochure_popover',
                				'styles': {
                            				'position': 'absolute',
                            				'top': '100px',
                            				'left': '518px',
                            				'z-index': 9999
                            			}
            	});

            	popupElement.setOpacity(0);
            
            	popupElement.innerHTML = HTML;
            	$('wrapper').adopt(popupElement);

		
		// add click handler for close button

		$('ebrochure_closepopup').addEvent('click', function() {
			jeep.eBrochure.closePopup();
		});


		// add change handlers for derivatives radio buttons

		$$("input[name=product]").addEvent('change', function() {

			// if postcode is set then the user
			// has already completed the form
			if(jeep.eBrochure.cookied) 
				jeep.eBrochure.showDownloadAnother();
		});	


		// finally add click handler on ebrochure link

		$('ebrochure').addEvent('click', function() {
			jeep.eBrochure.showHidePopup();
		});
	},

	// toggles popup box
	showHidePopup: function() {

		var fXPopover = new Fx.Styles($('ebrochure_popover'), {duration:500, wait:false});

		if(!jeep.eBrochure.isActive) {

			$('ebrochure').addClass('features_menu_on');

			fXPopover.element.setOpacity(0);
			fXPopover.element.style.display = '';

    			fXPopover.start({'opacity': [0, 1]}).chain(function() {
				jeep.eBrochure.isActive = true;
			});
		}
		else {
			jeep.eBrochure.closePopup();
		}
	},

	// replaces form div with thanks div
	showThanks: function() {

		var fxForm = new Fx.Styles($('diveBrochureForm'), {duration:500, wait:false});
		var fxThanks = new Fx.Styles($('diveBrochureThanks'), {duration:500, wait:false});

    		fxForm.start({'opacity': [1, 0]}).chain(function() {

			fxForm.element.style.display = 'none';

			fxThanks.element.setOpacity(0);
			fxThanks.element.style.display = '';

			fxThanks.start({'opacity': [0, 1]});
		});
	},

	// fades out popup box
	closePopup: function() {

		var fxPopover = new Fx.Styles($('ebrochure_popover'), {duration:500, wait:false});

		$('ebrochure').removeClass('features_menu_on');

		if(jeep.eBrochure.isActive) {

			fxPopover.start({'opacity': [1, 0]}).chain(function() {
		
				fxPopover.element.style.display = 'none';
				jeep.eBrochure.isActive = false;
			});
		}
	},

	// replaces form and thanks page
	// 'download another' div
	showDownloadAnother: function() {
		
		jeep.eBrochure.cookied = true;

		$('diveBrochureForm').style.display = 'none';
		$('diveBrochureThanks').style.display = 'none';
		$('divDownloadAnother').style.display = '';

		$('ebrochure_derivative').innerHTML = jeep.eBrochure.getLabelForSelectedProduct();

		$('ebrochure_downloadlink').href = jeep.eBrochure.buildBrochureLink();

	},

	getSelectedProductID: function() {

		var ID = 0;

		$$("input[name=product]").each(function(item) {
			
			if(item.checked) {
				ID = item.value;
		    }
		});	

		return ID;
	},

	// returns the label for the selected product
	getLabelForSelectedProduct: function() {
		
		return $$("label[for=prod" + jeep.eBrochure.getSelectedProductID() + "]")[0].innerHTML;
	},

	buildBrochureLink: function() {
	
		var link;

		if($('ebrochure_downloadlink').href.indexOf("?") == -1) {
			link = $('ebrochure_downloadlink').href += "?productId=" + jeep.eBrochure.getSelectedProductID() + "&pc=" + jeep.eBrochure.postcode;		
		}
		else {
			var qsPos = $('ebrochure_downloadlink').href.indexOf("?");
			
			link = $('ebrochure_downloadlink').href.substring(0,qsPos) + "?productId=" + jeep.eBrochure.getSelectedProductID() + "&pc=" + jeep.eBrochure.postcode;

		}

		return link;
	}
}

jeep.featuresOverlay = {

	init: function() {
	
		if(jeep.modelID != null && $('feature_wrapper') && $E('div.features_menu_container') && $E('div.features_menu_pos')) {
   
    			// calculate margin correction for feature box
    			// this is the correction from 'Features' navigation link position in order
    			// for the feature box to be positioned against the right of the wrapper
   			var fbWidth = $('feature_wrapper').getSize().size.x;    // feature box width
    			var wrapperWidth = $('wrapper').getSize().size.x;       // wrapper width
    			var linkLeftPosition = $('features').getPosition().x - $('wrapper').getPosition().x;    // indentation of features link inside wrapper
    			var fbTargetLeft = wrapperWidth - fbWidth;    // where we want the feature box in relation to wrapper boundary
    			var marginCorrection  = linkLeftPosition - fbTargetLeft;    // the distance we'll need to shift the feature box

    			// hide feature box while we move it
    			$('feature_wrapper').style.display = "none";
    			$('feature_wrapper').style.left = "";
    			$('feature_wrapper').style.top = "";
    			$('feature_wrapper').style.position = "";

    			// first child of div with class features_menu_pos is a div created by MooTools fx.slide to hold sliding content
    			// adjust position of the features box using the marginCorrection and set the correct width for the sliding holder
    			var slideHolder = $E('div.features_menu_pos').getChildren()[0];
    			slideHolder.style.margin = "0 0 0 -" + marginCorrection + "px";
    			slideHolder.style.width = fbWidth + "px";
			slideHolder.style.position = "absolute";

    			// replace default interwoven navigation with feature box
    			$E('div.features_menu_container').innerHTML = '';
    			$E('div.features_menu_container').adopt($('feature_wrapper'));

    			// remove classname as it is affects feature box styles
    			$E('div.features_menu_container').removeClass('features_menu_container');

    			// feature box in place, unhide ready for sliding into view
    			$('feature_wrapper').style.display = "";

			jeep.featuresOverlay.configureLinks();
		}

	},

	configureLinks: function() {

		// array defines which feature box links should be hidden on a per model basis
		var linkExclusion = new Array (
				{"linkID": "ftlink_exterior-overview", "excludeModels": []}, 
				{"linkID": "ftlink_exterior-styling", "excludeModels": []},
                                {"linkID": "ftlink_tyresandwheels", "excludeModels": []},
				{"linkID": "ftlink_interior-overview", "excludeModels": []},
				{"linkID": "ftlink_interior-styling", "excludeModels": []},
				{"linkID": "ftlink_seating", "excludeModels": []},
				{"linkID": "ftlink_entertainment", "excludeModels": []},
				{"linkID": "ftlink_capability-overview", "excludeModels": []},
				{"linkID": "ftlink_engines", "excludeModels": []},
				{"linkID": "ftlink_transmissions", "excludeModels": []},
				{"linkID": "ftlink_handling", "excludeModels": []},
				{"linkID": "ftlink_safety-overview", "excludeModels": []},
				{"linkID": "ftlink_protection", "excludeModels": []},
				{"linkID": "ftlink_lighting", "excludeModels": []},
				{"linkID": "ftlink_theft", "excludeModels": []}
			);

		// loop through all li tags in feature box
		$ES('li', 'feature_wrapper').each(function(li) {

    			// correct links on a tags
    			li.firstChild.href = li.firstChild.href.replace(/jeep.co.uk\/[a-z]+\//, "jeep.co.uk/" + jeep.modelDirectory + "/");

    			// search for the id of the a tag in the link exclusion array
    			linkExclusion.each(function(item) {
        
				// if link id found in exclusion array and
				// exclusion array contains the current model id
				// then go ahead and hide the li tag
        			if(li.firstChild.id == item["linkID"]) {
            				if(item["excludeModels"].contains(jeep.modelID)) {
                				// hide the li tag
                				li.style.display = 'none';
            				} 
        			}
    			});
		});
	}
}

function strrev(str)  {
	if (!str) return '';
	revstr='';

	for (i = str.length-1; i>=0; i--)
		revstr+=str.charAt(i)
	return revstr;
}

function formatPrice(price) {
	
	count = 0;
	formattedPrice = "";
	decimals = "";
	price = new String(price);

	if(price.indexOf('.') != -1) {
		decimals = price.substring(price.indexOf('.'),price.length);
		price = price.substring(0,price.indexOf('.'));
	}		

	// loop through characters from right to left, adding commas where necessary
	for(var i = price.length - 1; i >= 0; i--) {
		count++;

		formattedPrice += price.charAt(i);

		if(count % 3 == 0 && i != 0) {
			formattedPrice += ",";
		}
	}

	formattedPrice = "&pound;" + strrev(formattedPrice) + decimals;

	return formattedPrice;
}


var request = {
	
	queryString: function(key) {
		var qs = location.search;
		
		if(qs.charAt(0) == '?')
			qs = qs.substring(1,qs.length);
		
		var vars = qs.split(/[&;]/);
		var rs = {};

		if (vars.length) vars.each(function(val) {
			var keys = val.split('=');
			if (keys.length && keys.length == 2) rs[encodeURIComponent(keys[0])] = encodeURIComponent(keys[1]);
		});

		return rs[key];
	}
}


window.addEvent('domready', function() {

	jeep.init();

});



/* iFrame resizing methods */

function setIframeHeight(iframeName) {

	try {	
		var iframeWin = window.frames[iframeName];
		var iframeEl = document.getElementById? document.getElementById(iframeName): document.all? document.all[iframeName]: null;
		if ( iframeEl && iframeWin ) {
			iframeEl.style.height = "auto"; // helps resize (for some) if new doc shorter than previous
			var docHt = getDocHeight(iframeWin.document);
			// need to add to height to be sure it will all show
			if (docHt) iframeEl.style.height = docHt + "px";
		}
	}
	catch(err) {}
}

function getDocHeight(doc) {
	
	var docHt = 0, sh, oh;
	if (doc.height) docHt = doc.height;
	else if (doc.body) {
		if (doc.body.scrollHeight) docHt = sh = doc.body.scrollHeight;
		if (doc.body.offsetHeight) docHt = oh = doc.body.offsetHeight;
		if (sh && oh) docHt = Math.max(sh, oh);
	}
	return docHt;

}


/* Adobe Flash loader methods */

//v1.0
//Copyright 2006 Adobe Systems, Inc. All rights reserved.
function AC_AddExtension(src, ext)
{
  if (src.indexOf('?') != -1)
    return src.replace(/\?/, ext+'?'); 
  else
    return src + ext;
}

function AC_Generateobj(objAttrs, params, embedAttrs) 
{ 
  var str = '<object ';
  for (var i in objAttrs)
    str += i + '="' + objAttrs[i] + '" ';
  str += '>';
  for (var i in params)
    str += '<param name="' + i + '" value="' + params[i] + '" /> ';
  str += '<embed ';
  for (var i in embedAttrs)
    str += i + '="' + embedAttrs[i] + '" ';
  str += ' ></embed></object>';

  document.write(str);
}

function AC_FL_RunContent(){
  var ret = 
    AC_GetArgs
    (  arguments, ".swf", "movie", "clsid:d27cdb6e-ae6d-11cf-96b8-444553540000"
     , "application/x-shockwave-flash"
    );
  AC_Generateobj(ret.objAttrs, ret.params, ret.embedAttrs);
}

function AC_SW_RunContent(){
  var ret = 
    AC_GetArgs
    (  arguments, ".dcr", "src", "clsid:166B1BCA-3F9C-11CF-8075-444553540000"
     , null
    );
  AC_Generateobj(ret.objAttrs, ret.params, ret.embedAttrs);
}

function AC_GetArgs(args, ext, srcParamName, classid, mimeType){
  var ret = new Object();
  ret.embedAttrs = new Object();
  ret.params = new Object();
  ret.objAttrs = new Object();
  for (var i=0; i < args.length; i=i+2){
    var currArg = args[i].toLowerCase();    

    switch (currArg){	
      case "classid":
        break;
      case "pluginspage":
        ret.embedAttrs[args[i]] = args[i+1];
        break;
      case "src":
      case "movie":	
        args[i+1] = AC_AddExtension(args[i+1], ext);
        ret.embedAttrs["src"] = args[i+1];
        ret.params[srcParamName] = args[i+1];
        break;
      case "onafterupdate":
      case "onbeforeupdate":
      case "onblur":
      case "oncellchange":
      case "onclick":
      case "ondblClick":
      case "ondrag":
      case "ondragend":
      case "ondragenter":
      case "ondragleave":
      case "ondragover":
      case "ondrop":
      case "onfinish":
      case "onfocus":
      case "onhelp":
      case "onmousedown":
      case "onmouseup":
      case "onmouseover":
      case "onmousemove":
      case "onmouseout":
      case "onkeypress":
      case "onkeydown":
      case "onkeyup":
      case "onload":
      case "onlosecapture":
      case "onpropertychange":
      case "onreadystatechange":
      case "onrowsdelete":
      case "onrowenter":
      case "onrowexit":
      case "onrowsinserted":
      case "onstart":
      case "onscroll":
      case "onbeforeeditfocus":
      case "onactivate":
      case "onbeforedeactivate":
      case "ondeactivate":
      case "type":
      case "codebase":
        ret.objAttrs[args[i]] = args[i+1];
        break;
      case "width":
      case "height":
      case "align":
      case "vspace": 
      case "hspace":
      case "class":
      case "title":
      case "accesskey":
      case "name":
      case "id":
      case "tabindex":
        ret.embedAttrs[args[i]] = ret.objAttrs[args[i]] = args[i+1];
        break;
      default:
        ret.embedAttrs[args[i]] = ret.params[args[i]] = args[i+1];
    }
  }
  ret.objAttrs["classid"] = classid;
  if (mimeType) ret.embedAttrs["type"] = mimeType;
  return ret;
}




/*
 * Smoothbox v20070814 by Boris Popoff (http://gueschla.com)
 * To be used with mootools 1.1x
 * 
 * Based on Cody Lindley's Thickbox, MIT License
 *
 * Licensed under the MIT License:
 *   http://www.opensource.org/licenses/mit-license.php
 */

// on page load call TB_init
window.addEvent('domready', TB_init);

// prevent javascript error before the content has loaded
TB_WIDTH = 0;
TB_HEIGHT = 0;
var TB_doneOnce = 0 ;

// add smoothbox to href elements that have a class of .smoothbox
function TB_init(){
	$$("a.smoothbox").each(function(el){el.onclick=TB_bind});

	// links in shopping tools
	$("shoppingtools-brochure").addEvent('click', TB_bind);
	$("shoppingtools-testdrive").addEvent('click', TB_bind);
}


function TB_bind(event) {

	var event = new Event(event);
	// stop default behaviour
	event.preventDefault();
	// remove click border
	this.blur();
	// get caption: either title or name attribute
	var caption = this.title || this.name || "";
	// get rel attribute for image groups
	var group = this.rel || false;
	// display the box for the elements href
	TB_show(caption, this.href, group);
	//this.onclick=TB_bind;
	return false;
}



// called when the user clicks on a smoothbox link
function TB_show(caption, url, rel) {

	// create iframe, overlay and box if non-existent
	if ( !$("TB_overlay") )
	{
		new Element('iframe').setProperty('id', 'TB_HideSelect').injectInside(document.body);
		$('TB_HideSelect').setOpacity(0);
		new Element('div').setProperty('id', 'TB_overlay').injectInside(document.body);
		$('TB_overlay').setOpacity(0);
		TB_overlaySize();

		// add loading class
		$("TB_overlay").addClass('loaderBg');

		new Fx.Style('TB_overlay', 'opacity',{duration: 400, transition: Fx.Transitions.sineInOut}).start(0,0.8);
	}
	
	
	if ( !$("TB_window") )
	{
		new Element('div').setProperty('id', 'TB_window').injectInside(document.body);
		$('TB_window').setOpacity(0);
	}
	
	$("TB_overlay").onclick=TB_remove;
	window.onscroll=TB_positionEffect;

	// check if a query string is involved
	var baseURL = url.match(/(.+)?/)[1] || url;

	// regex to check if a href refers to an image
	var imageURL = /\.(jpe?g|png|gif|bmp)/gi;

	// check for images
	if ( baseURL.match(imageURL) ) {
		var dummy = { caption: "", url: "", html: "" };
		
		var prev = dummy,
			next = dummy,
			imageCount = "";
			
		// if an image group is given
		if ( rel ) {
			function getInfo(image, id, label) {
				return {
					caption: image.title,
					url: image.href,
					html: "<span id='TB_" + id + "'>&nbsp;&nbsp;<a href='#'>" + label + "</a></span>"
				}
			}
		
			// find the anchors that point to the group
			var imageGroup = [] ;
			$$("a.smoothbox").each(function(el){
				if (el.rel==rel) {imageGroup[imageGroup.length] = el ;}
			})

			var foundSelf = false;
			
			// loop through the anchors, looking for ourself, saving information about previous and next image
			for (var i = 0; i < imageGroup.length; i++) {
				var image = imageGroup[i];
				var urlTypeTemp = image.href.match(imageURL);
				
				// look for ourself
				if ( image.href == url ) {
					foundSelf = true;
					imageCount = "Image " + (i + 1) + " of "+ (imageGroup.length);
				} else {
					// when we found ourself, the current is the next image
					if ( foundSelf ) {
						next = getInfo(image, "next", "Next &gt;");
						// stop searching
						break;
					} else {
						// didn't find ourself yet, so this may be the one before ourself
						prev = getInfo(image, "prev", "&lt; Prev");
					}
				}
			}
		}
		
		imgPreloader = new Image();
		imgPreloader.onload = function() {
			imgPreloader.onload = null;

			// Resizing large images
			var x = window.getWidth() - 150;
			var y = window.getHeight() - 150;
			var imageWidth = imgPreloader.width;
			var imageHeight = imgPreloader.height;
			if (imageWidth > x) {
				imageHeight = imageHeight * (x / imageWidth); 
				imageWidth = x; 
				if (imageHeight > y) { 
					imageWidth = imageWidth * (y / imageHeight); 
					imageHeight = y; 
				}
			} else if (imageHeight > y) { 
				imageWidth = imageWidth * (y / imageHeight); 
				imageHeight = y; 
				if (imageWidth > x) { 
					imageHeight = imageHeight * (x / imageWidth); 
					imageWidth = x;
				}
			}
			// End Resizing
			
			// TODO don't use globals
			TB_WIDTH = imageWidth + 30;
			TB_HEIGHT = imageHeight + 60;
			
			// TODO empty window content instead
			$("TB_window").innerHTML += "<a href='' id='TB_ImageOff' title='Close'><img id='TB_Image' src='"+url+"' width='"+imageWidth+"' height='"+imageHeight+"' alt='"+caption+"'/></a>" + "<div id='TB_caption'>"+caption+"<div id='TB_secondLine'>" + imageCount + prev.html + next.html + "</div></div><div id='TB_closeWindow'><a href='#' id='TB_closeWindowButton' title='Close'>close</a></div>";
			
			$("TB_closeWindowButton").onclick = TB_remove;
			
			function buildClickHandler(image) {
				return function() {
					$("TB_window").remove();
					new Element('div').setProperty('id', 'TB_window').injectInside(document.body);
					
					TB_show(image.caption, image.url, rel);
					return false;
				};
			}
			var goPrev = buildClickHandler(prev);
			var goNext = buildClickHandler(next);
			if ( $('TB_prev') ) {
				$("TB_prev").onclick = goPrev;
			}
			
			if ( $('TB_next') ) {		
				$("TB_next").onclick = goNext;
			}
			
			document.onkeydown = function(event) {
				var event = new Event(event);
				switch(event.code) {
				case 27:
					TB_remove();
					break;
				case 190:
					if( $('TB_next') ) {
						document.onkeydown = null;
						goNext();
					}
					break;
				case 188:
					if( $('TB_prev') ) {
						document.onkeydown = null;
						goPrev();
					}
					break;
				}
			}
			
			// TODO don't remove loader etc., just hide and show later
			$("TB_ImageOff").onclick = TB_remove;
			TB_position();
			TB_showWindow();
		}
		imgPreloader.src = url;
		
	} else { //code to show html pages
		
		var queryString = url.match(/\?(.+)/)[1];
		var params = TB_parseQuery( queryString );
		
		TB_WIDTH = (params['width']*1) + 30;
		TB_HEIGHT = (params['height']*1) + 40;

		var ajaxContentW = TB_WIDTH - 30,
		ajaxContentH = TB_HEIGHT - 45;

		if(url.indexOf('TB_iframe') != -1){				
			urlNoQuery = url.split('TB_');		
			$("TB_window").innerHTML += "<div id='TB_title'><div id='TB_ajaxWindowTitle'>"+caption+"</div><div id='TB_closeAjaxWindow'><a href='#' id='TB_closeWindowButton' title='Close'>close</a></div></div><iframe frameborder='0' hspace='0' src='"+urlNoQuery[0]+"' id='TB_iframeContent' name='TB_iframeContent' style='width:"+(ajaxContentW + 30)+"px;height:"+(ajaxContentH + 15)+"px;' scrolling='no' onload='TB_showWindow()'> </iframe>";
		} else {
			$("TB_window").innerHTML += "<div id='TB_title'><div id='TB_ajaxWindowTitle'>"+caption+"</div><div id='TB_closeAjaxWindow'><a href='#' id='TB_closeWindowButton'>close</a></div></div><div id='TB_ajaxContent' style='width:"+ajaxContentW+"px;height:"+ajaxContentH+"px;'></div>";
		}
	
		$("TB_closeWindowButton").onclick = TB_remove;
		
			if(url.indexOf('TB_inline') != -1){	
				$("TB_ajaxContent").innerHTML = ($(params['inlineId']).innerHTML);
				TB_position();
				TB_showWindow();
			}else if(url.indexOf('TB_iframe') != -1){
				TB_position();
				if(frames['TB_iframeContent'] == undefined){//be nice to safari
					$(document).keyup( function(e){ var key = e.keyCode; if(key == 27){TB_remove()} });
					TB_showWindow();
				}
			}else{
				var handlerFunc = function(){
					TB_position();
					TB_showWindow();
				};
				var myRequest = new Ajax(url, {method: 'get',update: $("TB_ajaxContent"),onComplete: handlerFunc}).request();
			}
	}

	window.onresize=function(){ TB_position(); TB_overlaySize();}  
	
	document.onkeyup = function(event){ 	
		var event = new Event(event);
		if(event.code == 27){ // close
			TB_remove();
		}	
	}
		
}

//helper functions below

function TB_showWindow(){

	setTimeout(function() {

	// remove loading class
	$("TB_overlay").removeClass('loaderBg');

	if (TB_doneOnce==0) {
		TB_doneOnce = 1;
		var myFX = new Fx.Style('TB_window', 'opacity',{duration: 250, transition: Fx.Transitions.sineInOut, onComplete:function(){if ($('TB_load')) { $('TB_load').remove();}} }).start(0,1);
		
	} else {
		$('TB_window').setStyle('opacity',1);
		if ($('TB_load')) { $('TB_load').remove();}
	}
	
	}, 1000);
}

function TB_remove() {
 	$("TB_overlay").onclick=null;
	document.onkeyup=null;
	document.onkeydown=null;
	
	if ($('TB_imageOff')) $("TB_imageOff").onclick=null;
	if ($('TB_closeWindowButton')) $("TB_closeWindowButton").onclick=null;
	if ( $('TB_prev') ) { $("TB_prev").onclick = null; }
	if ( $('TB_next') ) { $("TB_next").onclick = null; }

	new Fx.Style('TB_window', 'opacity',{duration: 250, transition: Fx.Transitions.sineInOut, onComplete:function(){$('TB_window').remove();} }).start(1,0);
	new Fx.Style('TB_overlay', 'opacity',{duration: 400, transition: Fx.Transitions.sineInOut, onComplete:function(){$('TB_overlay').remove();} }).start(0.6,0);

	window.onscroll=null;
	window.onresize=null;	
	
	$('TB_HideSelect').remove();
	TB_init();
	TB_doneOnce = 0;
	return false;
}

function TB_position() {

	var top = (window.getScrollTop() + (window.getHeight() - TB_HEIGHT)/2);
	top = top - 50;
	if(top < 0)
		top = 0;

	$("TB_window").setStyles({width: TB_WIDTH+'px', 
				 left: (window.getScrollLeft() + (window.getWidth() - TB_WIDTH)/2)+'px',
				 top: top +'px'});
}


function TB_positionEffect() {
	new Fx.Styles('TB_window', {duration: 75, transition: Fx.Transitions.sineInOut}).start({
		'left':(window.getScrollLeft() + (window.getWidth() - TB_WIDTH)/2)+'px',
		'top':(window.getScrollTop() + (window.getHeight() - TB_HEIGHT)/2)+'px'});
}

function TB_overlaySize(){
	// we have to set this to 0px before so we can reduce the size / width of the overflow onresize 
	$("TB_overlay").setStyles({"height": '0px', "width": '0px'});
	$("TB_HideSelect").setStyles({"height": '0px', "width": '0px'});
	$("TB_overlay").setStyles({"height": window.getScrollHeight()+'px', "width": window.getScrollWidth()+'px'});
	$("TB_HideSelect").setStyles({"height": window.getScrollHeight()+'px',"width": window.getScrollWidth()+'px'});
}

function TB_load_position() {
	if ($("TB_load")) { $("TB_load").setStyles({left: (window.getScrollLeft() + (window.getWidth() - 56)/2)+'px', top: (window.getScrollTop() + ((window.getHeight()-20)/2))+'px',display:"block"}); }
}

function TB_parseQuery ( query ) {
	// return empty object
	if( !query )
		return {};
	var params = {};
	
	// parse query
	var pairs = query.split(/[;&]/);
	for ( var i = 0; i < pairs.length; i++ ) {
		var pair = pairs[i].split('=');
		if ( !pair || pair.length != 2 )
			continue;
		// unescape both key and value, replace "+" with spaces in value
		params[unescape(pair[0])] = unescape(pair[1]).replace(/\+/g, ' ');
   }
   return params;
}

/* End Smoothbox */