/*
 	External Utility scripts 
	© 2008, Manheim Auctions
*/

/*  Selects from a single Select All checkbox an array of Checkboxes that all have an 
	identical ID that is supplied to the script */
function selectAllCheckboxes(itemID, controlID) {
	boxes = document.getElementsByName(itemID);
	count = boxes.length;
	flag = controlID.checked;
	for (i = 0; i < count; i++) {
		boxes[i].checked = flag;
	}
}

/* Clears and resets the Select All checkbox if any member checkbox is unchecked */
function clearSelectAll(controlID) {
	control = document.getElementsByName(controlID);
	flag = control[0].checked;
	if (flag) {
		control[0].checked = 0;
	}
}

/* Opens an Alert popup to display vehicle VIN with extra alert text, if it is supplied */
function showvin(fullvin, alertText) {
	if (!(alertText)){
		str = "Full VIN: " + fullvin;
		alert(str);
	} else {
		str = alertText + "\n\nFull VIN: " + fullvin;
		alert(str);
	}
}

windowFlag = 0;

/* Opens a non-scrollable window with the specified width and height in the center of the screen */
function openWindow(URL, wide, high, windowID){
    scrnX = screen.availWidth;
    scrnY = screen.availHeight;
    leftPos = (scrnX - wide)/2;
    topPos = (scrnY - high)/2;
    str = "status=no,toolbar=no,scrollbars=no,resizable=no,width=" + wide + ",height=" + high + ",screenX=" + leftPos + ",screenY=" + topPos + ",left=" + leftPos + ",top=" + topPos;
	if (windowFlag && !(dialog.closed)){
		dialog.close();
	}
	dialog = window.open(URL,windowID,str);
	windowFlag = 1;
}

/* Opens a scrollable window with the specified width and height in the center of the screen */
function openScrollingWindow(URL, wide, high, windowID){
    scrnX = screen.availWidth;
    scrnY = screen.availHeight;
    leftPos = (scrnX - wide)/2;
    topPos = (scrnY - high)/2;
    str = "status=no,toolbar=no,scrollbars=yes,resizable=no,width=" + wide + ",height=" + high + ",screenX=" + leftPos + ",screenY=" + topPos + ",left=" + leftPos + ",top=" + topPos;
	if (windowFlag && !(dialog.closed)){
		dialog.close();
	}
	dialog = window.open(URL,windowID,str);
	windowFlag = 1;
}

/*  Ad Manager Vehicle Registration confirmation popup */
function selectVehicle(year, makeModel, fullvin, form){
	str = "Are you sure you want to register this\n" + year + " " + makeModel + " with a VIN of\n" + fullvin + "?";
	if (confirm(str)){
		document.forms[form].submit();
	}
}

/*  Ad Manager Lane Registration confirmation popup */
function selectLane(year, makeModel, auction, lane, date, form){
	str = "Are you sure you want to register this " + year + "\n" + makeModel + " to " + auction + "\nfor Lane/Run " + lane + " for sale date " + date +"?";
	if (confirm(str)){
		document.forms[form].submit();
	}
}

/* Delete Object confirmation popup */
function confirmDelete(object, form){
	str = "Are you sure you want to delete this " + object + "?";
	if (confirm(str)){
		document.forms[form].submit();
	}
}

/* Generic confirmation popup */
function confirmMessage(msg, form){
	if (confirm(msg)){
		document.forms[form].submit();
	}
}

/* Prints the concatenated value of two passed form fields to a page object specified by ID */
function printFormText(sourceForm, sourceField0, sourceField1, targetID)	{
	formPointer = document.forms[sourceForm];
	document.getElementById(targetID).innerHTML = formPointer.elements[sourceField0].value + " " + formPointer.elements[sourceField1].value;
}

/* Show/Hide object functions */
function show(object) {
	if (document.getElementById && document.getElementById(object) != null) {
		document.getElementById(object).style.visibility = 'visible';
	}
}

function hide(object) {
	if (document.getElementById && document.getElementById(object) != null) {
		document.getElementById(object).style.visibility = 'hidden';
	}
}

function showHide(obj, status) {
	if (status == '1') {
		document.getElementById(obj).style.display = 'block';
	} else {
		document.getElementById(obj).style.display = 'none';
	}
}

