var qlHoverParent=null;

var qlHoverTemplate=new Template("\n"
+"  <div><a href=\"javascript:;\" onclick=\"showQL(event,this,'#{product_id}','#{dept_id}','#{item_num}');return false;\"><img src=\"/assets/images/quicklook/ql_view.gif\" alt=\"Quick View\" title=\"Quick View\" /></a></div>"
+"");

var qlWaitTemplate=new Template("\n"
+"  <div class=\"close\"><a href=\"javascript:;\" onclick=\"$('quick-look').hide();return false;\"><img src=\"/assets/images/quicklook/ql_close.gif\" width=\"11\" height=\"12\" /></a></div>\n"
+"  <div class=\"message\">#{message}</div>\n"
+"");

var qlTemplate=new Template("\n"
+"  <div class=\"close\"><a href=\"javascript:;\" onclick=\"hideQL();return false;\"><img src=\"/assets/images/quicklook/ql_close.gif\" width=\"11\" height=\"12\" /></a></div>\n"
+"  <div class=\"image\">\n"
+"    <a href=\"product?prodId=#{product_id}&deptId=&srchitm=#{search_item}&q=#{search_query}&qt=#{search_type}&lf=#{linked_from}\"><img src=\"http://images.daigger.com/view/1/daigger/product-images/noimage.gif/2/190/3/165/4/FFFFFF/5/daigger/product-images/#{product_img}\" /></a><br />\n"
+"	  <div class=\"product-name\"><a href=\"product?prodId=#{product_id}&deptId=&srchitm=#{search_item}&q=#{search_query}&qt=#{search_type}&lf=#{linked_from}\">#{product_name}</a></div>\n"
+"  </div>\n"
+"  <div class=\"tab\">Product Details</div>\n"
+"  <div class=\"tab-body\">\n"
+"    <div class=\"tab-body-content\">\n"
+"      #{product_desc}\n"
+"	   </div>\n"
+"  </div>\n"
+"  <div class=\"tab-footer\"></div>\n"
+"  <form name=\"form-quick-look\" id=\"form-quick-look\" method=\"post\" action=\"/cart/add\">\n"
+"  <div class=\"item-table\">\n"
+"    <table cellspacing=\"0\">\n"
+"      <thead>\n"
+"        <tr>\n"
+"          <td class=\"col-1\">Cat No</td>\n"
+"          <td class=\"col-2\">UOM</td>\n"
+"          <td class=\"col-3\">Daigger<br />Price</td>\n"
+"          <td class=\"col-4\">Qty to<br />Order</td>\n"
+"        </tr>\n"
+"      </thead>\n"
+"      <tbody>\n"
+"	     #{item_rows}\n"
+"      </tbody>\n"
+"	  </table>\n"
+"  </div>\n"
+"  <button type=\"submit\" title=\"Add to Cart\" class=\"submit\">Add to Cart</button>\n"
+"  </form>\n"
+"");

var qlItemTemplate=new Template("\n"
+"	     <tr>\n"
+"	       <td class=\"col-1\">#{item_alias}</td>\n"
+"	       <td class=\"col-2\">#{item_uom_desc}</td>\n"
+"		   <td class=\"col-3\">$#{item_price}</td>\n"
+"		   <td class=\"col-4\"><input type=\"text\" name=\"#{qty_field_name}\" id=\"#{qty_field_name}\" value=\"0\" maxlength=\"3\" class=\"qty\" /></td>\n"
+"         #{sub_item}\n"
+"       </tr>\n"
+"");

