// ###### start mssQv Class (with Ajax)  #######
// This script is the sole property of 4D Internet Solutions. Copyright 2008. All rights reserved. It may not be copied, used, modified except under license from 4D Internet Soutions, Inc.
var mssQvVersion = 4.0; // requires mootools 1.2
var mssQv = new Class({
	Implements: [Options, Events],
	options: {
		qvBtnText: '',
		moreTxt: 'More Details',
		singleEl: false,
		container: 'container',
		waitText: 'Loading. Please wait...',
		includeAlts: true, 
		includeYouSave: true, 
		includeTabs: true,
		includeShadow: true,
		draggable: true,
		skipCart: false,
		customFieldNames: new Array("Designer","Fabric","Availability","","","","","",""),
		addCartImg:'/playground/quickview/addtocart.gif', //if no image, set to false
		frameCart:false,
		qvOffestLeft: -160,
		qvOffestTop: -150
	},
	
	initialize: function(options){
		this.setOptions(options),
		this.qvBtnText = this.options.qvBtnText || '',
		this.includeAlts = this.options.includeAlts || false,
		this.includeYouSave = this.options.includeYouSave || false,
		this.includeTabs = this.options.includeTabs || false,
		this.includeShadow = this.options.includeShadow || false,
		this.draggable = this.options.draggable || false,
		this.skipCart =  this.options.skipCart || false,
		this.moreTxt = this.options.moreTxt || '',
		this.customFieldNames = this.options.customFieldNames || null,
		this.qvOffestLeft = this.options.qvOffestLeft || 0,
		this.qvOffestTop = this.options.qvOffestTop || 0,
		this.singleEl = $(this.options.singleEl),
		this.qvBtn = null,
		this.addCartImg = this.options.addCartImg || false,
		this.frameCart = this.options.frameCart || false,
		this.qv = null,
		this.activeContent = "",
		this.ajax = null,
		this.qvShell = null,
		this.qvOverlay = null,
		this.waiting = null,
		this.cLeft = 0,
		this.cTop = 0,
		this.container = $(this.options.container) || null,
		this.waitText = this.options.waitText || "",
		this.pageHeight = 0,
		this.frameId = 0,
		this.initQv()
	},
	
	initQv: function(){
		var imgs = $$('#contents img');
		imgs.each(function(im){
			var img = im;
			im.addEvent('mouseenter',(function(){this.initCurrent(img);ghostImg = img.clone();}).bind(this))
		},this)
	},
		
	initCurrent: function(el){this.buildBtn();this.showQvBtn(el);},
	
	buildBtn: function(){
		if($chk($('qvBtn'))) $('qvBtn').dispose();
		this.qvBtn = new Element('a', {'id': 'qvBtn', "class":'qvBtn'});
	},
	
	showQvBtn: function(el){ 
	  	var td = el.parentNode.parentNode.parentNode;
	  	var index = $$('#contents td').indexOf(td);
		var pageUrl = "qv"+index+".html"; 
 		if (true){ 
			this.qvBtn.injectTop(td);
			this.qvBtn.setAttribute('href','javascript:void(0)');
			this.qvBtn.setAttribute('rel',pageUrl);
			this.cLeft = 390//this.findPos(this.qvBtn)[0] + this.qvOffestLeft;
			this.cTop = 200//this.findPos(this.qvBtn)[1] + this.qvOffestTop;
			if (this.qvBtnText.length > 0){this.qvBtn.innerHTML=this.qvBtnText;}
		  	this.qvBtn.style.visibility='visible';
			this.qvBtn.addEvent('click',this.prepQvWin.bind(this));
  		} else { return false; } 
	},
	
	findPos: function(obj){
		var curleft = curtop = 0;if (obj.offsetParent) {do {curleft += obj.offsetLeft;curtop += obj.offsetTop;} while (obj = obj.offsetParent);}return [curleft,curtop];
	},
	
	prepQvWin: function(e){ 
		if (!e) var e = window.event; 
		new Event(e).stop();  
		var el = (e.target) ? e.target : ((e.srcElement) ? e.srcElement : null);
		try{if($chk(mssHideCart)){mssHideCart()}}catch(e){}
		var frameContainer=(this.frameCart)?$('mssFrameContainer'):document.body;
		if ($type($('mssframe'+this.frameId))=='element') {$('mssframe'+this.frameId).dispose();}
		this.frameId++;
		if(this.frameCart){	mssMakeFrame('http://order.store.yahoo.net/cgi-bin/wg-order?catalog=' + storeId)}
		else {
			this.iframe = new Element('iframe', {'id': 'mssframe'+this.frameId, 'name': 'mssframe'+this.frameId, 'scrolling': 'no', 'frameborder': 0}).injectInside(frameContainer);
			this.iframe.setStyles({border: 'none',width: 1,height:1,visibility: 'hidden'});
		}
		if ($type($('qvShell'))=='element'){$('qvShell').dispose();}
		this.qvShell = new Element('div', {'id': 'qvShell', 'styles': {'top': this.cTop, 'left': this.cLeft}}).injectInside(document.body);
		this.qvDrag = new Element('div', {'id': 'qvDrag'}).injectInside(this.qvShell);
		this.qvClose = new Element('a', {'id': 'qvClose', 'href':"javascript:void(0)"}).injectInside(this.qvDrag);
		this.qv = new Element('div', {'id': 'qv1'}).injectInside(this.qvShell);
	  	this.getAjax(el.rel);
		this.buildOverlay();
		this.waiting.setStyle('display','block');
	},
	
	getWinHeight: function(){
		var a = this.container.offsetHeight;
		var b = window.getHeight()+ window.getScrollTop();
		return Math.max(a, b);
	},
	
	buildOverlay: function(){
		if (this.qvOverlay) this.qvOverlay.dispose();
		if (this.waiting) this.waiting.dispose();
		this.qvOverlay = new Element('div', {'id': 'qvOverlay', 'styles': {'height': this.getWinHeight(),'opacity':.5,'position':'absolute', 'width':'100%','height':'100%', 'zIndex':1000, 'background':'#000', 'top':0, 'bottom':0, 'left':0, 'cursor':'pointer'}}).injectTop(document.body);
		//var fadeInOverlay = new Fx.Tween('qvOverlay', {property: 'opacity', duration: 200}).start(0, 0.5);
		this.waiting = new Element('div', {'id': 'qvLoading', 'alt':this.waitText, 'title':this.waitText, 'styles': {'top': this.cTop}}).injectTop(document.body);
		this.waiting.innerHTML=this.waitText;
	},
		
	
	getAjax: function(url){ 
		if(this.ajax){if (this.ajax.url==url)return;}
		this.ajax = new Request({url: url, method: 'get', evalScripts: false,autoCancel: true,onSuccess: this.Callback.bind(this)}).send();
	 },
	 
	 Callback: function(ResponseText){	
		var fadeOutOverlay = new Fx.Tween('qvOverlay', {property: 'opacity',duration: 200}).start(0);
	 	var start = ResponseText.indexOf('<!--mssqvstart');
		var end = ResponseText.indexOf('mssqvend-->');
		this.activeContent = ResponseText.substring(start + 14, end);
		this.showQvWin();
		this.ajax = null;
	},
	
	showQvWin: function(){
		this.waiting.setStyle('display','none');    	
		this.activeContent = this.activeContent.replace( new RegExp( "\\n", "g" )," ");
		var a = JSON.decode(this.activeContent);
		this.customFields=a;
		a.act = a.act.toLowerCase();
		var fid=(this.frameCart)?mssCartFrameId:this.frameId;
		var skipCart = (this.skipCart && !Browser.Engine.webkit) ? ' target="mssframe' + fid + '" onsubmit="reloadCart()" ' :'';
		var head = (a.name)? '<h3>' +a.name+ '</h3>':"";
		var name = (a.name)? '<div id="qvName"><a href="#">' +a.name+ '</a></div>':"";
		var caption = (a.caption)? '<div id="qvCaption">' +a.caption+ '</div>':"";
		var img = (a.images)? '<a href="#"><img id="qvIm0" src="' +a.images.split('^')[0]+ '" border="0" hspace="0" vspace="0" alt="' +a.name+ '" /></a>': "";
		var p = (a.price>0)?a.price:-1;
		var s = (a.sprice>0)?a.sprice:-1;
		var price = (p>-1)? '<div id="qvP" class="price">Retail price: $' + p + '</div>': "";
		var sprice =(s>-1)?  '<div id="qvSp" class="sale-price-bold">Our price: $' +s+ '</div>':"";
		var youSave = (this.includeYouSave && p>0 && s>0)?'<div id="qvSave">You Save: ' + ((p - s)/(p)*100).toFixed(2) + '%</div>':"";
		var options = (a.options)?'<div id="qvOptions"></div>':"";
		var cartBtn = (this.addCartImg)?'<input id="qvCartBtn" type="image" src="'+this.addCartImg+'" value="' +a.btn+ '" />':'<input id="qvCartBtn" type="submit" class="ys_primary" value="' +a.btn+ '" />';
		var tabs = (this.includeTabs)?'<div id="qvT1" class="active">Overview</div><div id="qvT2">Details</div>':"";
		var tab2Content = (this.includeTabs)?this.makeCustomFields(a.custom):"";
		
		var qvWin = '<div id="qvContainer">'
			+tabs+
			'<form onsubmit="alert(\'this feature is not active in this demo\'); return false;" method="POST"' +skipCart+ 'action="http://order.store.yahoo.net/cgi-bin/wg-order?' + a.act + '+' +a.id+ '" id="qvForm">\
				<input id="qvAct" name="vwcatalog" type="hidden" value="' + a.act + '" />\
				<input id="qvId" name="vwitem" type="hidden" value="' + a.id + '" />\
				<input id="qvDone" type="hidden" name=".autodone" value="' + a.url + a.id  + '.html" />\
				'+head+'<div id="qvImage">'
					+img+
					'<div id="qvAltImgs"></div></div>\
				<div id="qvEls1">\
					'+price+sprice+youSave+options+caption+cartBtn+'\
				<a href="' + a.id + '.html" class="qvItemLink">'+this.moreTxt+'</a>\
				</div>\
				<div id="qvEls2">'+tab2Content+'</div>\
			</form>\
			<div class="clearfix"></div>\
			</div>';	
	  this.qv.innerHTML=qvWin;
		var form = $('qvForm');
		mssActiveCartForm = form;
	  this.qvDrag.innerHTML+='<div class="header">'+this.makeCustomFields(a.custom,'designer')+'</div>';
		if (this.includeTabs) {
			$('qvT1').addEvent('click',this.changeTabs.bind(this));
			$('qvT2').addEvent('click',this.changeTabs.bind(this));
		}
		this.makeOptions(a.options);
		$('qvClose').addEvent('click',this.closeQv.bind(this));
		if (this.includeAlts) {this.makeAltThmbs(a.images, a.thumbs);}
		if (this.includeShadow) {this.addShadow(this.qvShell.offsetHeight,this.qvShell.offsetWidth);}
		var fadeInFx = new Fx.Tween('qvShell', { property:'opacity', duration: 300}).start(0,1);
	  	if(this.draggable) this.qvShell.makeDraggable({handle: $('qvDrag')});
	},
	
	addShadow: function(h,w){
		this.shadow = new Element('div', {'id': 'qvShadow', 'styles': {'width': w, 'height':h}}).injectInside(this.qvShell);
	},
	
	makeCustomFields: function(cfields,f){
		var customFields = "";
		var header = "";
		if (cfields){
			var fieldData = cfields.split('^');
			fieldData.each(function(fdata,i){
				if(fdata.length>0){
					if(f=='designer'&&i==0){
						header=fdata;
					}
					else{
						var cname = (this.customFieldNames[i].length>0)?'<b>'+this.customFieldNames[i]+'</b>:':"";
						customFields+='<div class="customField">'+cname+fdata+"</div>";
					}
				}
			}, this)
		}
		
		if(f=='designer'&&header!=""){return header;}
		else{return customFields;}
	},
	
	changeTabs: function(e){
		if (!e) var e = window.event; 
		new Event(e).stop();  
		var el = (e.target) ? e.target : ((e.srcElement) ? e.srcElement : null);
		var c = el.id.substring(3);
		var onId = 'qvEls' + c;
		$('qvEls1').style.display='none';
		$('qvEls2').style.display='none';
		$(onId).style.display='block';
		$('qvT1').className='';
		$('qvT2').className='';
		el.className='active';
	},
	
	makeAltThmbs: function(imgs, thmbs){
		if (!imgs || !thmbs) return;
		var altThmbs = thmbs.split('^');
		var altImgs = imgs.split('^');
		for (i=0;i<altThmbs.length;i++){
			var thisAlt = altThmbs[i];
			var thisLink = new Element('a', {'href': 'javascript:void(0)'}).injectInside($('qvAltImgs'));
			var thisImg = new Element('img', {'src': thisAlt, 'alt':i}).injectTop(thisLink);
			thisImg.addEvent('mouseover',function(){
				var index = (this.alt * 1);
				if ((index * 1)==0) {$('qvIm0').src=altImgs[0]} 
				else {$('qvIm0').src=altImgs[index]}
				})
		}
		$('qvAltImgs').style.display='block';
	},
	
	makeOptions: function(options){
		if (!options) {return}
		var optDiv = $('qvOptions');
		var menu = options.split("^"); 
		for(i=0;i<menu.length;i++){  
			var thisMenu = menu[i].split("~"); 
			var oname = thisMenu[0];
			var thisOname = new Element('span', {'id': 'qvBtn' + i}).injectInside(optDiv);
			thisOname.innerHTML=oname +":"; 
			var thisSel = new Element('select', {'name': oname, 'id':'qvSel' + i}).injectInside(optDiv);
			for (j=1;j<thisMenu.length;j++){
				var value = thisMenu[j];
				var option = document.createElement("option");
				thisSel.setAttribute("value",thisMenu[j]);
				thisSel.appendChild(option); 
				option.innerHTML=value; 
			} 
		} 
	} ,
	
	hideQvBtn: function(){
	  this.qvBtn.style.visibility='hidden';
	  if(this.qvBtn) this.qvBtn.dispose();
	},
	
	closeQv: function(){ 
		if (!this.qvShell) return;
		var fadeOutFx = new Fx.Tween('qvShell', { property:'opacity', duration: 600}).start(1,0);
		this.hideQvBtn();
		if ($('qvShell')){$('qvShell').dispose();this.qvShell=false;}
	}
	
});
window.addEvent('domready', function(){new mssQv();});
// ###### end mssQv Class  #######
