var fullImageURL = new Array();
var showFullSizeImages = true;
var selectedImageId = 0;
var magnifiedImages = new Array();

function showLargeImagesDiv(){
    //Set the XSL path
    var xslFile = "info.html";
    //Turn the XML string into an XML document
    var xmlDoc = returnXMLDocument(xml);
    var xslDoc = "";
    //Make an AJAX request to get the XSL
    new Ajax.Request(xslFile, {
        method: "get",
        parameters: "view=Search/lotImagesLargeXsl",
        onSuccess: function(transport){
            //Take the XSL string and make an XML document
            xslDoc = returnXMLDocument(transport.responseText);
            //Pass the XML and XSL documents and get the display content
            var content = getFormattedXMLContent(xmlDoc, xslDoc);
            //IF we don't get an error that browser is not supported
            if (content != "error:not supported") {
                //Show the div that the images will reside in
                $("viewLargeImages").style.display = "block";
                //Change the text to the View Large Images link
                $("changeTxtLink").innerHTML = message.hideLarge;
                //Change its URL to point to the Hide Images function
                $("changeTxtLink").href = "javascript:hideLargeImagesDiv();";
                //If Mozilla/Opera
                if (document.implementation && document.implementation.createDocument) {
                    //Apend the data
                    $("largeImageLocation").appendChild(content);
                }
                //IE
                else 
                    if (window.ActiveXObject) {
                        //Write the content
                        $("largeImageLocation").innerHTML = content;
                    }
                    else {
                        //Else its a non supported broswer.
                        $("largeImageLocation").innerHTML = message.unsupportedBrowser;
                    }
            }
            else //We have an error
            {
                alert(message.unsupportedBrowser);
            }
        }
    });
}

/**
 * This function hides the div with the large images and clears the content. It
 * also resets the text for the View Large Images link and its href.
 */
function hideLargeImagesDiv(){
    $("changeTxtLink").innerHTML = message.showLarge;
    $("changeTxtLink").href = "javascript:showLargeImagesDiv();";
    $("viewLargeImages").style.display = "none";
    $("largeImageLocation").innerHTML = "";
}

/**
 * Added for Lot detail getViewFinder thumb nail images
 */
function getImageDiv(controller, view, lot_ID, largeImage, title, imgUrl){
    var params = "lotId=" + lot_ID + "&selectedImage=" + largeImage + "&title=" + title + "&imgUrl=" + imgUrl;
    createInfoDivgetViewFinder(controller, view, params, false);
}

/**
 * This function is used to display the large Image on the left side of the lot detail pop-up page.
 */
function SetImage(i){
    document.mainimage.src = fullImageURL[i];
}