function hideQL(){
	$('quick-look').hide();
	showDropDown();
}
function showQL(event,e,prodId,deptId,itemNum,searchQuery,searchType,linkedFrom){
	if(prodId&&prodId.strip()!=''){
		var ql=$('quick-look');
		ql.update(qlWaitTemplate.evaluate({message: 'Loading product information...'}));
		ql.show();
		Position.clone(e, ql, { setWidth: false, setHeight: false, offsetTop: -350 });
		var offset=Position.cumulativeOffset(ql);
		var p=Position.page(ql);
		var cs=Client.viewportSize();
		if(p[1]<0)ql.setStyle({top:(offset[1]-p[1])+'px'});
		var ow=cs['width']-(offset[0]+375);
		if(ow<0)ql.setStyle({left:(offset[0]+ow-30)+'px'});
		hideDropDown(ql);
		new Ajax.Request('/ajax/ajax.QuickLook', {
			parameters: {
				p: prodId,
				d: deptId,
				i: (itemNum&&itemNum.strip()!=''?itemNum.strip():'')
			},
			onFailure: function(trans) {
				$('quick-look').update(qlWaitTemplate.evaluate({message: 'There was a problem.'}));
			},
			onSuccess: function(trans) {
				try{
					var x=trans.responseXML;
					var pId=x.getElementsByTagName('pmpid')[0].firstChild.data;
					var pName=x.getElementsByTagName('pmname')[0].firstChild.data;
					var pDesc=qlFormatDesc(x.getElementsByTagName('pttext')[0].firstChild.data);
					var pImg=x.getElementsByTagName('imgfile')[0].firstChild.data;
					var items=x.getElementsByTagName('Item');
					var itemNum='';
					var itemAlias='';
					var itemUom='';
					var itemUomDesc='';
					var itemLPrc=0;
					var itemDPrc=0;
					var itemCPrc=0;
					var itemPrc=0;
					var itemRows='';
					if(items&&items.length>0){
						for(var i=0;i<items.length;i++){
							isTitle=items[i].getElementsByTagName('sectionTitle').item(0).firstChild.data;
							if(isTitle.strip()=='false'){
								itemNum=items[i].getElementsByTagName('iditm').item(0).firstChild.data;
								itemDesc=items[i].getElementsByTagName('iddesc').item(0).firstChild.data;
								itemAlias=items[i].getElementsByTagName('itemalias').item(0).firstChild.data;
								itemUom=items[i].getElementsByTagName('iduom').item(0).firstChild.data;
								itemUomDesc=items[i].getElementsByTagName('uomdesc').item(0).firstChild.data;
								itemLPrc=parseFloat(items[i].getElementsByTagName('listprice').item(0).firstChild.data);
								itemDPrc=parseFloat(items[i].getElementsByTagName('discprice').item(0).firstChild.data);
								itemCPrc=parseFloat(items[i].getElementsByTagName('custprice').item(0).firstChild.data);
								itemPrc=itemLPrc;
								if(itemDPrc!=0&&itemDPrc<itemPrc)itemPrc=itemDPrc;
								if(itemCPrc!=0&&itemCPrc<itemPrc)itemPrc=itemCPrc;
								qtyFieldName=encodeURI(pId.strip()+' | '+itemNum.strip()+' | '+itemUom.strip()+' | '+itemAlias.strip()+' | '+itemDesc.strip()+' | |zz');
								subItem=(!searchType||searchType.strip()!='SUBST-REPL'||!linkedFrom||linkedFrom.strip()==''?'':'<input type="hidden" name="'+qtyFieldName+'-SUBST-ORIG" id='+qtyFieldName+'-SUBST-ORIG" value="'+linkedFrom.strip()+'" />');
								itemRows+=qlItemTemplate.evaluate({
										item_alias:itemAlias.strip(),
										item_uom_desc:itemUomDesc.strip(),
										item_price:formatCurrency(itemPrc),
										qty_field_name:qtyFieldName,
										sub_item:subItem
								});
							}
						}
					}
					$('quick-look').update(qlTemplate.evaluate({
							product_id:pId.strip(),
							product_name:pName.strip(),
							product_desc:(pDesc['isCut']?pDesc['description'].strip()+'<br /><br /><a href=\"product?prodId='+pId.strip()+'&deptId=&srchitm='+(itemNum&&itemNum.strip()!=''?itemNum.strip():'')+'&q='+(searchQuery&&searchQuery.strip()!=''?searchQuery.strip():'')+'&qt='+(searchType&&searchType.strip()!=''?searchType.strip():'')+'&lf='+(!linkedFrom||linkedFrom.strip()==''?'':linkedFrom.strip())+'\" class="textSmall">More Details...</a>':pDesc['description'].strip()),
							product_img:pImg.strip(),
							item_rows:itemRows,
							search_item:(itemNum&&itemNum.strip()!=''?itemNum.strip():''),
							search_query:(searchQuery&&searchQuery.strip()!=''?searchQuery.strip():''),
							search_type:(searchType&&searchType.strip()!=''?searchType.strip():''),
							linked_from:(!searchType||searchType.strip()!='SUBST-REPL'||!linkedFrom||linkedFrom.strip()==''?'':linkedFrom.strip())
					}));
				}catch(err){
					$('quick-look').update(qlWaitTemplate.evaluate({message: 'There was a problem.<br /><br />'+err}));
				}
			}
		});
	}
	Event.stop(event);
}

function qlMouseOver(e,prodId,deptId,itemNum){
	var qlh=$('quick-look-hover');
	qlHoverParent=e;
	
	qlh.update(qlHoverTemplate.evaluate({
			product_id:(prodId?prodId.strip():''),
			dept_id:(deptId?deptId.strip():''),
			item_num:(itemNum?itemNum.strip():'')
	}));
	qlh.show();
	Position.clone(qlHoverParent, qlh, { setWidth: false, setHeight: false, offsetLeft:($(e).getWidth()/2)-(qlh.getWidth()/2)-30, offsetTop:($(e).getHeight()/2)-(qlh.getHeight()/2)+20});
	Event.observe(qlh,'mouseout',qlMouseOut);
	Event.observe(qlHoverParent,'mouseout',qlMouseOut);
}

function qlMouseOut(event){
	var qlh=$('quick-look-hover');
	if(!Position.within(qlh,Event.pointerX(event),Event.pointerY(event))){
		Event.stopObserving(qlh,'mouseout',qlMouseOut);
		Event.stopObserving(qlHoverParent,'mouseout',qlMouseOut);
		qlHoverParent=null;
		qlh.hide();
	}
}

