//Reload sothebys.com to www.sothebys.com
/*
 * v 1.0.3 
 * 1/13/2010
 * Vadym Ustymenko 
 * - decreased file size by rewriting some functions and making code more user-friendly
 * - Add support for loading dynamic scripts with both letters and numbers
 * - added event removal on page unload to handle memory leaks
 * 
 * v 1.0.4
 * 1/14/2010
 * Bernie Cultess
 * - Rewrote the loadFlash function to accept FLV and SWF files.
 * 
 * v 1.0.5
 * 1/25/2010
 * Bernie Cultess
 * - Removed showCafe
 * 
 * v 1.0.6
 * 2/17/2010
 * Bernie Cultess
 * - Fixed IE 8 issue with DD_belatedPNG_0.0.8a.js file.
 * 
 * v 1.0.7
 * 2/25/2010
 * Bernie Cultess
 * - Changed isSothebysHost() to fix issue where files were not loading on Omniture pages.
 * 
 * v 1.0.8
 * 3/3/2010
 * Bernie Cultess
 * - Updated wssLink function
 * 
 * v 1.0.9
 * 3/22/2010
 * Vadym Ustymenko
 * - excluded loading dynamic JS for some pages
 * 
 * v 1.0.10
 * 4/27/2010
 * Vadym Ustymenko
 * - added logic to load dynamic JS for specified pages
 * 
 * v 1.0.11
 * 4/28/2010
 * Vadym Ustymenko
 * - added logging function
 * */
if(location.hostname == "sothebys.com") location.hostname = "www.sothebys.com";

