/*
 * jQuery.ScrollTo - Easy element scrolling using jQuery.
 * Copyright (c) 2007-2009 Ariel Flesler - aflesler(at)gmail(dot)com | http://flesler.blogspot.com
 * Dual licensed under MIT and GPL.
 * Date: 5/25/2009
 * @author Ariel Flesler
 * @version 1.4.2
 *
 * http://flesler.blogspot.com/2007/10/jqueryscrollto.html
 */
;(function(d){var k=d.scrollTo=function(a,i,e){d(window).scrollTo(a,i,e)};k.defaults={axis:'xy',duration:parseFloat(d.fn.jquery)>=1.3?0:1};k.window=function(a){return d(window)._scrollable()};d.fn._scrollable=function(){return this.map(function(){var a=this,i=!a.nodeName||d.inArray(a.nodeName.toLowerCase(),['iframe','#document','html','body'])!=-1;if(!i)return a;var e=(a.contentWindow||a).document||a.ownerDocument||a;return d.browser.safari||e.compatMode=='BackCompat'?e.body:e.documentElement})};d.fn.scrollTo=function(n,j,b){if(typeof j=='object'){b=j;j=0}if(typeof b=='function')b={onAfter:b};if(n=='max')n=9e9;b=d.extend({},k.defaults,b);j=j||b.speed||b.duration;b.queue=b.queue&&b.axis.length>1;if(b.queue)j/=2;b.offset=p(b.offset);b.over=p(b.over);return this._scrollable().each(function(){var q=this,r=d(q),f=n,s,g={},u=r.is('html,body');switch(typeof f){case'number':case'string':if(/^([+-]=)?\d+(\.\d+)?(px|%)?$/.test(f)){f=p(f);break}f=d(f,this);case'object':if(f.is||f.style)s=(f=d(f)).offset()}d.each(b.axis.split(''),function(a,i){var e=i=='x'?'Left':'Top',h=e.toLowerCase(),c='scroll'+e,l=q[c],m=k.max(q,i);if(s){g[c]=s[h]+(u?0:l-r.offset()[h]);if(b.margin){g[c]-=parseInt(f.css('margin'+e))||0;g[c]-=parseInt(f.css('border'+e+'Width'))||0}g[c]+=b.offset[h]||0;if(b.over[h])g[c]+=f[i=='x'?'width':'height']()*b.over[h]}else{var o=f[h];g[c]=o.slice&&o.slice(-1)=='%'?parseFloat(o)/100*m:o}if(/^\d+$/.test(g[c]))g[c]=g[c]<=0?0:Math.min(g[c],m);if(!a&&b.queue){if(l!=g[c])t(b.onAfterFirst);delete g[c]}});t(b.onAfter);function t(a){r.animate(g,j,b.easing,a&&function(){a.call(this,n,b)})}}).end()};k.max=function(a,i){var e=i=='x'?'Width':'Height',h='scroll'+e;if(!d(a).is('html,body'))return a[h]-d(a)[e.toLowerCase()]();var c='client'+e,l=a.ownerDocument.documentElement,m=a.ownerDocument.body;return Math.max(l[h],m[h])-Math.min(l[c],m[c])};function p(a){return typeof a=='object'?a:{top:a,left:a}}})(jQuery);
//////////////////////////////////////////////////////////////////////////////////
// Cloud Zoom V1.0.2
// (c) 2010 by R Cecco. <http://www.professorcloud.com>
// MIT License
//
// Please retain this copyright header in all versions of the software
//////////////////////////////////////////////////////////////////////////////////
(function($){$(document).ready(function(){$('.cloud-zoom, .cloud-zoom-gallery').CloudZoom()});function format(str){for(var i=1;i<arguments.length;i++){str=str.replace('%'+(i-1),arguments[i])}return str}function CloudZoom(jWin,opts){var sImg=$('img',jWin);var img1;var img2;var zoomDiv=null;var $mouseTrap=null;var lens=null;var $tint=null;var softFocus=null;var $ie6Fix=null;var zoomImage;var controlTimer=0;var cw,ch;var destU=0;var destV=0;var currV=0;var currU=0;var filesLoaded=0;var mx,my;var ctx=this,zw;setTimeout(function(){if($mouseTrap===null){var w=jWin.width();jWin.parent().append(format('<div style="width:%0px;position:absolute;top:75%;left:%1px;text-align:center" class="cloud-zoom-loading" ></div>',w/3,(w/2)-(w/6))).find(':last').css('opacity',0.5)}},200);var ie6FixRemove=function(){if($ie6Fix!==null){$ie6Fix.remove();$ie6Fix=null}};this.removeBits=function(){if(lens){lens.remove();lens=null}if($tint){$tint.remove();$tint=null}if(softFocus){softFocus.remove();softFocus=null}ie6FixRemove();$('.cloud-zoom-loading',jWin.parent()).remove()};this.destroy=function(){jWin.data('zoom',null);if($mouseTrap){$mouseTrap.unbind();$mouseTrap.remove();$mouseTrap=null}if(zoomDiv){zoomDiv.remove();zoomDiv=null}this.removeBits()};this.fadedOut=function(){if(zoomDiv){zoomDiv.remove();zoomDiv=null}this.removeBits()};this.controlLoop=function(){if(lens){var x=(mx-sImg.offset().left-(cw*0.5))>>0;var y=(my-sImg.offset().top-(ch*0.5))>>0;if(x<0){x=0}else if(x>(sImg.outerWidth()-cw)){x=(sImg.outerWidth()-cw)}if(y<0){y=0}else if(y>(sImg.outerHeight()-ch)){y=(sImg.outerHeight()-ch)}lens.css({left:x,top:y});lens.css('background-position',(-x)+'px '+(-y)+'px');destU=(((x)/sImg.outerWidth())*zoomImage.width)>>0;destV=(((y)/sImg.outerHeight())*zoomImage.height)>>0;currU+=(destU-currU)/opts.smoothMove;currV+=(destV-currV)/opts.smoothMove;zoomDiv.css('background-position',(-(currU>>0)+'px ')+(-(currV>>0)+'px'))}controlTimer=setTimeout(function(){ctx.controlLoop()},30)};this.init2=function(img,id){filesLoaded++;if(id===1){zoomImage=img}if(filesLoaded===2){this.init()}};this.init=function(){$('.cloud-zoom-loading',jWin.parent()).remove();$mouseTrap=jWin.parent().append(format("<div class='mousetrap' style='background-image:url(\".\");z-index:999;position:absolute;width:%0px;height:%1px;left:%2px;top:%3px;\'></div>",sImg.outerWidth(),sImg.outerHeight(),0,0)).find(':last');$mouseTrap.bind('mousemove',this,function(event){mx=event.pageX;my=event.pageY});$mouseTrap.bind('mouseleave',this,function(event){clearTimeout(controlTimer);if(lens){lens.fadeOut(299)}if($tint){$tint.fadeOut(299)}if(softFocus){softFocus.fadeOut(299)}zoomDiv.fadeOut(300,function(){ctx.fadedOut()});return false});$mouseTrap.bind('mouseenter',this,function(event){mx=event.pageX;my=event.pageY;zw=event.data;if(zoomDiv){zoomDiv.stop(true,false);zoomDiv.remove()}var xPos=opts.adjustX,yPos=opts.adjustY;var siw=sImg.outerWidth();var sih=sImg.outerHeight();var w=opts.zoomWidth;var h=opts.zoomHeight;if(opts.zoomWidth=='auto'){w=siw}if(opts.zoomHeight=='auto'){h=sih}var appendTo=jWin.parent();switch(opts.position){case'top':yPos-=h;break;case'right':xPos+=siw;break;case'bottom':yPos+=sih;break;case'left':xPos-=w;break;case'inside':w=siw;h=sih;break;default:appendTo=$('#'+opts.position);if(!appendTo.length){appendTo=jWin;xPos+=siw;yPos+=sih}else{w=appendTo.innerWidth();h=appendTo.innerHeight()}}zoomDiv=appendTo.append(format('<div id="cloud-zoom-big" class="cloud-zoom-big" style="display:none;position:absolute;left:%0px;top:%1px;width:%2px;height:%3px;background-image:url(\'%4\');z-index:99;"></div>',xPos,yPos,w,h,zoomImage.src)).find(':last');if(sImg.attr('title')&&opts.showTitle){zoomDiv.append(format('<div class="cloud-zoom-title">%0</div>',sImg.attr('title'))).find(':last').css('opacity',opts.titleOpacity)}if($.browser.msie&&$.browser.version<7){$ie6Fix=$('<iframe frameborder="0" src="#"></iframe>').css({position:"absolute",left:xPos,top:yPos,zIndex:99,width:w,height:h}).insertBefore(zoomDiv)}zoomDiv.fadeIn(500);if(lens){lens.remove();lens=null}cw=(sImg.outerWidth()/zoomImage.width)*zoomDiv.width();ch=(sImg.outerHeight()/zoomImage.height)*zoomDiv.height();lens=jWin.append(format("<div class = 'cloud-zoom-lens' style='display:none;z-index:98;position:absolute;width:%0px;height:%1px;'></div>",cw,ch)).find(':last');$mouseTrap.css('cursor',lens.css('cursor'));var noTrans=false;if(opts.tint){lens.css('background','url("'+sImg.attr('src')+'")');$tint=jWin.append(format('<div style="display:none;position:absolute; left:0px; top:0px; width:%0px; height:%1px; background-color:%2;" />',sImg.outerWidth(),sImg.outerHeight(),opts.tint)).find(':last');$tint.css('opacity',opts.tintOpacity);noTrans=true;$tint.fadeIn(500)}if(opts.softFocus){lens.css('background','url("'+sImg.attr('src')+'")');softFocus=jWin.append(format('<div style="position:absolute;display:none;top:2px; left:2px; width:%0px; height:%1px;" />',sImg.outerWidth()-2,sImg.outerHeight()-2,opts.tint)).find(':last');softFocus.css('background','url("'+sImg.attr('src')+'")');softFocus.css('opacity',0.5);noTrans=true;softFocus.fadeIn(500)}if(!noTrans){lens.css('opacity',opts.lensOpacity)}if(opts.position!=='inside'){lens.fadeIn(500)}zw.controlLoop();return})};img1=new Image();$(img1).load(function(){ctx.init2(this,0)});img1.src=sImg.attr('src');img2=new Image();$(img2).load(function(){ctx.init2(this,1)});img2.src=jWin.attr('href')}$.fn.CloudZoom=function(options){try{document.execCommand("BackgroundImageCache",false,true)}catch(e){}this.each(function(){var relOpts,opts;eval('var	a = {'+$(this).attr('rel')+'}');relOpts=a;if($(this).is('.cloud-zoom')){$(this).css({'position':'relative','display':'block'});$('img',$(this)).css({'display':'block'});if($(this).parent().attr('id')!='wrap'){$(this).wrap('<div id="wrap" style="top:0px;z-index:9999;position:relative;"></div>')}opts=$.extend({},$.fn.CloudZoom.defaults,options);opts=$.extend({},opts,relOpts);$(this).data('zoom',new CloudZoom($(this),opts))}else if($(this).is('.cloud-zoom-gallery')){opts=$.extend({},relOpts,options);$(this).data('relOpts',opts);$(this).bind('click',$(this),function(event){var data=event.data.data('relOpts');$('#'+data.useZoom).data('zoom').destroy();$('#'+data.useZoom).attr('href',event.data.attr('href'));$('#'+data.useZoom+' img').attr('src',event.data.data('relOpts').smallImage);$('#'+event.data.data('relOpts').useZoom).CloudZoom();return false})}});return this};$.fn.CloudZoom.defaults={zoomWidth:'auto',zoomHeight:'auto',position:'right',tint:false,tintOpacity:0.5,lensOpacity:0.5,softFocus:false,smoothMove:3,showTitle:true,titleOpacity:0.5,adjustX:0,adjustY:0}})(jQuery);
/*
 * Code by AD
 * SuiteCommerce
 */
