var doWatchLot;
var doSaveLot;
var doSetNotify;
var onLotDetailsPage = (/\/auction-lot\//).test(window.location.href);


if (onLotDetailsPage) {
	jQ.fn.hasScrollBar = function() {
		//note: clientHeight= height of holder
		//scrollHeight= we have content till this height
		var _elm = jQ(this)[0];
		var _hasScrollBar = false; 
		if ((_elm.clientHeight < _elm.scrollHeight) || (_elm.clientWidth < _elm.scrollWidth)) {
			_hasScrollBar = true;
		}
		return _hasScrollBar;
	};
}

function closeIt() {
	jQ("#rfaTYContent").fadeOut("slow",function(){
		jQ("#mask").fadeOut("slow");
	});
}


function setNotify() {
	  var	method = "saveReminderNotification",
		notification = jQ("input[name='notification']:checked").val(),
		notificationMinutes = jQ("#notificationMinutes").val(),
		approvalRef = jQ("input[name='approvalRef']").attr("value");

	  notification ? notification = 1 : notification = 0;
	  
	  doWatchLot = jQ.getJSON(
		  '/lib/jQueryObj/jFineArtObj.cfc?wsdl',
			  { 
				 method : method,
				 notification : notification,
				 notificationMinutes : notificationMinutes,
				 approvalRef : approvalRef
			  },
		  function() {
			  jQ("#updateAlert").html("Alert added to your <a href='/myLive/myWatchedLots.cfm'>watched lots</a>.</span>");
			  closeIt();			  
		 }
	  );			
			  
	  return false;
}


function watchLot(lotRef,mID,wwwURL,mRef) {
      //abort previous ajax call for this method if its still running
      var j=jQ(this);
      var watchHTML="";
	  watchHTML += "<p class='saveLot left2 clearfix'>";
		 watchHTML += "<span>You are <a href='" + wwwURL + "/myLive/myWatchedLots.cfm'>watching this lot</a>.</span>";
		 watchHTML += "<span id='updateAlert' lotRef='"+lotRef+"' memberRef='"+mRef+"'>&nbsp;Set an <a href='javascript:void(0);'>email alert</a>.</span>";
	  watchHTML += "</p>";

      if (doWatchLot) 
         {
            doWatchLot.abort();
         }
      doWatchLot = jQ.getJSON(
         '/lib/jQueryObj/jFineArtObj.cfc?wsdl',
            { 
               method : 'watchLot',
               lotRef : lotRef,
               mID : mID
            },
            function(data)
               {
                  if(data!="")
                     {
                        alert(data);
                     }
                  else
                     {
                        jQ("#watchThisLot").html(watchHTML);
                     }
               }
        );
   }

function saveLot(lotRef,mID,wwwURL)
   {
      //abort previous ajax call for this method if its still running
      var j=jQ(this);
      var saveHTML="<p class='saveLot left2'>Lot Saved in <a href='" + wwwURL + "/features/viewArtistAlertGallery.cfm?savedLots=true&cache=false'>My Saved Lots</a></p>";
      if (doSaveLot) 
         {
            doSaveLot.abort();
         }
      doSaveLot = jQ.getJSON(
         '/lib/jQueryObj/jFineArtObj.cfc?wsdl',
            { 
               method : 'saveLot',
               lotRef : lotRef,
               mID : mID
            },
            function(data)
               {
                  if(data!="")
                     {
                        alert(data);
                     }
                  else
                     {
                        jQ("#saveMyLot").html(saveHTML);
                     }
               }
        );
   }

function showDetails()
   {
      var h=jQ(this).next(".fieldName").height();
      jQ(this).parent().animate({ height : h},500).children(".expand").removeClass("expand").addClass("hide").html("<a href='#'>- Hide</a>");
       
      return false;
   }        

function hideDetails()
   {
      jQ(this).parent().animate({ height : "26px"},500).children(".hide").removeClass("hide").addClass("expand").html("<a href='#'>+ Expand</a>");
       
      return false;
   }        

function showAddress() 
   {
      var $address=jQ("#locDetails");
      var j=jQ(this);
      var linkText =j.text();

      switch(linkText)
         {
            case "+ Show Location Details":
               j.html("<a href='##'>- Hide Location Details</a>");            
            break;
            
            case "- Hide Location Details":
               j.html("<a href='##'>+ Show Location Details</a>");
            break;
         }     
      $address.toggle(500);
      return false;
   }
   
function setExpand()
   {
      var j=jQ(this);
      var height =  j.height();
      if(height > 28) {
         j.parent().children(".expand").show("slow");
      }
   }

function closeModal()
   {  
      if(jQ("#bidIncrementsTable"))
         {
            var bidTable = jQ("#bidIncrementsTable");
            jQ("#bidInfo").append(bidTable);
            bidTable.css("display","none");
         }
      jQ("#modal").stop().fadeOut().remove();
      jQ("#opaque")
         .css({opacity:0})
         .fadeOut()
         .remove();
      jQ("#footerButtons").fadeIn("fast");
      jQ("#largePicFrame").stop().fadeOut().attr("src", "").css("marginLeft", "-9999px").css({
         width: 1,
         height: 1
      }).fadeIn("fast");
   }

function resizeIframe()
   {
      if(jQ(this).attr("src") == ""){return;}
      
      var newHeight = this.contentWindow.document.body.scrollHeight;
      var newWidth = this.contentWindow.document.body.scrollWidth+10;
      var newLeft = 485-(newWidth/2);
      var screenHeight = jQ(window).height();
      var newTop;

      if(screenHeight > newHeight)
         {
            newTop = (screenHeight/2)-(newHeight/2);
         }
      else
         {
            newTop = 0;
         }
         
      jQ("#modal").animate({
         height: newHeight,
         top: newTop
      }).animate({
         width: newWidth,
         left: newLeft
      }, function(){
         jQ("#largePicFrame").hide().css("marginLeft", 0).height(newHeight).width(newWidth).fadeIn("slow");
         jQ("#modal").removeClass("modalload");
      });   
   }

function modulize()
   {
      jQ("#container-inner").append("<div id='modal' class='modalload'></div>").append("<div id='opaque'></div>");
      jQ("#opaque")
         .css({opacity:0.5})
         .fadeIn();
      jQ("#modal").append("<img id='closeWindow' src='/wwwImages/lotDetails/icnCloseWindow.png' alt='icnCloseWindow' width='30' height='30'/>");
   }

function thumbClick()
   {  
      modulize();
      jQ("#modal").append('<iframe id="largePicFrame" src="" scrolling="no"></iframe>');
      var src = this.id;
      jQ("#largePicFrame").attr("src", src);
      jQ("#footerButtons").fadeOut("fast");
      jQ("div#modal").addClass("modalload").fadeIn();
      jQ("#largePicFrame").load(resizeIframe);
   }

function showIncrements()
   {
      var bidTable = jQ("#bidIncrementsTable").clone();
      modulize();
      jQ("#modal img#closeWindow").hide();
      jQ("#modal").append(bidTable).css({"display":"block","height":"auto","width":"354px"}).removeClass("modalload");
      bidTable.css("display","block");
   }

function thumbBox()
   {
      jQ("#thumbBox").toggle("slow");
   }

function onBorder()
   {
      jQ(this).css(
         {
            borderColor: "#000"
         }
      );
   }
   
function offBorder()
   {
      jQ(this).css(
         {
            borderColor: "#ccc"
         }
      );
   }

function bidIncrement()
   {
      var bidText;
      bidText = jQ(this).text();
      jQ("input#bidAmt").val(bidText);
      jQ("#nextIncrements").animate({
               height: "0px",
               opacity: 0.0
            },500);
   }
function showRegInfo()
   {
	jQ("#bidReg ").fadeIn();
	jQ("#lb_bidAmt").attr("disabled", true);
	  return false;
   }
function hideRegInfo()
   {
      jQ("#results.lotDetails .description #bidInfo #bidReg ").fadeOut();
   }
function hidePopUp()
   {
      jQ("#popUp").fadeOut();
   }
function bidButton()
   {
	  var myVal = jQ("#bidAmt").val();
	  if(myVal == ""){return false;}
   }

   
jQ(function(){ 
   var hideDelay = 500;
   var hideDelayTimer = null;
   var beingShown = false;
   var shown = false;
   var time = 250;
   var distance = 10;
   
	
	//Google Analytics event tracking for when lightbox gallery is called
	jQ("#singleThumbBox a").delegate("img", "click", function(){
	_gaq.push(['_trackEvent', 'lightbox_link',  'clicked', 'lot_image_link']);
	});
	jQ("#singleThumbBox div.imgInfo").delegate("a", "click", function(){
	_gaq.push(['_trackEvent', 'lightbox_link',  'clicked', 'lot_view_more_link']);
	});
	
   
   jQ("#results.lotDetails  p.expand").live("click",showDetails);
   jQ("#results.lotDetails  p.hide").live("click",hideDetails);
   jQ("#results.lotDetails p.showDetails").click(showAddress);
   //jQ("#results.lotDetails div.descriptionText p.fieldName").each(setExpand);
   jQ("#modal #closeWindow, #opaque,#bidIncrementsTable img,#bidIncrementsTable p a").live("click",closeModal);
   	
   jQ("#bidIncrements").live("click",showIncrements);
   jQ("#nextIncrements li").live("click",bidIncrement);
   //jQ("#largePicFrame").live("load",resizeIframe);
   jQ(".imgInfo, #closeThumbBox").live("click", function() {
	   //thumbBox();
	   var thumbBoxTop = (jQ("#thumbBox center").length ? (jQ("#af_carouselThumbList").length ? 10 : 300) : 300);
	   jQ.colorbox({
			overlayClose: true,
			opacity: 0.5,
			transition: 'none',
			width: 460,
			top: thumbBoxTop,
			inline: true,
			href: "#thumbBox",
			close: '<span style="border: 1px solid black; font-weight:bold; font-size: 16px; padding:2px 6px; border-radius: 15px;"><span style="color: #444; font-size: 18px;">x</span><span>'
		});
		
		jQ(".caroufredsel_wrapper").css({"height": "101px"});
		jQ("#af_carouselThumbList").css({"left": "25px"});
   });
   jQ("#af_carouselThumbList li img").live("click", setActiveThumbInCarousel);
   jQ("#thumbBox ul li").hover(onBorder, offBorder);
   jQ("#bidAmt").val("").attr("autocomplete","off");
   jQ("div#nextIncrements").css("height","0px");
   jQ("#lb_bidAmt, input.lb_bidAmt").live("click", showRegInfo);
   jQ("#bidInfo #biddingWrapper #bidButton").live("click",bidButton);
   jQ("#bidReg p a").live("click",hideRegInfo);
   jQ("#popUp p.right2 a").live("click",hidePopUp);
   jQ("#placeAbsBid").click(function(){
      jQ("#popUp").fadeIn(time);
   });
   
   jQ("#bidAmt, #bidButton.bidAmt, div#nextIncrements").hover(function(){
      if (hideDelayTimer) 
         {
            clearTimeout(hideDelayTimer);
         }
      if (beingShown || shown)
         {
            return;
         }
      else 
         {
            beingShown = true;
            jQ("#results div#nextIncrements").animate({
               height: "130px",
               opacity: 1.0
            },time);
            shown = true;
         }
      },function(){
         if (hideDelayTimer) 
            {
               clearTimeout(hideDelayTimer);
            }
         hideDelayTimer = setTimeout(function () {
            hideDelayTimer = null;
            shown = false;
            jQ("#results div#nextIncrements").animate({
               height: "0px",
               opacity: 0.0
            },time);
         }, hideDelay); 
         beingShown = false;
      });
	  
	  jQ('#af_carouselThumbList').carouFredSel({
			prev: '#af_carouselPrevBtn',
			next: '#af_carouselNextBtn',
			auto: false,
			circular: false,
			infinite: false,
			width: 400,
			items: 3
		});	  
	  
		
});


function closeModals(e) {
	
	var target = e.target;
	var myId = target.id;
	
	if ((myId !== "lb_bidAmt") && (myId !== "bidButton") && (myId !== "secureBidLink") && (myId!=="placeAbsBidLink")) {
		
		if (jQ("#bidReg").is(":visible")) {
			jQ("#bidReg").fadeOut();
			jQ("#lb_bidAmt").attr("disabled", false);
		}
		
		if (jQ("#popUp").is(":visible")) {
			jQ("#popUp").fadeOut("slow", function() {
				jQ("#bidNotices").remove();
				jQ("#secureBid").show();
			});
		}
	}
}  
   
   
function buildToolTip(ver, jThis) {
	var toolTip = "", imgSrc, myText;
	
	//alert(ver);
	
	if (ver == "pricesVerified") {
		imgSrc = "/wwwImages/pricesVerified.png";
		myText = "This symbol indicates that this auction house has verified this price result.";
	} else {
		imgSrc = "/wwwImages/pricesNotVerified.png";
		myText = "This symbol indicates that this auction house has NOT verified this price result.";			
	}
	toolTip += '<img class="priceVerification" class="priceVerIcon" src="' + imgSrc + '" alt="pricesVerified" />';
	toolTip += '<p><strong>What is this symbol? </strong>' + myText + '</p>';

	jQ("#priceVerInfo").html('').html(toolTip);
	jThis.parent().append(jQ("#priceVerInfo"));
	if (jQ.browser.msie){
		jQ("#priceVerInfo").show();
	} else {
		jQ("#priceVerInfo").animate({opacity:"show"},"slow");
	}  

}

function showToolTip() {	
	var jThis=jQ(this), ver = jThis.attr("alt");
	if (jQ("#priceVerInfo").is(":visible") == false) buildToolTip(ver, jThis);
}

function hideToolTip() {
	if (jQ.browser.msie) {
		jQ("#priceVerInfo").hide();
	} else {
		jQ("#priceVerInfo").animate({opacity:"hide"},"fast");
	}
	jQ("#priceVerInfo").html('');     
}
   
jQ(function(){
   var pdNew, pd, pdFinal, logo, newImg, dtls, newPrice, newContent;
   pdNew="<div id='printable'></div>";
   logo=jQ("#logo").clone();
   if ( jQ("#singleThumbBox").length)
      {
   /* Lot Details Page! */
         newImg = jQ("#singleThumbBox").clone();
         newPrice = jQ("#priceInfo").clone();
         dtls=jQ("#lotcontent").clone();
         pdFinal = jQ(pdNew).append(newImg).append(newPrice).append(dtls);
      }
   else if ( jQ("#catalogCoverTop").length)
      {
   /* Auction Details Page! */
         newContent = jQ("#content").clone();
         pdFinal = jQ(pdNew).append(newContent);
      }
            
   
   jQ("body").append(pdFinal);
   jQ("#printable div, #printable span").each(function(){
      var newID;
      newID = jQ(this).attr("id");
      if (newID.length!==0){
         newID += "-printable";
         jQ(this).attr("id", newID);         
      }
   });
   jQ("#rfaTYContent input.submit").live("click", setNotify);
   jQ("body").live("click",closeModals);
   jQ("img.tooltip").hover(showToolTip, hideToolTip);
   // Replacing 'hover' with 'click' can helpful when debugging styling issues
   // jQ("img.tooltip").live("click", showToolTip);
	
	jQ(".af_bidIncrementButton").live("click", function(event) {
		var bidAmount = jQ(this).html().match(/\d+/)[0];
		
		jQ("#bidAmt").val(bidAmount);
		jQ("#bidButton").click();
		
	});

	if (onLotDetailsPage) {
		var lotTitleHeading = jQ("h1#lotTitle");
	   
		if (lotTitleHeading.hasScrollBar()) {
			jQ("#detailsHeader").removeAttr("style");
			lotTitleHeading.after('<span id="lotTitleToggler" class="collapsed"><span id="lotTitleTogglerText">show title</span></span>');
			
			var 	lotTitleToggler = jQ("#lotTitleToggler"),
					addThis = jQ("#addThis");
			
			lotTitleToggler.live("click", function() {
				
				var 	jqThis = jQ(this),
					isCollapsed = jqThis.hasClass("collapsed"),
					maxHeight = (isCollapsed ? "" : "23px"),
					text = (isCollapsed ? "hide title" : "show title");
				
				jQ("#lotTitleTogglerText").html(text);
				lotTitleHeading.css({"max-height": maxHeight});
				
				jqThis.toggleClass("collapsed");
								
				return false;
			});
		}
	}
   
});