/* Check for Flash Plugin */
var hasFlash = function(){
	var nRequiredVersion = 6;	
	
	if(navigator.appVersion.indexOf("MSIE") != -1 && navigator.appVersion.indexOf("Windows") > -1){
		document.write('<script language="VBScript"\> \non error resume next \nhasFlash = (IsObject(CreateObject("ShockwaveFlash.ShockwaveFlash." & ' + nRequiredVersion + '))) \n</script\> \n');
		/*	If executed, the VBScript above checks for Flash and sets the hasFlash variable. 
			If VBScript is not supported it's value will still be undefined, so we'll run it though another test
			This will make sure even Opera identified as IE will be tested */
		if(window.hasFlash != null){
			return window.hasFlash;
		};
	};
	
	if(navigator.mimeTypes && navigator.mimeTypes["application/x-shockwave-flash"] && navigator.mimeTypes["application/x-shockwave-flash"].enabledPlugin){
		var flashDescription = (navigator.plugins["Shockwave Flash 2.0"] || navigator.plugins["Shockwave Flash"]).description;
		return parseInt(flashDescription.charAt(flashDescription.indexOf(".") - 1)) >= nRequiredVersion;
	};
	
	return false;
}();

/* Show Flash Banner */
function showFlashBanner() {
	if (hasFlash){
		if (document.getElementById && document.getElementById('banner') != null) {
			document.getElementById('banner').style.visibility = 'visible';
		}
	}
}

/* new window functions */
function FAQ() { window.open('https://www.manheim.com/members/mmr/help.html','FAQ','toolbar=no,location=no,directories=no,status=no,menubar=no,resizable=yes,copyhistory=no,scrollbars=no,width=710,height=480'); }
function NewInternetMMRWindow() {window.open('https://www.manheim.com/members/internetmmr/','_blank','toolbar=no,location=no,directories=no,status=no,menubar=yes,resizable=yes,copyhistory=no,scrollbars=no','_blank'); }
function TRAMMR() {window.open('/members/trammr/','_blank','toolbar=no,location=no,directories=no,status=no,menubar=yes,resizable=yes,copyhistory=no,scrollbars=no','_blank'); }
function PDA() {window.open('pda.html','PDA','toolbar=no,location=no,directories=no,status=no,menubar=no,resizable=yes,copyhistory=no,scrollbars=no,width=450,height=400'); }
function MMRbot() {window.open('/members/mmrregistration/mmrbot.mmr','_blank','toolbar=no,location=no,directories=no,status=no,menubar=no,resizable=yes,copyhistory=no,scrollbars=yes','_blank'); }
function downloadMMRWindow() {window.open('https://www.manheim.com/members/mmr/mmrDownloads.mpl','_blank','toolbar=no,location=no,directories=no,status=no,menubar=no,resizable=yes,copyhistory=no,scrollbars=yes,width=860,height=560'); }
function newfeatures() {window.open('/members/sell/admanager-newfeatures.html','newfeatures','toolbar=no,location=no,directories=no,status=no,menubar=no,resizable=yes,copyhistory=no,scrollbars=yes,width=800,height=500'); }
function openWindowF(URL) {popupWin = window.open(URL, 'F', 'toolbar=no,status=yes,scrollbars=no,resizable=no,width=550,height=350'); }
function openWindowH(URL) {popupWin = window.open(URL, 'H', 'toolbar=no,location=no,directories=no,status=no,menubar=no,resizable=no,copyhistory=no,scrollbars=no,width=600,height=480'); }
function VIEW() {window.open('bid_popup.html','BidWatch','toolbar=no,location=no,directories=no,status=no,menubar=no,resizable=no,copyhistory=no,scrollbars=yes,width=426,height=560'); }
function showSurvey() {window.open('http://www.surveymonkey.com/s.aspx?sm=dhHi_2f2Efd5H72WSSdD3BAw_3d_3d','survey','resizable=1,width=500,height=540,scrollbars=no');}

function emailWindow () {
    var ref_url = document.referrer;
    var http_stat = ref_url.split(":");

    var ref_url2 = parent.document.URL;
    var http_stat2 = ref_url2.split(":");

    if(http_stat[0] == "https" || http_stat2[0] == "https"){
       //alert("open under https -- " + ref_url);
       window.open ('/members/email.mpl?context=/members/index.mpl?login=', 'ManEmailWindow', 'Height=400, width=550, toolbar=no, scrollbars=yes, directories=no, resizable=yes, location=no, menubar=no');
    } else {
       //alert("2 open under http -- " + ref_url2);
       window.open ('/email.mpl?context=/guests/index.mpl?login=', 'ManEmailWindow', 'Height=400, width=550, toolbar=no, scrollbars=yes, directories=no, resizable=yes, location=no, menubar=no');
    }
}

/* get url parameter */
function gup( name )
{
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( window.location.href );
  if( results == null )
    return "";
  else
    return results[1];
}