//Prices
function parsePrice(number,bool)	{
	number = (Math.round(number*100))/100;
	var aux1 = parseInt(number/1000), aux2 = Math.round((number%1000)*100)/100;
	if(aux2 < 100)	{
		if(aux2 < 10) aux2 = "00"+ aux2;
		else aux2 = "0"+ aux2;
	}
	if(aux1 > 0)	{
		aux1 = parsePrice(aux1,true);
		number = aux1 +","+ aux2;
	}
	if(!bool){
		number += "";
		if (number.indexOf(".") != -1) {
			var sigFig = number.substring(number.indexOf(".") + 1, number.length);
			if (sigFig.length == 1)	number += "0";
		}
		else number += ".00";
		return "$" + number;
	}
	return number;
}
function getNumber(string){
	string += "";
	if(string.indexOf("$") != -1) string = string.substring(string.indexOf("$") + 1).replace(",","").replace(" ","");
	return parseFloat(string);
}
// Options Display
function parseOptions(wrap){
	wrap.find("select").each(function(){
		var current = $(this), td = current.parent().hide().parent();
		td.removeAttr("noWrap");
		td.removeAttr("nowrap");
		var type = (this.id == "custcol1") ? "color" : "size";
		current.find("option[value!='']").each(function(){
			var option = $("<a href='#' rel='" + $(this).val() + "' class='option " + type + "'>" + $(this).html() + "</a>");
			if(type == "color") {
				td.parent().not(".disclaimed").after("<tr class='disclaimer'><td colspan='2'>&nbsp;</td><td>Product color may vary from button above.</td></tr>").addClass("disclaimed");
				option.css("background","url('/site/img/colors/opt-color-" + $(this).val() + ".png')");
				option.attr("title",$(this).text());
			}
			option.appendTo(td);
		});
	});
	wrap.find(".option").click(function(){
		var current = $(this), td = current.parent();
		td.find("a").filter(".selected").removeClass("selected");
		current.addClass("selected");
		td.find("option[value='" + current.attr("rel") + "']").attr("selected",true).parent().change();
		return false;
	});
}
// Quick View
function quickView(itemList){
	var itemsWrap = $("#" + itemList), quickWrap = $("#quick-view");
	quickWrap.find(".content-wrap").html('');
	itemsWrap.find(".quick-view").each(function(){
		var current = $(this), discontinued = current.find(".discontinued").text(),
			backDate = current.find(".stock-date").text(),
			dropship = current.find(".dropship").text(),
			viewOnly = current.find(".view-only").text();
		if(viewOnly == "Yes") {
			current.find(".qty-wrap").hide();
			current.find(".addtocart").hide().parent().append("<a href='http://www.audiusa.com/us/brand/en/tools/ngwext/dsh/dealersearch.html' target='_blank' class='find-dealer'>Find a Dealer</a>");
			current.find(".stock-message").html("This item is sold only through your local dealership. Professional installation may be required at an additional charge.");
		}
		else if(dropship == "Yes"){
			current.find(".stock-message").html("Please allow 3-4 weeks for delivery of this item. Item will be shipped separately from other Audi collection purchases and will ship via UPS ground only.");
		}
		else if(discontinued == "No" && current.find(".stock-status span").html() != ""){
			backDate = (backDate == "") ? "" : ", expected on " + backDate;
			current.find(".stock-message").html("We apologize this item is currently out of stock" + backDate + ". You may still add this item to your cart and we will ship the item as soon as it is available.");
		}
		//else if(discontinued == "Yes") current.find(".addtocart").hide();
		current.appendTo(quickWrap.find(".content-wrap"));
	});
	parseOptions(quickWrap);
	itemsWrap.find(".quick-btn").click(function(){
		var isMatrix = $(this).parent().find(".is-matrix").text(), quickView = quickWrap.find("#quick-item-" + this.rel);
		quickWrap.show().find(".quick-view").hide();
		if(isMatrix == "T" && quickView.find("select").length == 0){
			var options = quickView.find(".options");
			options.parent().find(".cart-wrap").hide();
			options.addClass("loading").load(quickView.find(".name:first a").attr("href") + " #sc_table_kore",function(){
				options.removeClass("loading").find("#sc_table_kore").attr("id","");
				parseOptions(quickView);
				options.parent().find(".cart-wrap").show();
			});
		}
		quickView.show();
		$.scrollTo("#quick-view",500);
		return false;
	});
	itemsWrap.find(".itemcell").hover(function(){
		$(this).find(".quick-btn").css("display","block");
	},function(){
		$(this).find(".quick-btn").hide();
	});
	quickWrap.find(".close").click(function(){
		quickWrap.hide();
		return false;
	});
	quickWrap.find(".add-wish").click(function(){
		var current = $(this), wrap = current.parent().parent(),
			config = {
				customer : wrap.find(".customer").val(),
				item : current.attr("rel"),
				messages : current.parent().find(".wish-messages p:first")
			};
		addToWishlist(config);
		return false;
	});
	quickWrap.find(".addtocart").click(function(){
		var current = $(this), cartWrap = current.parent().parent(),
			minQty = cartWrap.find(".minqty:first").text(),
			qty = cartWrap.find(".qty").val(), procede = true,
			options = "",cartCell = cartWrap.find(".new_in_cart_");
		cartCell.find("tr:first td:last").html(qty);
		cartCell.find("tr:gt(1)").remove();
		cartWrap.find("table table select").each(function(){
			var select = $(this), td = select.parent().parent(), label = td.parent().find("a:first").text(), selected = td.find(".selected");
			if(procede){
				if (select.find("option:selected").val() == "") {
					alert("Please select a value for: " + label);
					procede = false;
				}
				else {
					options += "&" + select.attr("id") + "=" + select.find("option:selected").val();
					cartCell.find("table").append("<tr><td class='option_label_'>" + label + "</td><td></td></tr>");
					selected.clone().appendTo(cartCell.find(".option_label_:contains('" + label + "')").next());
				}
			}
		});
		cartWrap.find("table table input").each(function(){
			var input = $(this), td = input.parent().parent(),
				label = td.parent().find("a:first").text();
			if(procede){
				if(input.val() != ""){
					options += "&" + input.attr("id") + "=" + input.val();
					cartCell.find("table").append("<tr><td class='option_label_'>" + label + "</td><td>" + input.val() + "</td></tr>");
				}
				else if (input.hasClass("inputreq")) {
					alert("Please select a value for: " + label);
					procede = false;
				}
			}
		});
		if(procede)	{
			if(parseFloat(qty) >= parseFloat(minQty)){
				$.get("/app/site/backend/additemtocart.nl?c=1135977&buyid=" + current.attr("rel") + "&qty=" + qty + options);
				//$.scrollTo("#div__header",200);
				$("<div class='red-box'></div>").appendTo("#customproduct_minicart div:first");
				$(function(){
					$("#customproduct_minicart").find(".red-box").animate({
						height: '-=185',
						width: '-=195',
						top: '-=230',
						left: '+=445'
					},"slow",function(){
						var count = $("#customproduct_minicart").find("#item-count").find("span");
						var total = parseFloat(count.html()) + parseFloat(qty);
						var count2 = $('#ms_minicart_expbox .qty_items');
						count.html(total);
						count2.html(total);
						$(this).remove();
						updateItems(cartCell.html());
						var totalMC = $('#ms_minicart_expbox .cart_subtotal_value_');
						var totalMCVal = totalMC.text().replace('$','').replace(',','');
						var itemTotal = $('#ms_minicart_expbox .new_item_selected_options_ tr:eq(1) td:eq(1)').text().replace('$','').replace(',','');
						var itemQty = $('#ms_minicart_expbox .new_item_selected_options_ tr:eq(0) td:eq(1)').text();
						var totalMCNew = totalMC.text().replace('$','').replace(',','');
						jQuery('#ms_minicart_expbox .cart_subtotal_value_').html('$' + (parseFloat(totalMCNew) + parseFloat(itemTotal)).toFixed(2));
						if(parseFloat(itemTotal > 0)) totalMC.html(parsePrice(parseFloat(totalMCVal) + (parseFloat(itemTotal) * parseInt(itemQty))));
					});
				});
			}
			else alert("The minimum quantity for this item is "+ minQty +".");
		}
		return false;
	});
}
// Cookies
function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}
function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}
function eraseCookie(name) {
	createCookie(name,"",-1);
}
// Wishlist
function addToWishlist(config){
	config.messages.hide();
	var items = readCookie("wishlist");
	if (!items) createCookie("wishlist",config.item,30);
	else {
		var splited = items.split(","), found = false;
		for(var i = 0; i < splited.length; i++){
			if(parseFloat(splited[i]) == config.item) found = true;
		}
		if (!found) items += "," + config.item;
		createCookie("wishlist",items,30);
	}
	if(config.customer != "") $.get("/app/site/hosting/scriptlet.nl?script=22&deploy=1&q=1&s=1&o=&ss=13&i=" + config.item + "&j=" + config.customer,function(){
		updateWishBox(config.customer);
	});
	else updateWishBox("");
	config.messages.show();
	setTimeout(function(){
		config.messages.fadeOut();
	},5000);
}
function updateWishBox(customer){
	var wrap = $("#my-wishlist"), itemsWished = readCookie("wishlist");
	wrap.find("div").html("");
	if (customer == "") {
		wrap.find(".bullet_r").show();
		if(itemsWished) $.getScript("/app/site/hosting/scriptlet.nl?script=14&deploy=1&i=" + itemsWished,function(){
			removeWishItem(wrap);
		});
		else wrap.find("div").html("<p>There are no items in your Wish List. <br/>Look for the \"Add to Wish List\" links throughout the site.</p>");
	}
	else $.getScript("/app/site/hosting/scriptlet.nl?script=15&deploy=1&i=" + itemsWished + "&j=" + customer,function(){
		$(function(){
			if(wrap.find("div").html() == "") wrap.find("div").html("<p>There are no items in your Wish List. <br/>Look for the \"Add to Wish List\" links throughout the site.</p>");
			else removeWishItem(wrap,customer);
		});
	});
}
function drawWishItem(itemId,itemName,itemUrl){
	$("#my-wishlist > div:first").append("<div class='cell_wish_'><a class='remove' href='#' rel='" + itemId + "'><img src='/site/img/remove_wish.gif' /></a><a href=/" + itemUrl + " rel='" + itemId + "'>" + unescape(itemName) + "</a></div>");
}
function removeWishItem(wraper,customer){
	wraper.find(".remove").click(function(){
		var current = $(this), cookieWish = readCookie("wishlist").split(","), itemId = current.attr("rel"), newWish = [];
		for(var i = 0; i < cookieWish.length; i++){
			if(cookieWish[i] != itemId) newWish.push(cookieWish[i]);
		}
		createCookie("wishlist",newWish.join(","),30);
		if(customer != "") $.get("/app/site/hosting/scriptlet.nl?script=17&deploy=1&j=" + customer + "&i=" + itemId);
		current.parent().fadeOut(function(){
			current.parent().remove();
			if(wraper.find(".cell_wish_").length == 0) wraper.find("div").html("<p>There are no items in your Wish List. <br/>Look for the \"Add to Wish List\" links throughout the site.</p>");
		});
		return false;
	});
}
