/**
 * All detailview related JavaScript
 */

// when DOM is ready
$(function(){
	
	/**
	 * Email through web functionality
	 */
	$("#vehicle-seller #send_email_show").click(function() {
		$("#vehicle-seller #send_email").show();
		return false;
	});
	
	/**
	 * Switching between thumbnail images
	 */
	(function(){
	
		initThumbnailSwitcher("#vehicle-images");
		initThumbnailSwitcher("#large-images");
		
		function initThumbnailSwitcher(id) {
			// if ID is missing from document, do nothing
			if ( $(id).length == 0 ) {
				return;
			}
			
			// find the size of large image and the size of thumbs
			function getImgSize(img) {
				return img.attr("src").replace(/^.*\/([0-9]+x[0-9]+)\/.*$/, "$1");
			}
			var largeImageSize = getImgSize( $(id + " p.large-image img") );
			var thumbSize = getImgSize( $(id + " ul li:first-child img") );
			
			// try to get large-image-link
			// if it fails, leave the link undefined
			var largeImgLink = $(id + " p.large-image a");
			if (largeImgLink.length == 0) {
				largeImgLink = undefined;
			}
			
			// We use closure to remember index of each thumbnail image
			// The first image should be 0, second 1, third 2, etc
			//
			// We loop through all images, each time saving the the position
			// to imgIndex and incrementing counter. At the end all event
			// handlers have variable imgIndex with the value of their index.
			var imgCounter = 0;
			
			$(id + " ul a").map(function(){
				
				var imgIndex = imgCounter;
				
				$(this).mouseover(function(){
					switchImage(this);
				});
				$(this).click(function(){
					switchImage(this);
					return false;
				});

				function switchImage(element) {
					// take the path of clicked thumbnail image
					// and replace the thumb size in it (e.g. "80x70") with large image size
					if (!$("img", element).attr("src")) {
						return false;
					}
					var newLargeImgPath = $("img", element).attr("src").replace(thumbSize, largeImageSize);
					$(id + " p.large-image img").attr("src", newLargeImgPath);
					
					// if larger image is link, change href attribute
					if (largeImgLink) {
						var href = largeImgLink.attr("href");
						// if img=... is not at end of path, add it
						if ( ! /img=[0-9]+$/.test(href) ) {
							href += "&img=0";
						}
						largeImgLink.attr("href", href.replace(/img=[0-9]+$/, "img="+imgIndex));
					}
					
					// set the selected image
					$(id + " ul a.selected").removeClass("selected");
					$(element).addClass("selected");
					
					return false;
				}
				
				imgCounter++;
			});
		}
	})();
	
	/**
	 * This is our own number formatting function
	 */
	function formatNumber (anynum, decimal) {
		var divider;
		switch (decimal) {
			case 0:
				divider = 1;
			break;
			case 1:
				divider = 10;
			break;
			case 2:
				divider = 100;
			break;
			default:
				divider = 10;
			break;
		}
		
		var workNum = Math.abs ((Math.round (anynum * divider) / divider));
		var workStr = "" + workNum;
		if (workStr.indexOf (".") == -1) {
			workStr += ".";
		}
		var dStr = workStr.substr (0, workStr.indexOf ("."));
		var dNum = dStr - 0;
		var pStr = workStr.substr (workStr.indexOf ("."));
		
		while (pStr.length - 1 < decimal) {
			pStr += "0";
		}
		
		if (pStr == '.') {
			pStr = '';
		}
		if (dNum >= 1000) {
			dStr = parseInt ("" + (dNum / 1000), 10) + " " + dStr.substring (dStr.length - 3, dStr.length);
		}
		if (dNum >= 1000000) {
			dStr = parseInt ("" + (dNum / 1000000), 10) + " " + dStr.substring (dStr.length - 7, dStr.length);
		}
		var retval = dStr + pStr;
		if (anynum < 0) {
			retval = "(" + retval + ")";
		}
		return retval;
	}
 
	/**
	 * Switching between price currency and vat tax
	 */
	$("#vehicle-price select").change(function() {
		setPrices(); 
		return;
	});	
	
	function setPrices() {
		var price_element = document.getElementById('price_currency');
		if (!price_element){
			return;
		}

		var str = new String(price_element.value);
		var prices = str.split(';');
		var i = 0;

		var elements = new Array('price', 'ordinary_price', 'export_price');
		for (el in elements){
			if (document.getElementById('price')){
				changePrice(elements[el], prices[i], elements[el] != 'export_price');
			}
				i++;
		}
		$("#vehicle-price .currency-label").text(price_element.options[price_element.selectedIndex].text);
	}

	function changePrice(el_name, new_price, addVat) {
		new_price = String(new_price);
		new_price = Math.round(new_price.replace(/ /g, ''), 10);
		
		if (addVat) {		
			// if selected VAT type is WITHOUT_VAT, then remove VAT tax from price
			var vat = $("#vehicle-price #vat").val();
			var vat_percent = parseInt($("#vehicle-price #vat_percent").val());
			if (vat_percent == null || vat_percent == 0) vat_percent = 20;
			if (vat == 2) {
				// for some strange reason konqueror fails to divide or multiply a number with 1.20
				new_price = new_price * 100 / (100 + vat_percent);
			}
		}
		new_price = formatNumber(new_price, 0);
		$("#vehicle-price #"+el_name).text(new_price);
	}
	
	$('#vehicle-admin_actions input[name=delete_bt]').click(function() {
		if (!confirm(gettext('Are You sure to delete?'))) {
			return false;
		}
	});
	
	$('#vehicle-admin_actions input[name=disable_bt]').click(function() {
		if (!confirm(gettext('Are You sure to disable?'))) {
			return false;
		}
	});
});