/**
 * Set form values and submit form
 * 
 * @param formId the form id
 * @param map the map containing name-value pairs
 * @return always <code>false</code>
 */
function submitForm(formId, map) {
	var $form = $("#" + formId);
	if (map) {
		$.each(map, function(key, value) {
			$form.find("[id = '" + key + "']").val(value);
		});
	}
	$form.submit();
	return false;
}

/**
 * Remove picture from the specified index location
 * 
 * @param picLocation index location
 */
function deletePic(picLocation) {
	$("#picture" + picLocation + "tempPath").attr("value", "");
	$("#picture" + picLocation + "tempThumbnailPath").attr("value", "");
	$("#picture" + picLocation + " img.thumbnail").attr("src", "");
	
	$("#picture" + picLocation).hide();
}

/**
 * Submit form with specified action parameter
 * 
 * @param action the Ad action parameter
 * @return the same as <code>submitForm</code> function
 */
function submitWithAction(action) {
	return submitForm("adData", {
		"formAction": action
	});
}

/**
 * Submit form with specified action parameter after user gives permission
 * 
 * @param action the Ad action parameter
 * @param message the confirmation message
 * @return the same as <code>submitForm</code> function
 */
function submitWithActionC(action, message) {
	if (confirm(message)) {
		submitWithAction(action);
	}
}

/**
 * Get template service URL
 * 
 * @param category the category id
 * @param action the action id
 * @param type the template type
 * @return template service URL
 */
function getTemplateUrl(category, action, type) {
	return '/template/load.html?category=' + category + '&action=' + action + '&type=' + type;
}

/**
 * Load content to #template element
 * 
 * @param category the category id
 * @param action the action id
 * @param type the template type
 */
function loadTemplate(category, action, type) {
	$("#template").load(getTemplateUrl(category, action, type));
}

/**
 * Load content to specified table element as additional table rows
 * 
 * @param tableId target table id
 * @param category the category id
 * @param action the action id
 * @param type the template type
 */
function loadTemplateInTable(tableId, category, action, type) {
	$.get(getTemplateUrl(category, action, type), function(data) {
		var $table = $('table#' + tableId);
		$table.find('tr.template').remove();
		
		$(data)
			.addClass('template')
			.appendTo($table.children('tbody'))
			.find('input[type=text]')
			.defaultText();
		
		/** Unbind and bind the action so it will be the last action after defaultText */
		$('form').unbind("submit", shortenUrl);
		$('form').bind("submit", shortenUrl);
	});
}

/**
 * Upload ad picture
 * 
 * @param opts additional options
 * @return always <code>false</code>
 */
function adPicturesAjaxFileUpload(opts) {
	var opts = opts || {};
	opts.msg_NO_EMPTY_SLOTS = opts.msg_NO_EMPTY_SLOTS || "msg_NO_EMPTY_SLOTS";
	opts.uploadUrl = opts.uploadUrl || "";
	
	/**
	 * Starting index 0.
	 */
	var findEmptySlot = function() {
		var counter = 0;
		while (counter < 10) {
			var $picture = $("#picture" + counter + "tempPath");
			if ($picture.length > 0) {
				if ($picture.attr("value").length == 0) {
					return counter;
				}
			} else {
				break;
			}
			counter++;
		}
		return -1;
	}
	
	var emptySlot = findEmptySlot();
	if (emptySlot < 0) {
		alert(opts.msg_NO_EMPTY_SLOTS);
		return false;
	}
	
	/*
	$("#loading").ajaxStart(function() {
		$(this).show();
	}).ajaxComplete(function() {
		$(this).hide();
	});
	*/
	
	$.ajaxFileUpload({
			url: opts.uploadUrl,
			secureuri: false,
			fileElementId: 'adPictureFileToUpload',
			dataType: 'json',
			success: function (data, status) {
				if (typeof(data.error) != 'undefined') {
					if (data.error != '') {
						alert(data.error);
					} else {
						$("#picture" + emptySlot + "tempPath").attr("value", data.tempPath);
						$("#picture" + emptySlot + "tempThumbnailPath").attr("value", data.tempThumbnailPath);
						$("#picture" + emptySlot + " img.thumbnail").attr("src", data.tempThumbnailPath);
						
						$("#picture" + emptySlot).show();
					}
				}
			},
			error: function (data, status, e) {
				alert(e);
			}
		}
	)
	return false;
}

/**
 * Go to next page in search results
 * 
 * @return the same as <code>submitForm</code> function
 */
function nextPage() {
	return submitForm("searchData", {
		"page": Number($("#page").val()) + 1
	});
}

/**
 * Go to previous page in search results
 * 
 * @return the same as <code>submitForm</code> function
 */
function previousPage() {
	var page = Number($("#page").val());
	return submitForm("searchData", {
		"page": Math.max(page - 1, 0)
	});
}

/**
 * Re-order search results by the specified column
 * 
 * @param column the column name
 * @param direction the direction, <code>ASCENDING</code> or <code>DESCENDING</code>
 * @return the same as <code>submitForm</code> function
 */
function reorderSearch(column, direction) {
	return submitForm("searchData", {
		"page": "0",
		"sortColumn": column,
		"sortDirection": direction
	});
}