function NewInternetMMR( server ) {
	if (isLoggedIn()) {
	  NewInternetMMRWindow();
  } else {
		launchProduct(server, 'mymanheim','IMMR');
  }
}
function downloadMMR( server ) {
	if (isLoggedIn()) {
	  downloadMMRWindow();
  } else {
		launchProduct(server, 'mymanheim','DMMR');
	}
}
function launchLanesOnline( server ) {
	if (isLoggedIn()) {
	  launchLanesOnlineWindow(server);
  } else {
		launchProduct(server, 'mymanheim','LOL');
	}
}
function launchProduct(server, product, launch){
	document.location= (server == null ? '':server) + '/secureredirect?product=' + (product == null ? 'MANHEIM' : product) + (launch == null ? '' : '&launch=' + launch)                                                        ;
}

/* lanes online javascript */
//resize the LOL applet window
function launchLanesOnlineWindow( server ){
	if(screen.availHeight >= 625 && screen.availWidth >= 860){
		winH=625;
		winW=860;
	}else{
		winH=screen.availHeight-47;
		winW=screen.availWidth-10;
	}
	appH=winH-77;
	appW=winW-37;

	open((server == null ? '' : server) + '/secureredirect?product=lanesonline&w='+appW+'&h='+appH,'lanes','status,scrollbars,width='+winW+',height='+winH+',top=0,left=0,screenX=0,screenY=0');
}


function openECR(ecrUrl) {
	ecrWindow = window.open(ecrUrl, 'ecr_popup', 'toolbar=no,location=no,directories=no,status=no,menubar=no,resizable=no,copyhistory=no,scrollbars=yes,width=750,height=600');      
	ecrWindow.focus();
}

function openWindowSticker(wsUrl) {
	var wsWindow = window.open(wsUrl, 'ws_popup', 'toolbar=no,location=no,directories=no,status=no,menubar=no,resizable=yes,copyhistory=no,scrollbars=yes,width=765,height=750');
	wsWindow.focus();
}

function openVehicleHistory(vhUrl) {
	var vhWindow = window.open(vhUrl, '', 'toolbar=no,location=no,directories=no,status=no,menubar=no,resizable=no,copyhistory=no,scrollbars=yes,width=1024,height=735');      
	vhWindow.focus();
}
         
function openMMR(mmrUrl) {
	var mmrWindow = window.open(mmrUrl, 'InternetMMR', 'toolbar=no,location=no,directories=no,status=no,menubar=no,resizable=no,copyhistory=no,scrollbars=yes,width=600,height=550,left=0,top=0,screenX=0,screenY=0');
	mmrWindow.focus();
}

function getFullName() {
	var fullName = null;
	if (isLoggedIn()) {
		fullName = 'Manheim.com User';
  	var tktValues = unescape(getCookieValue('auth_tkt')).split('!');
  	if (tktValues != null && tktValues.length == 3) {		
   		var tktData = tktValues[2];
   		if (tktData != null && tktData.length > 0) {
  			var dataValues = tktData.split('|');
  			if (dataValues != null && dataValues.length > 0) {
  				var data = dataValues[0];
  				if (data != null && data.length > 0) {
  				  fullName = data;
  			  }
        }
			}
		}
	}
	return fullName;
}

function getCookieValue( cookieName ) {
    var cookieValue = '';
    if (document.cookie.length > 0) {
        var startIndex = document.cookie.indexOf(cookieName + '=');
        if (startIndex != -1) {
            startIndex = startIndex + cookieName.length + 1;
            var endIndex = document.cookie.indexOf(';', startIndex);
            if (endIndex == -1) {
                endIndex = document.cookie.length;
            }
            cookieValue = document.cookie.substring(startIndex, endIndex);
        }
    }
   
    return cookieValue;
}

function getCookieValueAsArray( cookieName, delim ) {
    var valueArray = new Array();
    var cookieValue = getCookieValue( cookieName );
    if ( cookieValue != null && cookieValue.length > 0 ) {
        valueArray = cookieValue.split(delim);
    }
   
    return valueArray;
}

function updateName( userFullName ) {
    if ( userFullName != null && userFullName.length > 0 ) {
        var welcomeElement = document.getElementById('utilWelcome');
        if ( welcomeElement != null ) {
            var fullNameElement = document.getElementById('fullName');
            if ( fullNameElement != null ) {
                fullNameElement.innerHTML = unescape(userFullName).replace(/\+/g, ' ');
                welcomeElement.style.display = 'inline';
            }
        }
        var loginElement = document.getElementById('utilLogin');
        if ( loginElement != null ) {
	         loginElement.style.display = 'none';
        }
				var logoutElement = document.getElementById('utilLogout');
        if ( logoutElement != null ) {
	         //logoutElement.style.display = 'inline';
        }
    }
}