function showLargeImages(lotId, isOnSale){
    var d = new Date();
    var imagesURL = message.lotImagesAjax + "?lotId=" + lotId + "&isFullsize=true&isOnSale=" + isOnSale + "&d=" + d.getTime();
    var imageXslDoc = "";
    var imageXmlDoc = "";
    if (showFullSizeImages && $("lotLargeImages").innerHTML === "") {
        if (lotId !== "") {
            new Ajax.Request(message.lotImagesLargeXsl, {
                method: "get",
                onSuccess: function(transport){
                    imageXslDoc = transport.responseText;
                    //imageXslDoc = returnXMLDocument(imageXslDoc);
                    new Ajax.Request(imagesURL, {
                        method: "get",
                        onSuccess: function(xmlTransport){
                            imageXmlDoc = xmlTransport.responseText;
                            //imageXmlDoc = returnXMLDocument(imageXmlDoc);

                            if (imageXslDoc !== "" && imageXmlDoc !== "") {
                                var content = getFormattedXMLContent(imageXmlDoc, imageXslDoc);

                                if (content != "error: not supported") {
                                    if (showFullSizeImages) {
                                        showFullSizeImages = false;

                                        $("showImagesLink").innerHTML = message.hideLargeImages;
                                        $("showImagesLink2").innerHTML = message.hideLargeImages;
                                        $("lotLargeImages").style.display = "block";
                                        $("lotInfo").style.display = "block";

                                        if (document.implementation && document.implementation.createDocument) {
                                            //Apend the data
                                            $("lotLargeImages").appendChild(content);
                                        }
                                        //IE
                                        else {
                                            if (window.ActiveXObject) {
                                                //Write the content
                                                $("lotLargeImages").innerHTML = content;
                                            }
                                            else {
                                                //Else its a non supported broswer.
                                                $("lotLargeImages").innerHTML = message.unsupportedBrowser;
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    });
                }
            });
        }
    }
    else {
        if (showFullSizeImages) {
            showFullSizeImages = false;
            $("showImagesLink").innerHTML = message.hideLargeImages;
            $("showImagesLink2").innerHTML = message.hideLargeImages;
            $("lotLargeImages").style.display = "block";
            $("lotInfo").style.display = "block";
        }
        else {
            showFullSizeImages = true;
            $("showImagesLink").innerHTML = message.showLargeImages;
            $("showImagesLink2").innerHTML = message.showLargeImages;
            $("lotLargeImages").style.display = "none";
            $("lotInfo").style.display = "none";
        }
    }
}
function getViewFinder(imageId, lotId, isOnSale)
{
 	var isIE = !!document.all && !!window.attachEvent && !window.opera;
    selectedImageId = imageId;
    var d = new Date();
    var imgViewerURL = message.imageViewerAjax + "?selectedImage=" + imageId + "&lotId=" + lotId + "&isOnSale=" + isOnSale + "&d=" + d.getTime();
    createInfoDivPopup(imgViewerURL, "Search/imageViewer", "img=" + imageId, false, "get");
	if(isIE) {
    	// Slight delay to ensure images are loaded
    	setTimeout(function() { makeMagnified(imageId) }, 400);
    }
    else {
    	// Slight delay to ensure images are loaded
    	setTimeout(function() { MojoMagnify.init() }, 400);
    }
}
function setLargeImage(imageId, cur_image)
{
	var isIE = !!document.all && !!window.attachEvent && !window.opera;
 	$("imageViewerMainImage" + selectedImageId).style.display = "none";
	$("image"+selectedImageId).removeClassName('selected'); 
    selectedImageId = imageId;
    $("imageViewerMainImage" + selectedImageId).style.display = "block";
	$("image"+imageId).addClassName('selected'); 
	
	if(isIE) {
    	// Slight delay to ensure images are loaded
    	setTimeout(function() { makeMagnified(imageId) }, 400);
    }
    else {
    	// Slight delay to ensure images are loaded
    	setTimeout(function() { MojoMagnify.init() }, 400);
    }
	
}
/*
 *  IE Fix method for placement and Magnify.
 */
function makeMagnified(imageToShowId) {
	//alert(imageToShowId);
	var isIE = !!document.all && !!window.attachEvent && !window.opera;
	var imageId = "imageViewerMainImage" + imageToShowId;
	var makeMagnifiable = false;
	var imgRepoTop = "-40px";
	var imgRepoLeft = "-40px";
	 if(isIE) {
	    imgRepoTop = "0px"
	    imgRepoLeft = "0px"	
	 }
	
	if (magnifiedImages.length > 0) {
		//alert('has collection');
		var isInArray = false;
		for(var i = 0; i < magnifiedImages.length; i++) {
			if(magnifiedImages[i] == imageId) {
				isInArray = true;
				break;
			}
		}
		if(!isInArray) {
			//alert('not array');
			makeMagnifiable = true;
			magnifiedImages.push(imageId);
		}
	}
	else {
		//alert('new collection');
		makeMagnifiable = true;
		magnifiedImages.push(imageId);
	}
	if(makeMagnifiable) {
		//alert('make magnify');
		var img = $(imageId);
		
	    var zoomSrc = img.getAttribute("data-magnifysrc");
	    var opt = {
				full : img.getAttribute("data-magnifyfull") === "true",
				animate : img.getAttribute("data-magnifyanimate") === "true",
				imgWidth : img.getAttribute("data-magnify-width"),
				imgHeight : img.getAttribute("data-magnify-height")
			};
	    MojoMagnify.makeMagnifiable(img, zoomSrc, opt);
	    var parent = img.parentNode;
		with(img.style) {
			position = "absolute";
			left = imgRepoLeft;
			top = imgRepoTop;
		}
		with(parent.style) {
			position = "absolute";
			left = imgRepoLeft;
			top = imgRepoTop;
			width = img.offsetWidth+"px";
			height = img.offsetHeight+"px";
			overflow = "hidden";
			display = "block";
		}
	}
	else {
		//alert('magnified, just show');
		var img = $(imageId);
		var parent = img.parentNode;
		with(img.style) {
			position = "absolute";
			left = imgRepoLeft;
			top = imgRepoTop;
		}
		with(parent.style) {
			position = "absolute";
			left = imgRepoLeft;
			top = imgRepoTop;
			width = img.offsetWidth+"px";
			height = img.offsetHeight+"px";
			overflow = "hidden";
			display = "block";
		}
	}
}
function clearMagnified() {
	magnifiedImages = new Array();
}
function validateBid(fromForm) {
	var isBidValid = validateBidAmt($('max_bid').value, $('max_bid'));
	
	if(fromForm) {
		return isBidValid;
	}
	else {
		if(isBidValid)
		{
			$('submitBidForm').submit();
		}
	}
	return true;
}

function validateBidAmt(v, elm) {
	var iCurrentBid = parseInt($('cur_bid').value);
	var iBidAmt = parseInt(get_bid_inc(iCurrentBid));
	var iMinBidAmt = parseInt(iCurrentBid + iBidAmt);
	
	if(v.indexOf('.') >= 0)
	{
		var howManyDecimals = v.split('.');
		if(howManyDecimals.length > 2) { //If we have more than 1 decimal
			$('advice-common-before').innerHTML = message.invalidBidAmt;
			$('advice-common-before').style.display = 'block';
			$('max_bid').focus();
			return false;
		} 
		else { // 1 decimal found
			// check the number after the decimal
			if(howManyDecimals[1] !== null && howManyDecimals[1] !== '') {
				// If its .0 or .00 then trim it off and return true, for no error
				if(howManyDecimals[1] == "0" || howManyDecimals[1] == "00") {
					$(elm).value = howManyDecimals[0];
					if((($(elm).value - iCurrentBid) % iBidAmt) > 0) {
						$('advice-common-before').innerHTML = message.invalidBidInc+" $"+parseInt($('bidInc').value)+" "+$('currency').innerHTML+".";
						$('advice-common-before').style.display = 'block';
						$('max_bid').focus();
						return false;
					}
					return true;
				}
				else {
					// User tried to enter cents, return an error.
					$('advice-common-before').innerHTML = message.invalidBidAmt;
					$('advice-common-before').style.display = 'block';
					$('max_bid').focus();
				}
			}
			else {
				// User entered a 100., which is valid, ignore the decimal and fix value
				$(elm).value = howManyDecimals[0];
				if((($(elm).value - iCurrentBid) % iBidAmt) > 0) {
					$('advice-common-before').innerHTML = message.invalidBidInc+" $"+parseInt($('bidInc').value)+" "+$('currency').innerHTML+".";
					$('advice-common-before').style.display = 'block';
					$('max_bid').focus();
					return false;
				}
				return true;
			}
		}
	}
	else if(v.indexOf(',') >= 0) {
		$('advice-common-before').innerHTML = message.invalidBidAmt;
		$('advice-common-before').style.display = 'block';
		$('max_bid').focus();
		return false;
	}
	else if(v <= 0 || isNaN(v))	{
		$('advice-common-before').innerHTML = message.invalidBidAmt;
		$('advice-common-before').style.display = 'block';
		$('max_bid').focus();
		return false;
	}
	else if(((v - iCurrentBid) % iBidAmt) > 0) {
		$('advice-common-before').innerHTML = message.invalidBidInc+" $"+parseInt($('bidInc').value)+" "+$('currency').innerHTML+".";
		$('advice-common-before').style.display = 'block';
		$('max_bid').focus();
		return false;
	}
	else if(v < iMinBidAmt) {
		$('advice-common-before').innerHTML = message.lowBidAmtError+" $"+(parseInt($('bidInc').value) + parseInt($('cur_bid').value))+" "+$('currency').innerHTML+".";
		$('advice-common-before').style.display = 'block';
		$('max_bid').focus();
		return false;
	}
	$('advice-common-before').innerHTML = "";
	$('advice-common-before').style.display = 'none';
	
	$('bidInc').value = get_bid_inc(v); 
	$('bidInc_str').update(get_bid_inc(v)); 
	
	return true;
}

function current_bid( lot, h ) {
	var ajaxUrl = url+'carfinder-online-auto-auctions/ajax/current_bid/'+lot+'/'+h+'/';
	new Ajax.Request(ajaxUrl,
	{
		method: 'get',
		evalJSON: true,
		onSuccess: function(transport) {
			var result = transport.responseJSON;
			
			if($('current-bid') != null && $('current-bid') !== undefined) {
				$('current-bid').update(result.current_bid_str);
			} 
			if($('cur_bid') != null && $('cur_bid') !== undefined) {
				$('cur_bid').value = result.bid_now;
			}
			if($('max_bid') != null && $('max_bid') !== undefined) {
				$('max_bid').value = result.bid_now_bid;
				$('bidInc').value = result.bid_inc;
				$('bidInc_str').update(result.bid_inc_str);
			}
			if(result.sold==1) {
				window.location.reload();
			}
		},
		onFailure: function(){}, 
		onException: function(request, ex){}
	});		
}
function calculate( ) 
{
	var lot		= $('lot').value;
	var cond 	= $('cond').value;
	var price 	= parseInt($('max_bid').value);
	var vehtype = $('vehtype').value;
	var h 		= $('h').value;
	
	if(vehtype != 'M' && vehtype!='E' && vehtype!='R')
	{
		var shipping 	= $('shipping').value;
		var from_zip 	= $('from_zip').value;
		var to_zip 		= $('to_zip').value;
		var usa_port 	= $('usa_port').value;
		var country 	= $('country').value;
		var to_port 	= $('to_port').value;
		var yard		= $('yard').value;
		var border_crossing	= $('border_crossing').value;

		if (shipping=='D') {
			if (!isZipValid($('to_zip').value))
			{
				$('to_zip').focus();
				return false;
			}
		
		} else if (shipping=='B') {
			if(border_crossing === '') {
				return false;
			}
		} else if(shipping=='I') {
			if(to_port === '') {
				return false;
			}
			if(usa_port==='') {
				return false;
			}
		}
	  parameters = {lot:lot, cond:cond, price:price, from_zip:from_zip, to_zip:to_zip, vehtype:vehtype, h:h, shipping:shipping, usa_port:usa_port, country:country, to_port:to_port, yard:yard, border_crossing:border_crossing};
	} else {
	  parameters = {lot:lot, cond:cond, price:price, vehtype:vehtype, h:h, shipping:shipping};
	}
	if (price < 1)
	{
		$('max_bid').focus();
		return false;
	}

	var ajaxUrl = url+'carfinder-online-auto-auctions/ajax/calc/';
	new Ajax.Request(ajaxUrl,
	{
		method: 'get',
		evalJSON: true,
		parameters: parameters,

		onSuccess: function(transport) {
			docalc( transport.responseJSON, vehtype );
		},
		onFailure: function(){}, 
		onException: function(request, ex){}
	});		
	
	return true;
}

function docalc( calc, vehtype ) 
{
	if ( calc.total ) 
	{
/*		$('buyer_fee-container-label').style.display = "block";
		$('buyer_fee-container-value').style.display = "block";
		$('r_buyer_fee').update(calc.buyer_fee);

		$('gate-container-label').style.display = "block";
		$('gate-container-value').style.display = "block";
		$('r_gate').update(calc.gate);
		
		$('internet_bid_fee-container-label').style.display = "block";
		$('internet_bid_fee-container-value').style.display = "block";
		$('r_internet_bid_fee').update(calc.internet_bid_fee);
*/		
		$('r_copart_fee').update(calc.copart_fee);
		$('r_transaction_fee').update(calc.transaction_fee);
		$('r_total').update(calc.total);

		if(vehtype != 'M' && vehtype!='E' && vehtype!='R')
		{
			if (calc.shipping=='D' || calc.shipping=='B') {
				$('domestic-data-container').style.display = "block";
				$('r_domestic_price').update(calc.domestic_price);
				if(calc.domestic_place) {
					$('r_domestic_place').update(calc.domestic_place);
				}
			} else {
				$('domestic-data-container').style.display = "none";
			}
			if (calc.shipping=='I') {
				$('international-data-container').style.display = "block";
				$('r_usaport_price').update(calc.usaport_price);
				$('r_destport_price').update(calc.destport_price);
				$('r_yard').update(calc.yard_name);
				$('r_usaport').update(calc.usaport_name);
				$('r_usaport2').update(calc.usaport_name);
				$('r_destport').update(calc.destport_name);
			} else {
				$('interantional-data-container').style.display = "none";
			}
		}
	}
}
function subscribe() {
	var lot		= $('lot').value;
	var h 		= $('h').value;
	var type 	= $('type').value;
	var email 	= $('email').value;
	var phone 	= $('phone').value;
	
	if(type == 'email')
	{

	}

	$('d-subscribe-error').style.display = 'none';
	var ajaxUrl = url+'carfinder-online-auto-auctions/ajax/subscribe/';
	new Ajax.Request(ajaxUrl,
	{
		method: 'get',
		evalJSON: true,
		parameters: {lot:lot, type:type, h:h, email:email, phone:phone},

		onSuccess: function(transport) {
			result = transport.responseJSON
			if(result.error) {
				$('d-subscribe-error').update(result.error);
				$('d-subscribe-error').style.display = 'block';
			} else {
				$('d-subscribe').update(result.text);
			}
		},
		onFailure: function(){}, 
		onException: function(request, ex){}
	});		
	
	return true;
}
function do_subscribe() {
	var hash		= $('hash').value;
	var code 		= $('code').value;
	
	$('d-subscribe-error').style.display = 'none';
	var ajaxUrl = url+'carfinder-online-auto-auctions/ajax/do-subscribe/';
	new Ajax.Request(ajaxUrl,
	{
		method: 'get',
		evalJSON: true,
		parameters: {hash:hash, code:code},

		onSuccess: function(transport) {
			result = transport.responseJSON
			if(result.error) {
				$('d-subscribe-error').update(result.error);
				$('d-subscribe-error').style.display = 'block';
			} else {
				$('d-subscribe').update(result.text);
			}
		},
		onFailure: function(){}, 
		onException: function(request, ex){}
	});		
	
	return true;
}

function ChangeShippingType(){
	var type = $('shipping').value; 
	$('border_crossing-container').style.display = "none";
	$('domestic-container').style.display = "none";
	$('domestic-data-container').style.display = "none";
	$('international-container').style.display = "none";
	$('international-data-container').style.display = "none";
	if (type=='N')
	{
		calculate();
	} else if (type=='D') {
		$('domestic-container').style.display = "block";
		calculate();
	} else if (type=='B') {
		$('border_crossing-container').style.display = "block";
		calculate();
	} else if (type=='I') {
		ChangeCountry();
		$('international-container').style.display = "block";
		calculate();
	}
}
function ChangeCountry(){
	if ( $('preSelectedDestport') !== null ) {
		var preSelectedDestport = $('preSelectedDestport').value;
	}
	var country = $('country').value;
	
	var h =  $('h').value;
	var ajaxUrl = url+'shipping-salvage-vehicles/port/'+country+'/'+h+'/';
	new Ajax.Request(ajaxUrl,
	{
		method: 'get',
		evalJSON: true,
		onSuccess: function(transport) {
			updatePortList( transport.responseJSON.markers, preSelectedDestport );
		},
		onFailure: function(){}, 
		onException: function(request, ex){}
	});		
}

function updatePortList(ports, preSelectedDestport){
	var portListElement = $('to_port');
	var selected = false;
	if ( portListElement !== null ) {
		portListElement.update('');
		portListElement.options.add(new Element('option', { 'value' : '0'}));
		portListElement.options[0].update('---');
		
		for ( var i = 1; i <= ports.length; i++ ) {
			portListElement.options.add(new Element('option', { 'value' : ports[i-1].id}));
			portListElement.options[i].update(ports[i-1].name);
			
			if(preSelectedDestport !== null && preSelectedDestport==ports[i-1].id)
			{
				portListElement.options[i].selected = true;
				selected = true;	
			}
		}
		if(selected !== true)
		{
			portListElement.options[0].selected = true;
		}
		calculate();
	}
}

function bidIncDo(act, bid)
{
	var cur_bid = parseInt($('max_bid').value);
	var cur_bid_st = cur_bid;
	var min_bid = parseInt($('cur_bid').value)+get_bid_inc(parseInt($('cur_bid').value));

	var new_bid = 0;
	if(cur_bid_st <= 1 || isNaN(cur_bid) || (cur_bid < min_bid && act==1) || ((cur_bid-get_bid_inc(cur_bid)) < min_bid && act==2) ) {
		cur_bid = parseInt($('cur_bid').value) + get_bid_inc(parseInt($('cur_bid').value));
		cur_bid_st = cur_bid ;
		$('max_bid').value = cur_bid_st;
		validateBid(true);

		if(bid)
			calculate();
		return;
	}
	
	if(!validateBid(true)) {
		return;
	}
	if(act==1)
	{
		new_bid = parseInt(cur_bid + get_bid_inc(cur_bid));
		$('max_bid').value = new_bid;
	} else if (act==2) {
		new_bid = parseInt(cur_bid - get_bid_inc(cur_bid-1));
		$('max_bid').value = new_bid;
	}
	cur_bid = $('max_bid').value;

	if(!validateBid(true)) {
		return;
	}
	
	if(cur_bid_st==cur_bid && act > 0) {
		return;
	}
	if(bid)
		calculate();
}
function get_bid_inc(bid)
{
	var inc = 0;
	 
	if(bid < 5) {
		inc = 1;
	} else if(bid < 40) {
		inc = 5;
	} else if(bid < 100) {
		inc = 10;
	} else if(bid < 1000) { 
		inc = 25;
	} else if(bid < 5000) {
		inc = 50;
	} else if(bid < 25000) {
		inc = 100;
	} else if(bid < 50000) {
		inc = 250;
	} else if(bid < 100000) {
		inc = 500;
	} else  {
		inc = 1000;
	}
	
	return inc;
}
var currentImageCounter = 0;
function showMain(imageNum) {
	var oldSelected = $('LotImage' + currentImageCounter);
	if ( oldSelected != null ) {
	  oldSelected.removeClassName('selected');
	}
	
	currentImageCounter = imageNum;
	
	if ( currentImageCounter < 0 ) {
	  currentImageCounter = imageList.length-1;
	} else if ( currentImageCounter > imageList.length-1 ) {
	  currentImageCounter = 0;
	}
	
	$('LargeImage').src = imageList[currentImageCounter];
	$('LotImage' + currentImageCounter).addClassName('selected');      
}
function ChangeType(type)
{
	$('type').value = type;
	if(type=='email')
	{
		$('phone').style.display = 'none';		
		$('type-phone-act').style.display = 'none';
		$('type-phone').style.display = 'inline';
		$('email').style.display = 'inline';
		$('type-email').style.display = 'none';
		$('type-email-act').style.display = 'inline';
	} else {
		$('email').style.display = 'none';
		$('type-email').style.display = 'inline';
		$('type-email-act').style.display = 'none';
		$('phone').style.display = 'inline';		
		$('type-phone-act').style.display = 'inline';
		$('type-phone').style.display = 'none';
	}
}