var Bid = {
 	Version: '1.0.10',
	Browser: {
	    isIE: !!(window.attachEvent && !window.opera),
		isIE6: !!(window.attachEvent && !window.opera && !window.XMLHttpRequest),
		isOpera: !!window.opera,
		isWebKit: navigator.userAgent.indexOf('AppleWebKit/') > -1,
		isGecko: navigator.userAgent.indexOf('Gecko') > -1 && navigator.userAgent.indexOf('KHTML') == -1,
		isMobileSafari: !!navigator.userAgent.match(/Apple.*Mobile.*Safari/)
	},
	OS:{
		isMac: navigator.platform.indexOf('Mac') > -1,
		isPC: navigator.platform.indexOf('Win') > -1
	},
	AJAX: {
		READY_STATE_UNINITIALIZED : 0,
		READY_STATE_LOADING : 1,
		READY_STATE_LOADED : 2,
		READY_STATE_INTERACTIVE : 3,
		READY_STATE_COMPLETE : 4,   	
		Loader : function(method,url,asynch,respHandle,params,onerror){
			this.method =     method;
			this.url =        url;
			this.asynch =     asynch; 
			this.respHandle = respHandle;
			this.params =     params; 
			this.onerror =    (onerror) ? onerror : this.defaultError;
			this.req =        null;
			this.loadXMLDoc(method,url,asynch,params);
		}
    },
	require: function(libraryName) {
    	if(Bid.Browser.isIE){
    		document.write('<script type="text/javascript" src="'+libraryName+'"><\/script>');
    	}else{
	    	try{
				var script = document.createElement("script");
				script.src = libraryName;
				script.type = "text/javascript";
				script.language = "JavaScript";
				//script.defer = true;
				var heads = document.getElementsByTagName("head");
				heads[0].appendChild(script);
			}catch(e){
				//inserting via DOM fails in Safari 2.0, so brute force approach
				document.write('<script type="text/javascript" src="'+libraryName+'"><\/script>');
			}
    	}
  	},
  	randomNum: parseInt((Math.random()+0.01) * 999999),
	load: function() {
	 	var hostPrefix = (Bid.isSothebysHost()) ? "" : "http://www.sothebys.com";
	 	var ast = document.getElementsByTagName("script"); // ast == allScriptTags
	 	var map = [];
	 	map["pt"] = "/includes/ajax/lib/prototype";
	 	map["builder"] = "/includes/ajax/src/builder";
		map["effects"] = "/includes/ajax/src/effects";
		map["dragdrop"] = "/includes/ajax/src/dragdrop";
		map["controls"] = "/includes/ajax/src/controls";
		map["slider"] = "/includes/ajax/src/slider";
		map["sound"] = "/includes/ajax/src/sound";
		map["jq126"] = "/includes/ajax/lib/jquery-1.2.6.min";
		map["jq130"] = "/includes/ajax/lib/jquery-1.3.min";
		map["jq132"] = "/includes/ajax/lib/jquery-1.3.2.min";
		map["jq142"] = "/includes/ajax/lib/jquery-1.4.2.min";
		map["carousel"] = "/includes/ajax/lib/carousel";
		map["tinymce"] = "/includes/ajax/tiny_mce/tiny_mce_src";
		map["controltabs"] = "/includes/ajax/src/controltabs";
		map["fabtabulous"] = "/includes/ajax/src/fabtabulous";
		map["fastinit"] = "/includes/ajax/src/fastinit";
		map["scal"] = "/includes/ajax/src/scal";
		map["tablekit"] = "/includes/ajax/src/tablekit";
		map["tooltip"] = "/includes/ajax/src/tooltip";
		map["unittest"] = "/includes/ajax/src/unittest";
		map["swf"] = "/includes/swfobject/swfobject";
	 	for (var i in ast) {
	 		var asts = ast[i].src; // asts == allScriptTagsSrc
		 	if (asts && asts.match(/bid\.js(\?.*)?$/)){
		 		var includes = asts.match(/\?.*load=([a-z0-9,]*)/);
		 		if (includes) {
		 			var include = includes[1];
		 			var libs = include.split(",");
		 			for(var j in libs){
			 			var path = map[libs[j]];
			 			if(typeof map[libs[j]] == 'string') Bid.require(hostPrefix + path+'.js');
			 		}
		 		}
		 	}
	 	}
	 	var mustLoadMap = [ {"src":"/includes/js/webtoolkit.utf8.js","url":[]},
	 						{"src":"/includes/js/flashfont_2.js","url":[]},
	 						{"src":"/includes/js/newcatlinks_980.js","url":
	 							["/app/live/event/EventSearchResults.jsp","/app/live/lot/LotDetail.jsp",
	 							"/app/live/dept/DepartmentGlobal.jsp","/app/live/dept/DepartmentSpecialists.jsp",
	 							"/app/paddleReg/paddlereg.do?dispatch=eventDetails","browse.sothebys.com",
	 							"/app/live/lot/LotResultsDetailList.jsp","/app/live/event.do?reqCode=videoViewer"]}];
	 	
	 	if(window.location.href.indexOf("/app/servlets/EventAdminServlet")!=-1)mustLoadMap=[];
	 	for (var j in mustLoadMap) {
	 		var o = mustLoadMap[j];
	 		if(o.url.length>0){
	 			for (var jj=0; jj<o.url.length; jj++){
	 				if( window.location.href.indexOf(o.url[jj]) != -1 ) Bid.require(hostPrefix + o.src);
	 			}
	 		}else{
	 			Bid.require(hostPrefix + o.src);
	 		}
	 	}
	 	if(Bid.Browser.isIE6){
	 		Bid.require(hostPrefix+ "/includes/js/DD_belatedPNG_0.0.8a.js")
	 	}
	},
	//Event management (includes removing events for memory leak problems)
	eventPool : null,
	addEvent : function(obj, type, fn) {
		if(this.eventPool == null){
			 this.eventPool = [];
			 Bid.addEvent(window, "unload", this.clearEvents);
		}
		if (typeof obj == "string") obj = document.getElementById(obj);		
		if (obj.addEventListener){
			obj.addEventListener(type, fn, false);
			this.eventPool.push({obj: obj, type: type, fn: fn});
		}else if(obj.attachEvent){
			obj.attachEvent('on' + type, function() { return fn.apply(obj, new Array(window.event));});
			this.eventPool.push({obj: obj, type: type, fn: fn});
		}
	},
	clearEvents : function(){
		if(Bid.eventPool != null && Bid.eventPool.length>0){
			for (var i = 0; i < Bid.eventPool.length; i++) {			
				var el = Bid.eventPool[i];
				if (el.obj.removeEventListener) el.obj.removeEventListener(el.type, el.fn, false);
	            else if (el.obj.detachEvent) el.obj.detachEvent("on" + el.type, el.fn);
			}
		}
		Bid.eventPool = null;
	},
	isSothebysHost : function(){
		return location.hostname.indexOf("sothebys.com") != -1 && location.hostname.indexOf("browse.sothebys.com") == -1;
	},
	getQueryString : function(frm){
		var str = "";
		var elsLen = frm.elements.length;
		for(var i=0; i<elsLen; i++){
	    	if(i != elsLen - 1){
	        	str += frm.elements[i].name+"="+encodeURIComponent(frm.elements[i].value)+"&";
			}else{
	    		str += frm.elements[i].name+"="+encodeURIComponent(frm.elements[i].value);
			}
		}
	  	return str;
	},
	getURLParameter : function(paramName, urlStr){
		paramName = paramName.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
		var regexS = "[\\?&]"+paramName+"=([^&#]*)";
		var regex = new RegExp(regexS);
		var myURL = (urlStr) ? urlStr : window.location.href;
		var results = regex.exec(myURL);
		if(results == null) return "";
			else return results[1];
	},
	findPosition : function(obj){
		var curleft = curtop = 0;
		if(obj.offsetParent){
			curleft = obj.offsetLeft;
			curtop = obj.offsetTop;
			while(obj = obj.offsetParent){
				curleft += obj.offsetLeft;
				curtop += obj.offsetTop;
			}
		}
		return [curleft,curtop]; 
	},
	triggerShowHide : function(id){
		var el = document.getElementById(id);
		if(el){
			if(el.style.display == "none"){ el.style.display = "";
			}else{ el.style.display = "none"; }
		}
	},
	//For popup window
	openWin: function(url,nL,nW,nH,nS,nT,nLo,nR){
		if (nS == '') {	nS = "0"; } // for scrollBar
		if (nT == '') { nT = "0"; } // for toolbar
		if (nLo == '') { nLo = "0"; } // for location bar
		if (nR == '') { nR = "0"; } // for resizable
		lP = (screen.width) ? (screen.width-nW)/2 : 0;
		tP = (screen.height) ? (screen.height-nH)/2 : 0;
		features = 'width=' + nW + ', height=' + nH + ', top=' + tP + ', left=' + lP + ', scrollbars=' + nS + ', toolbar=' + nT + ', location=' + nLo + ', resizable=' + nR;
		
		//console.log('width=' + nW + ', height=' + nH + ', top=' + tP + ', left=' + lP + ', scrollbars=' + nS);
	
		chkWin = window.open(url,nL,features);
		chkWin.focus();
		if (chkWin.opener == null){
			chkWin.opener = self;
			chkWin.focus();
		}
	},
	/* COOKIE FUNCTIONS */
	getCookieValue: function(offset){
	     var endstr = document.cookie.indexOf (";", offset);
	     if (endstr == -1)
	     endstr = document.cookie.length;
	     return unescape(document.cookie.substring(offset, endstr));
	},	
	getCookie: function(name){
	     var arg = name + "=";
	     var alen = arg.length;
	     var clen = document.cookie.length;
	     var i = 0;
	     while (i < clen){
		     var j = i + alen;
		     if (document.cookie.substring(i, j) == arg)
		     	return Bid.getCookieValue(j);
		     	i = document.cookie.indexOf(" ", i) + 1;
		     if (i == 0)
		     	break; 
	     }
	     return null;
	},
	setCookie: function(name, value){
	     var argv = Bid.setCookie.arguments;
	     var argc = Bid.setCookie.arguments.length;
	     var expires = (argc > 2) ? argv[2] : null;
	     var path = (argc > 3) ? argv[3] : null;
	     var domain = (argc > 4) ? argv[4] : null;
	     var secure = (argc > 5) ? argv[5] : false;
	     document.cookie = name + "=" + escape (value) +
	     ((expires == null) ? "" : ("; expires=" + expires.toGMTString())) +
	     ((path == null) ? "" : ("; path=" + path)) +
	     ((domain == null) ? "" : ("; domain=" + domain)) +
	     ((secure == true) ? "; secure" : "");
	},
	deleteCookie: function(name){
	     var argv = Bid.deleteCookie.arguments;
	     var argc = Bid.deleteCookie.arguments.length;
	     var path = (argc > 1) ? argv[1] : null;
	     var domain = (argc > 2) ? argv[2] : null;
	     var secure = (argc > 3) ? argv[3] : false;
	     var exp = new Date();
	     exp.setTime (exp.getTime() - 1000000000);
	     var cval = Bid.getCookie(name);
	     document.cookie = name + "=" + cval + "; expires=" + exp.toGMTString() +
	     ((path == null) ? "" : ("; path=" + path)) +
	     ((domain == null) ? "" : ("; domain=" + domain)) +
	     ((secure == true) ? "; secure" : "");
	},
	/* Make relative links absolute
	for (https) pages on the secure web server */
	httpLink: function(addr) {
		currentUrl = window.top.location.href;
		currentUrlArray = currentUrl.split(':');
		protocol = currentUrlArray[0];
		addressArray = currentUrlArray[1].split('/');
		host = addressArray[2];
		
		link = "http://" + host + addr;
		
		window.top.location.href = link;
	},
	
	/* Make relative links absolute
	for (http) pages on the secure web server */
	httpsLink: function(addr) {
		currentUrl = window.top.location.href;
		currentUrlArray = currentUrl.split(':');
		protocol = currentUrlArray[0];
		addressArray = currentUrlArray[1].split('/');
		host = addressArray[2];
		
		link = "https://" + host + addr;
		
		window.top.location.href = link;
	},
	
	// Switch for WSS/Omniture
	wssLink: function() {
		var lotSearchField = document.getElementById('lotSearchField'); 		
		if(lotSearchField.value == 'Enter Keyword or Sale #' || lotSearchField.value == ""){
			alert('Please enter your search keyword!');
			return false;
		}
		else {
			if (window.location.hostname == 'www.sothebys.com' || window.location.hostname == 'browse.sothebys.com') {
				window.location.href='http://browse.sothebys.com/?q='.concat(lotSearchField.value);
			} else {
			    window.location.href='http://stage.browse.sothebys.com/?q='.concat(lotSearchField.value);
			}
			
		}
		return true;
	},

	hide: function(elID) {
	    var el = document.getElementById(elID);
	    el.style.display = "none";
	},
	show: function(elID) {
	    var el = document.getElementById(elID);
  		el.style.display = "block";
	},
	applyHttpsLinkBridge : function(){return;//TO DO
		if(Bid.Browser.isIE){
			var allLinks = document.getElementsByTagName("A");
			var securePages = ["/app/transactions/",
							   "/app/account/",
							   "/app/absentee/",
							   "/app/servlets/RegistrantServlet",
							   "/app/common/security/RegistrantEdit.jsp",
							   "/app/paddleReg/",
							   "/app/global/",
							   "/app/servlets/OrderCartServlet",
							   "/app/live/order/OrderShippingForm.jsp"];
			//alert(allLinks.length);
			for(var i=0; i<allLinks.length; i++){
				var link = allLinks[i];
				for(var j=0; j<securePages.length; j++){
					var page = securePages[j];
					
					if(link.href.indexOf(page) != -1 && link.href.indexOf("javascript:") == -1){
						//alert(link.href);
						var href = link.href.replace("http://","https://");
						link.onclick = function(){
								window.location.href = href;
								return false;
							}
						//link.href = "javascript:void(0);Bid.httpsLink('"+link.href+"')";
					}
				}
			}
		}
	},
	loadFlash : function(url,c,w,h,ver,vid) {
		if(w == '') { w = '100%' };
		if(h == '') { h = '100%' };
		var flashvars = {};
		var params = {};
		if(vid == ''){vid = null; } else { flashvars.vidpath = vid + '?rand=' + Bid.randomNum; }
		params.scale = "showall";
		params.wmode = "transparent";
		params.allowfullscreen = "true";
		params.allowscriptaccess = "sameDomain";
		params.salign = "lt";
		var attributes = {};
		attributes.id = "flash_file";

		var file = url + '?rand=' + Bid.randomNum;
		swfobject.embedSWF(file,c,w,h,ver,"/includes/swfobject/expressInstall.swf",flashvars,params,attributes);
	},
	loadVideo : function(url,c,w,h,ver,vid) {
		var player = url + '?rand=' + Bid.randomNum;
		var movie = vid + '?rand=' + (Bid.randomNum * 2);
		swfobject.embedSWF(player,c,w,h,ver,"/includes/swfobject/expressInstall.swf",{
			config: "{'clip': '"+ movie +"'}}"
		}); 
	},
	doClear : function(el) {
	    if (el.defaultValue==el.value) {
	        el.value = "";
	    }
	},
	log : function(s,type){
		if(Bid.Browser.isGecko && window.console){
			if(typeof type == "string"){
				switch(type){
					case "error" : console.error(s); break;
					case "warn" : console.warn(s); break;
					case "info" : console.info(s); break;
					case "debug" : console.debug(s); break;
					case "start" : console.time(s); break;
					case "end" : console.timeEnd(s); break;
					default : console.log(s); break;
				}
			}else{
				console.log(s);
			}
		}
	}
}