function qlFormatDesc(descOrig){
	var CUT_MIN=400;
	var CUT_START=200;
	var desc=new String(descOrig);
	desc=desc.strip().gsub('<!-- TRIM_POS -->','!-- TRIM_POS --!');
	desc=desc.strip().gsub('<!-- TRIM_POS_HIDE -->','!-- TRIM_POS_HIDE --!');
	desc=desc.strip().gsub('</tr>','!CRLF!');
	desc=desc.strip().gsub('<li>','!CRLF!');
	desc=desc.strip().gsub('</li>','!CRLF!');
	desc=desc.strip().gsub('</ul>','!CRLF!');
	desc=desc.strip().gsub('\t',' ');
	desc=desc.strip().stripTags();
	desc=desc.strip().gsub(' ',' ');
	
	var cutCancel=desc.indexOf('!-- TRIM_POS_HIDE --!');
	if(desc.length>CUT_MIN&&cutCancel<0){
		var cutManual=false;
		var cutPos1=-1;
		var cutPos2=0;
		var cutPos3=-1;
		
		cutPos1=desc.indexOf('!-- TRIM_POS --');
		if(cutPos1>=0){
			cutManual=true;
		}else{
			cutPos1=desc.indexOf('!CRLF!',CUT_START);
			desc=desc.strip().gsub('!CRLF!','      ');
			cutPos2=desc.indexOf('. ',CUT_START);
			cutPos3=desc.indexOf('.<',CUT_START);
			if(cutPos2<0||(cutPos3>=0&&cutPos3<cutPos2))cutPos2=cutPos3;
			if(cutPos1<0||(cutPos2>=0&&cutPos2<cutPos1))cutPos1=cutPos2;
			if(cutPos1<0)cutPos1=desc.indexOf('.',CUT_START);
			if(cutPos1<0)cutPos1=desc.indexOf(' ',CUT_START);		

			if(cutPos1>=0){
				var cutWord='';
				cutPos2=cutPos1;
				while(cutWord.strip()==''){
					cutPos2=desc.substring(0,cutPos2-1).lastIndexOf(' ');
					if(cutPos2<0)cutPos2=0;
					cutWord=desc.substring(cutPos2,cutPos1).strip();
				}
			}
		}

		if(cutPos1>=0&&cutPos2<cutPos1){
			if(cutManual){
				desc=descOrig.substring(0,descOrig.indexOf('<!-- TRIM_POS -->'));
				descOrig=descOrig.gsub(/<!--(.*)-->/i,'');
				desc=desc.gsub(/<!--(.*)-->/i,'');
			} else {
				var descTableCount=0;
				var descRowCount=0;
				var descColCount=0;
			
				descOrig=descOrig.gsub(/<!--(.*)-->/i,'');
				
				var wordCount=0;
				var cutWord=desc.substring(cutPos2,cutPos1+1).strip();
				cutPos3=desc.indexOf(cutWord);
				while(cutPos3>=0&&cutPos3<cutPos1){
					wordCount++;
					cutPos3=desc.indexOf(cutWord,cutPos3+1);
				}
				
				cutPos3=-1;
				while(wordCount>0) {
					cutPos3=descOrig.indexOf(cutWord,cutPos3+1);
					wordCount--;
				}
				
				desc=descOrig.substring(0,cutPos3+cutWord.length);
				for(cutPos1=desc.toLowerCase().indexOf('<table');cutPos1>=0;cutPos1=desc.toLowerCase().indexOf('<table',cutPos1+1))descTableCount++;
				for(cutPos1=desc.toLowerCase().indexOf('</table');cutPos1>=0;cutPos1=desc.toLowerCase().indexOf('</table',cutPos1 + 1))descTableCount--;
				for(cutPos1=desc.toLowerCase().indexOf('<tr');cutPos1>=0;cutPos1=desc.toLowerCase().indexOf('<tr',cutPos1+1))descRowCount++;
				for(cutPos1=desc.toLowerCase().indexOf('</tr');cutPos1>=0;cutPos1=desc.toLowerCase().indexOf('</tr',cutPos1+1))descRowCount--;
				for(cutPos1=desc.toLowerCase().indexOf('<td');cutPos1>=0;cutPos1=desc.toLowerCase().indexOf('<td',cutPos1+1))descColCount++;
				for(cutPos1=desc.toLowerCase().indexOf('</td');cutPos1>=0;cutPos1=desc.toLowerCase().indexOf('</td',cutPos1+1))descColCount--;
	
				for(var i=0;i<descColCount;i++)desc+='</td>';
				for(var i=0;i<descRowCount;i++)desc+='</tr>';
				for(var i=0;i<descTableCount;i++)desc+='</table>';
			}
		}
	}else{
		desc=new String(descOrig);
	}
	return $H({isCut:(desc.strip()!=descOrig.strip()),description:desc});
}