/**
 * Execute search
 * 
 * @return the same as <code>submitForm</code> function
 */
function submitSearch() {
	return submitForm("searchData", {
		"page": "",
		"sortColumn": "d",
		"sortDirection": "d",
		"id": ""
	});
}

/**
 * Set only the allowed actions to the enabled state.
 * 
 * @param form
 *            The form name.
 */
function filterActionsByCategory(form) {
	var actionElement = $("#" + form).find("#adAction");
	var category = $("#" + form).find("#category").val();
	var allowedActions = ALLOWED_CATEGORY_ACTIONS[category];
	actionElement.children().each(
			function(index) {
				if (jQuery.inArray($(this).attr("value"),
						allowedActions) != -1) {
					$(this).removeAttr("disabled");
				} else {
					$(this).attr("disabled", "disabled");
				}
			});
}

/**
 * Change target dropdown values. The first option with value = 0 is preserved.
 * 
 * @param url ajax service url as string or as a function that returns the url
 * @selector target dropdown selector 
 */
function ajaxFillDropdown(url, selector) {
	if ($(selector + " option:eq(0)").val() == "0") {
		$(selector + " option:gt(0)").remove();
	} else {
		$(selector + " option").remove();
	}
	if (typeof url == "function") {
		url = url();
	}
	$.get(url, function(data) {
		$.each($(eval(data)), function(index, value) {
			$(document.createElement("option"))
				.val(value.value)
				.append(document.createTextNode(value.title))
				.appendTo($(selector));
		});
	});
}

function shortenUrl() {
	$(this).find("input[type='text'], select").each(function() {
		var el = $(this);
		if (el.val() == "" || (el.is("select") && el.val() == "0")) {
			el.removeAttr("name");
		} else if (el.attr("id") == "priceFrom" || el.attr("id") == "priceTo") {
			el.val(el.val().replace(" ", ""));
		}
	});
	
	var action = $(this).attr("action");
	
	if ($(this).find("#category").val() != "0") {
		action = action.replace(".html", "/" + catTranslit[$(this).find("#category").val()] + ".html");
		$(this).find("#category").removeAttr("name");
	}
	
	if ($(this).find("#county").val() != "0") {
		action = action.replace(".html", "/" + locTranslit[$(this).find("#county").val()] + ".html");
		$(this).find("#county").removeAttr("name");
	}
	
	$(this).attr("action", action);
	
	$(this).find("input[type='hidden']").each(function() {
		var el = $(this);
		if (el.attr("id") == "sortColumn" && el.val() == "d") {
			el.removeAttr("name");
		} else if (el.attr("id") == "sortDirection" && el.val() == "d") {
			el.removeAttr("name");
		} else if (el.attr("id") == "id" && el.val() == "") {
			el.removeAttr("name");
		} else if (el.attr("id") == "page" && el.val() == "") {
			el.removeAttr("name");
		}
	});
}

/**
 * Calculates purchase prices for each service and total price
 * 
 */
var valuesLookUp = {
		'ZERO' : '0',
		'ONE' : '1',
		'TWO' : '2',
		'THREE' : '3',
		'FOUR' : '4',
		'FIVE' : '5'
}
function calculateTotal(){
	highlightHidePrices();
	var totalSum = 0;
	var hasNextService = $(".unitPrice0").length;
	var counter = 0;
	while(hasNextService){
		// get amount
		var serviceAmount = valuesLookUp[$(".service"+counter+"select :selected").val()];
		// set sum to row
		var unitPrice = $(".unitPrice"+counter).html();
		servicePrice = unitPrice.split(' ')[0].replace(',','.');
		serviceSum = serviceAmount*servicePrice;
		// add to total sum
		totalSum = totalSum + serviceSum;
		serviceSum = serviceSum.toFixed(2);
		serviceSum+"".replace('.',',');
		$(".price"+counter).html(serviceSum);
		if(serviceAmount == 0){
			$(".price"+counter).html(unitPrice);
		}
		counter++;
		// check if theres next service
		hasNextService =  $(".unitPrice"+counter).length;
	}
	// set total sum
	totalSum = totalSum.toFixed(2);
	totalSum = totalSum.replace('.00', '');
	totalSum = totalSum.replace('.',',');
	$("#priceTotal").html(totalSum);
	
}

/**
 * Highlights and hides prices when service is selected or not
 * 
 */
function highlightHidePrices(){
	var hasNextService = $(".unitPrice0").length;;
	var counter = 0
	while(hasNextService){
		var externalAdsSelected =  valuesLookUp[$(".service"+counter+"select :selected").val()] > 0;
		if(externalAdsSelected){
			// if price disabled
			if($(".price"+counter).parent().hasClass("disabledPrice")){
				// enable price
				$(".price"+counter).parent().removeClass("disabledPrice");
			}
		} else{
			// if price enabled
			if(! $(".price"+counter).parent().hasClass("disabledPrice")){
				// disable price
				$(".price"+counter).parent().addClass("disabledPrice");
				// put disabled unit price
				$(".price"+counter).html($(".unitPrice"+counter).html());
			}
		}
		counter++;
		hasNextService = $(".unitPrice"+counter).length;
	}
}