Bid.load();
Bid.addEvent(window,"load",Bid.applyHttpsLinkBridge);

Bid.AJAX.Loader.prototype = {
	  loadXMLDoc:function(method,url,asynch,params){       	      
	      if(window.XMLHttpRequest){//Mozilla-based browsers
	          this.req = new XMLHttpRequest();      
	      }else if(window.ActiveXObject){//Internet Explorer
	          this.req = new ActiveXObject("Msxml2.XMLHTTP");
	          if(!this.req){
	              this.req = new ActiveXObject("Microsoft.XMLHTTP");
	          }
	      }	      
	      if(this.req){//test for null request
	          if(method.toLowerCase() != "post"){
	              this.initReq(method,url,asynch);
	          }else{//POSTed data
	              var args = arguments[3];
	              if(args != null && args.length > 0){
	                  this.initReq(method,url,asynch,args);
	              }
	          }
	      }else{
	          alert("Your browser does not permit the use of all "+
	                "of this application's features!");
	      }   
	    },
	    initReq:function(method,url,asynch,args){       
	      try{
	          //Specify the function which will handle HTTP response
	          var loader = this;
	          this.req.onreadystatechange = function(){                               
	              loader.onReadyState.call(loader);
	          }
	          this.req.open(method,url,asynch);
	          //POSTed data
	          if(method.toLowerCase() == "post"){
	              this.req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
	              this.req.send(arguments[3]);   
	          }else{
	              this.req.send(null);
	          }
	      }catch (errv){
	          alert("The application cannot contact the server at the moment. Error details: "+errv.message);
	      }       
	    },
	    onReadyState:function(){
	      var req = this.req;
	      var ready = req.readyState;
	      if(ready == Bid.AJAX.READY_STATE_COMPLETE){       
	           var httpStatus = req.status;
	           if(httpStatus == 200 || httpStatus == 0){
	               this.respHandle.call(this);              
	           }else{
	               this.onerror.call(this);
	           }
	      }
	  },
	  defaultError:function(){
	      alert("error fetching data!"
	      +"\n\nreadyState:"+this.req.readyState
	      +"\nstatus: "+this.req.status
	      +"\nheaders: "+this.req.getAllResponseHeaders());
	  }
}
Number.prototype.toDecimals = function(n){
    n = (isNaN(n))? 2 : n;
    var nT = Math.pow(10,n);
    function pad(s){
        s = s||'.';
        return (s.length>n)? s : pad(s+'0');
    }
    return (isNaN(this)) ? this : (new String(Math.round(this*nT)/nT)).replace(/(\.\d*)?$/,pad);
}
String.prototype.trim = function(){
	return (this.replace(/^\s+/,'').replace(/\s+$/,''));
}
String.prototype.endsWith = function(str){
	return (this.length - str.length) == this.lastIndexOf(str);
}
Array.prototype.removeArrayItems = function(itemsToRemove){//alert("test")
	var j;
	for(var i=0; i<itemsToRemove.length; i++){
		j=0;
		while(j<this.length){
			if(this[j]==itemsToRemove[i]){
				this.splice(j,1);
			}else{
				j++;
			}
		}
	}
}

