/**
 * All userpage related JavaScript
 */

// when DOM is ready
$(function(){
	
	/**
	 * Login form
	 */
	$("#login input:text").focus(function(){
		if ($(this).val()==gettext('username')) {
			$(this).val('');
		}
	}).blur(function(){
		if ($(this).val()=='') {
			$(this).val(gettext('username'));
		}
	});
	$("#login input:password").focus(function(){
		if ($(this).val()=='******') {
			$(this).val('');
		}
	}).blur(function(){
		if ($(this).val()=='') {
			$(this).val('******');
		}
	});
	
	$('#form_vehiclemake_id').change( function() {
		if ($('#form_vehiclemodel_id')) {
			ModelSelection($('#form_vehiclemodel_id'), $(this).val()).load();
		}
	});
	/*if ($('#form_vehiclemodel_id') && $('#form_vehiclemake_id')) {
		ModelSelection($('#form_vehiclemodel_id'), $('#form_vehiclemake_id').val()).load();
	}*/
	
	
	/**
	 * Switching between register form user types
	 */
	$("#register-form .user-type input").click(function(){
		// use the value of radio-button
		// to show the fieldset with the same classname as radio-value
		var showClassName = $(this).val();
		var hideClassName = (showClassName == 'private') ? 'company' : 'private';
		$("#register-form fieldset." + hideClassName).hide();
		$("#register-form fieldset." + showClassName).show();
	});
	
	/**
	 * Add vehicle form first view
	 */
	 
	var selected_vehicle_type = $('#vehicle-body-type select').val();
	$("#vehicle-body-type select").change(function(){
		var href = $('#vehicle-maindata-form').attr('action');
		if (href.match(/id=[0-9]+/)) {
			if (!confirm(gettext('Are You sure You want to change bodytype? It causes a loss of data already inserted.'))) {
				$('#vehicle-body-type select').val(selected_vehicle_type);
				return false;
			}
		}
		this.form.submit();
	});
	
	/**
	 * Change make values
	 */
	$("#form_vehiclemake_id").change(function(){
		if ($("#form_vehiclemake_id").val() != 0) {
			$("#form_vehiclemake_text").val('');
			$("#form_vehiclemake_text").attr("readonly", "readonly");
		} else {
			$("#form_vehiclemake_text").removeAttr("readonly");
		}
	});

	/**
	 * Change make values
	 */
	$("#form_sell4vehicleexchangeable_id").change(function(){
		if ($("#form_sell4vehicleexchangeable_id").val() != 0) {
			$("#form_sell4vehicleexchangeable_text").val('');
			$("#form_sell4vehicleexchangeable_text").attr("readonly", "readonly");
		} else {
			$("#form_sell4vehicleexchangeable_text").removeAttr("readonly");
		}
	});

	/**
	 * Maindata add ons show and off
	 */
	$("#dimensiondata-link-show").click(function(){
		$("#dimensiondata").removeClass("hide");
		$("#dimensiondata-link-div").addClass("hide");
		$("#dimensiondata-link-div-show").addClass("hide");
		$("#dimensiondata-link-show-footer").removeClass("hide");
		return false;
	});
	$("#dimensiondata-link-hide").click(function(){
		$("#dimensiondata-link-div-show").removeClass("hide");
		$("#dimensiondata-link-div").removeClass("hide");
		$("#dimensiondata").addClass("hide");
		$("#dimensiondata-link-show-footer").addClass("hide");
		return false;
	});
	
	/**
	 * Changing language in free-form text-entry fields
	 */
	$("#vehicle-textarea h2 a").click(function(){
		var selectedLang = $(this).attr("class").replace(" bold", "");
		
		$("#vehicle-textarea h2 a").removeClass("bold");
		$("#vehicle-textarea h2 a."+selectedLang).addClass("bold");
		
		// first make selected textarea visible, then hide all, then make it visible again
		// this avoids flickering - at least in Opera
		$("#vehicle-textarea textarea."+selectedLang).show();
		$("#vehicle-textarea textarea").hide();
		$("#vehicle-textarea textarea."+selectedLang).show();
		
		return false;
	});
	
	$("#form_usershop_id").change(function(){
		$("#form_usershop_changed_bt").val(1);
		$('#contact_form').submit();
	});
	

	/**
	*	Multilanguage textareas
	*/
	$(".multilang-textareas h2 a").click(function(){		
		var selectedArea = $(this).attr("class").replace(" bold", "");
		var id = $(this).attr("id");

		// first make selected textarea visible, then hide all, then make it visible again
		// this avoids flickering - at least in Opera
		$('#'+id+' #'+selectedArea).show();
		$("#"+id+' div.box-content div').hide();
		$('#'+id+' #'+selectedArea).show();
		
		$("#"+id+' h2 a').removeClass("bold");
		$("#"+id+' h2 a.'+selectedArea).addClass("bold");
		return false;
	});
	
	
	/**
	 * Showing and hiding of field and status in My Account page.
	 */
	(function(){
		
		function recalculate() {
			var sum = 0;
			$("#vehicles table select:visible").map(function(){
				var val = $(this).val();
				var label = $("option[value='"+val+"']", this).text();
				var price = label.replace(/^.*\(([0-9]+(\.[0-9]{2})?) [A-Z]{3}\)$/, "$1")
				sum += parseFloat(price, 10);
			});
			if (sum > 0) {
				$("#vehicles .total-payment strong").text(sum);
				$("#vehicles .total-payment").show();
			}
			else {
				$("#vehicles .total-payment").hide();
			}
		}
		
		$("#vehicles table select").change(recalculate);
		
		function getField(elem) {
			return $("select", $(elem).parent().prev());
		}
		
		$("#vehicles table td.action a").map(function(){
			var link = $(this);
			var field = getField(this);
			var status = $("span", $(this).parent().prev());
			
			var oldText = $(this).text();
			var options = $("option", field).map(function(){
				if ($(this).attr("value")) {
					return '<option value="' + $(this).attr("value") + '">' + $(this).text() + '</option>';
				}
				else {
					return '';
				}
			});
			var filledSelect = '<select name="' + field.attr("name") + '">' + $.makeArray(options).join("") + '</select>';
			var emptySelect = '<select name="' + field.attr("name") + '"><option></option></select>';
			
			function show() {
				field = field.replaceWith(filledSelect);
				field = getField(link).change(recalculate);
				field.show();
				status.hide();
				$(this).text(gettext("Cancel"));
				recalculate();
				return false;
			}
			function hide() {
				field.replaceWith(emptySelect);
				field = getField(link).change(recalculate);
				field.hide();
				status.show();
				$(this).text(oldText);
				recalculate();
				return false;
			}
			
			if (field.attr("class") == "hide-initially") {
				field.hide();
				status.show();
				$(this).text(oldText);
				
				$(this).toggle(show, hide);
			}
			else {
				field.show();
				status.hide();
				$(this).text(gettext("Cancel"));
				
				$(this).toggle(hide, show);
			}
		});
		
		recalculate();
		
	})();

	$('#vehicle-price #form_sell_price4currency_id').change(function() {
		$('#vehicle-price .contact-form-currency').text(this.options[this.selectedIndex].text);
	});
	$('#vehicle-price #form_sell_price4currency_id').change();

	/**
	 * Popup on DELETE link
	 */
	$("#vehicles a.delete").click(function(){
		return confirm( $(this).attr("title") + "?" );
	});

	
	$("#gallery-edit a.delete").click(function(){
		return confirm( $(this).attr("title") + "?" );
	});



	/**
	 * Show-hide statistics
	 */
	$("#vehicles .stats-total a").toggle(
		// show
		function() {
			$(this).text( gettext("Hide statistics") );
			var stats = $("+ .stats", $(this).parent());
			
			stats.show("fast", function(){
				// scroll as far right as possible
				stats.get(0).scrollLeft = stats.get(0).scrollWidth;
			});
		},
		// hide
		function(){
			$(this).text( gettext("View statistics") );
			$("+ .stats", $(this).parent()).hide("fast");
		}
	);

	$("#bills .edit-billing-data a").click(function(){
		$("#bills #billing-data").hide();
		$("#bills #billing_form").show();
		return false;
	});

	$("#bills #cancel_bt").click(function(){
		$("#bills #billing-data").show();
		$("#bills #billing_form").hide();
	});
	
	$("#bills .hide").hide();

	$('#paperusers .hide').hide();

	$('#paperusers #add_new_bt').click(function(){
		$('#paperusers #new-form').show();
		$('#paperusers #buttons').hide();
	});
	$('#paperusers #cancel_bt').click(function(){
		$('#paperusers #new-form').hide();
		$('#paperusers #buttons').show();
	});

	$('#form_sell_vehicleexchangeable_text').keyup( function() {
		var select_input = '#form_sell4vehicleexchangeable_id';
		if (this.value.length > 0) {
			$(select_input).attr('disabled', 'disabled');
		}
		else {
			$(select_input).removeAttr('disabled');
		}
	});

	$('#form_sell4vehicleexchangeable_id').change( function() {
		var text_input = '#form_sell_vehicleexchangeable_text';
		if (parseInt(this.value) > 0) {
			$(text_input).attr('disabled', 'disabled');
		}
		else {
			$(text_input).removeAttr('disabled');
		}
	});

	$('#form_sell_booked_cb').click(function() {
		setBookedActiveness();
	});

	$('#form_cond_warranty_cb').click(function() {
		setWarrantyActiveness();
	});

	$('#form_cond_technical_inspection_cb').click(function() {
		setTechInspectionActiveness();
	});

	function setBookedActiveness() {
		setActiveness($('#form_sell_booked_cb').attr('checked'), new Array(
			'#form_sell_booked_until_D', 
			'#form_sell_booked_until_F', 
			'#form_sell_booked_until_Y'
		));
	}

	function setTechInspectionActiveness() {
		setActiveness($('#form_cond_technical_inspection_cb').attr('checked'), new Array(
			'#form_cond_technical_inspection_next_F', 
			'#form_cond_technical_inspection_next_Y'
		));
	}
	
	function setWarrantyActiveness() {
		setActiveness($('#form_cond_warranty_cb').attr('checked'), new Array(
			'#form_cond_warranty_until_date_D', 
			'#form_cond_warranty_until_date_F', 
			'#form_cond_warranty_until_date_Y', 
			'#form_cond_warranty_until_dist_km'
		));
	}
	
	function setActiveness(show, arr) {
		for (var element in arr) {
			if (show) {
				$(arr[element]).removeAttr('disabled');
			}
			else {
				$(arr[element]).attr('disabled', 'disabled');
			}
		}
	}
	setBookedActiveness();
	setWarrantyActiveness();
	setTechInspectionActiveness();

	function generateLink() {
		var url = getLinkUrl();
		
		var content = "<script type=\"text/javascript\" src=\"http://www.ekspressauto.ee/forte/ads?"+ url +"\"></script>";
		$('#link-generation #search-box-result').val(content);

	}

	function getLinkUrl() {
		var params = '';
		$('#link-generation #search-box form select').map(function(){
			params += '&' + $(this).attr('name') + '=' + $(this).val();
		});
		$('#link-generation #search-box form input').map(function(){
			params += '&' + $(this).attr('name') + '=' + $(this).val();
		});
		return params;
	}

	$('#link-generation #search-box form').submit(function() {
		$('#link-generation #search-box form input').map(function(){
			if ($(this).attr('title') == $(this).val()) {
				$(this).val('');
			}
		});
		generateLink();
		return false;
	});
	$('#link-generation #search-box input').focus(function() {
		if ($(this).attr('title') == $(this).val()) {
			$(this).val('');
		}
	});
	$('#link-generation #search-box input').blur(function() {
		if (!$(this).val()) {
			$(this).val($(this).attr('title'));
		}
	});
	

	$('#link-generation #search-box select[name=make_id]').change( function() {
		if ($('#link-generation #search-box select[name=model_id]')) {
			var model_selection = ModelSelection($('#link-generation #search-box select[name=model_id]'), $(this).val());
			model_selection.setMode('');
			model_selection.load();
		}
	});

	$('#edit-pictures select').change(function() {
		var name = $(this).attr('name');
		var id = name.split('_');
		id = id[1];
		if (!name.match(/^watermark/) || !id) {
			return;
		}
		var href=document.location.href;
		href = href.replace(/pictures/, 'watermark');
		href = href.split('?');
		document.location.href = href[0] + '?picture_id=' + id + '&mode=' + $(this).val();
	});
});