/*
 *  This file should be used by all applications that have the 
 *  new PowerSearch free text search in their header.
 */

function searchByKeyword(e, formElement) {
	var code;
	if (!e) {
		e = window.event;
	}

	if (e.keyCode) {
		code = e.keyCode;
	} else if (e.which) {
		code = e.which;
	}

	if (code == 13) {
		return executeKeywordSearch(false);
	}

	return true;
}

function executeKeywordSearch(shouldSubmit) {
	if ( document.keywordSearchForm && document.keywordSearchForm.searchTerms ) {
	        var keywordForm = document.keywordSearchForm;
		var termsElement = keywordForm.searchTerms;
		var searchTerms = termsElement.value;
		searchTerms = searchTerms.replace(/^\s*/, "").replace(/\s*$/, "");

		if (searchTerms == '' || searchTerms == 'Vehicle Keyword Search') {
			alert('Search text is required.');
			termsElement.value = '';
			termsElement.focus();
			return false;
		} else {
			keywordForm.action = '/members/powersearch/keywordSearchResults.do';
            		
            		if ( shouldSubmit ) {
				keywordForm.submit();
			}
		}

		return true;
	}

	return false;
}

function isLoggedIn() {
	var loginCookieValue = getCookieValue('auth_tkt');
	return (loginCookieValue != null && loginCookieValue.length > 0);
}

/* Process launch parameter to popup application windows
 * Only process if logged in
 */
var launchParam = gup('launch');
if(launchParam != "" && isLoggedIn()){
	if(launchParam == "LOL"){
		launchLanesOnlineWindow();
	}else if(launchParam == "IMMR"){
		NewInternetMMRWindow();
	}else if(launchParam == "DMMR"){
		downloadMMRWindow();
	}
}


/*
 *  baseDomainString() is used to set the document.domain to get around cross-domain 
 *  scripting which happens with subdomains. This is being added to make the Control.Modals
 *  work on Simulcast and myAccount but can be used for other scripting across windows.
 */

function baseDomainString(){
	e = document.domain.split(/\./);
	if(e.length > 1) {
		return(e[e.length-2] + "." +  e[e.length-1]);
	} else {
		return(document.domain);
	}
}
document.domain = baseDomainString();


/*
 * Class for use with Manheim.com rotating image panel.  See the sapphire content editing help document
 * for the html template to be used with this class.
 */
RotatingImagePanel = function(element_id, options) {
  this.element = $(element_id);
  this.rotating = true;
  this.number_of_images = this.element.select('.main_image_panel .main_image').length
  this.options = options;

	this.auto_rotate_ads([0, 1, 2, 3, 0]);
	
	this.element.select('.thumb_off').each(function(image, image_number) {
		Event.observe(image, 'click', function() { this.show_ad(image_number); }.bind(this));
	}.bind(this));
	Event.observe(this.element, 'click', function() { this.rotating = false; }.bind(this));
};

RotatingImagePanel.prototype = {
  show_ad : function(ad_number) {
    this.element.select('.main_image_panel .main_image').each(function(anchor, anchor_number) {
      if (anchor_number == ad_number) { anchor.addClassName("shown"); } else { anchor.removeClassName("shown"); }
    });
    
    this.element.select('.thumbnail_panel .thumbnail').each(function(promo_thumb_div, thumb_div_number) {
      if (thumb_div_number == ad_number) {
        promo_thumb_div.addClassName("shown");
      } else {
        promo_thumb_div.removeClassName("shown");
      }
    });
  },
  
	auto_rotate_ads : function(ad_numbers) {
	  if (!this.rotating) return;
	  
	  this.show_ad(ad_numbers.shift());
	  
	  if (ad_numbers.length > 0) {
			var _ = function () { this.auto_rotate_ads(ad_numbers); }.bind(this).delay(this.options.auto_rotate_interval_in_seconds);
			// _ is for syntax - JS won't let you declare an anonymous function without doing something with it
		}
	}
};

function wtClickTrack(url, title, actionId, event) { 
	dcsMultiTrack('DCS.dcsuri', 'click:' + url, 'WT.ti', 'Click:' + title, 'WT.z_actionId', actionId, 'WT.z_event', event, 'WT.dl', '999', 'DCS.dcsqry', '', 'WT.si_n', '', 'WT.si_p', '', 'WT.cg_n', '', 'WT.cg_s', '', 'WT.z_search_type', '', 'WT.z_search_criteria', '', 'WT.tx_e', '', 'WT.oss_r', '', 'DCSext.pf', '', 'DCSext.pfv', '', 'DCSext.sct', ''); 
	DCS.dcsuri=WT.ti=WT.dl=WT.z_actionId=WT.z_event=''; 
}