/*Redirect to new page */
function redirectPage(path) {
	window.location.href = path;
}


//add CSS
document.writeln("<style type='text/css' media='screen'>");
//for files to work on shareholder and silverpop - add sothebys domain
document.writeln("@import '"+((Bid.isSothebysHost())?"":"http://www.sothebys.com")+"/includes/css/bid.css';");
if (Bid.Browser.isIE)
	document.writeln("@import '"+((Bid.isSothebysHost())?"":"http://www.sothebys.com")+"/includes/css/ie.css';");
if (Bid.Browser.isWebKit)
	document.writeln("@import '"+((Bid.isSothebysHost())?"":"http://www.sothebys.com")+"/includes/css/safari.css';");
if (Bid.Browser.isWebKit && Bid.OS.isMac)
	document.writeln("@import '"+((Bid.isSothebysHost())?"":"http://www.sothebys.com")+"/includes/css/safari_mac.css';");
document.writeln("</style>");

/* ------------------------------FOR NAVIGATION-----------------------------*/
function highlightOn() {
	var subNavExplore = document.getElementById("subNavExplore");
	var subNavDept = document.getElementById("subNavDept");
	var subNavMy2 = document.getElementById("subNavMy2");	
	if(typeof section != "undefined" && section != null && subsection != null) {
			if(section == 'explore' && subsection == 'auction calendar')
				subNavExplore.className = "calendar";
			if(section == 'explore' && subsection == 'auction results')
				subNavExplore.className = "results";
			if(section == 'explore' && subsection == 'sold lot archive')
				subNavExplore.className = "sla";
			if(section == 'explore' && subsection == 'live auction feed')
				subNavExplore.className = "webcast";
			if(section == 'explore' && subsection == 'videos')
				subNavExplore.className = "video";
			if(section == 'dept' && subsection == 'departments')
				subNavDept.className = "dept";
			if(section == 'dept' && subsection == 'other services')
				subNavDept.className = "services";
			if(section == 'dept' && subsection == 'publications')
				subNavDept.className = "catalogue";
			if(section == 'dept' && subsection == 'related businesses')
				subNavDept.className = "business";
			if(section == 'dept' && subsection == 'about us')
				subNavDept.className = "about";
			if(section == 'my' && subsection == 'client')
				subNavMy2.className = "clientprof";
			if(section == 'my' && subsection == 'communication')
				subNavMy2.className = "commpref";
			if(section == 'my' && subsection == 'transaction')
				subNavMy2.className = "auctionactivities";
	}
}
Bid.addEvent(window,'load',highlightOn);
/* ------------------------------END NAVIGATION-----------------------------*/


/*---------------------------FOR Sotheby's Cafe--------------------------
function showCafe(url) {
	if(url != null) {
		if(Bid.Browser.isIE){
			Bid.openWin(url+'/cafe/index.html','Cafe',740,645,'1','',''); return false;
		} else {
			Bid.openWin(url+'/cafe/index.html','Cafe',730,645,'1','',''); return false;
		}
	} else {
		if(Bid.Browser.isIE){
			Bid.openWin('/cafe/index.html','Cafe',740,645,'1','',''); return false;
		} else {
			Bid.openWin('/cafe/index.html','Cafe',730,645,'1','',''); return false;
		}		
	}
}*/


/* ---------------FOR OLD SITE TEMPORARY FIX-------------------------*/
function openWin(url,name,features){
	chkWin = window.open(url,name,features);
	chkWin.focus();
	if (chkWin.opener == null){
		chkWin.opener = self;
		chkWin.focus();
	}
}
//window.wssLink = window.Bid.wssLink;

/* WEBSIDESTORY CODE HBX2.0 (Universal)
COPYRIGHT 1997-2005 WEBSIDESTORY,INC. ALL RIGHTS RESERVED. U.S.PATENT No. 6,393,479B1. MORE INFO:http://websidestory.com/privacy */

var _hbEC=0,_hbE=new Array;function _hbEvent(a,b){b=_hbE[_hbEC++]=new Object();b._N=a;b._C=0;return b;}
var hbx=_hbEvent("pv");hbx.vpc="HBX0200u";hbx.gn="ehg-sothebys.hitbox.com";

/* WEBSIDESTORY CODE HBX2.0 (Universal)  CONTINUES IN FOOTER SECTION */
