var formData = null;
var huomioOpts = {};
var updateTitle = false;
var tempCountMax = 10000;

// Variables for automatic category finder
var catTimeout = null;
var $catInput = null;
var prevInput = "";
var lastKeyPressCode = null;
var $catResults = $("<div></div>");
var prevKeyword = null;
$catResults.css({'padding' : '2px', 'position' : 'relative'});


//things that should be done when the document is ready
$(document).ready(function() {
				if (page == 0) {
					initState1();
				} else if (page == 1) {
					initState2();
				}
			});

/**
 * Prepare first states javascript actions
 * @return
 */
function initState1() {
	updateTitle = false;

	var intentionType = $("input[name='intention']:checked").val();

	$("#proddataModels label").click(function(e) {
		e.preventDefault();
		$(this).find("input").attr("checked", "checked");
		if (dataModelType != "vert_car") {
			// Remove existing productCategory selection (IE8)
			$("[name='productCategory']").remove();
			// Set default as car, productCategory 00K001010001
			$("<input value='00K001010001' name='productCategory' type='hidden'>").appendTo("form#command");
		}
		moveToPage(0);
	});

	$("#mainProduct option:selected").removeAttr("selected").addClass("active");
	$("#productSelect option:selected").removeAttr("selected").addClass("active");

	//Disable title for car dataModel
	if (dataModelType == "vert_car") {
		$("#prodtitle input").attr("disabled","disabled" ).addClass("disabled");
		updateTitle = true;

        // Enable title-based automatic category finder
        } else {
            $catInput = $("#prodtitle input");

			// Attempt to disable browser autocomplete feature
			$catInput.attr("autocomplete", "off");

			// Insert container for results
            $catInput.after($catResults);

            $catInput.keydown(function(e) {
                // Remember last keypress
                lastKeyPressCode = e.keyCode;

				// Throttle ajax requests
                if (catTimeout) clearTimeout(catTimeout);
                catTimeout = setTimeout(function() {
                    onTitleChange();
                }, 800); // milliseconds
            });
        }

	//For highlighting the production selection box
	$("#mainProduct").change(
			function () {
				var selected = $("#mainProduct option:selected").attr('id');
				updateIntention(selected.substring(1,selected.length));
				changeCategorySet($("#mainProduct option:selected"));
				if (updateTitle)
					updateSetTitle();
			}
	);

	$("#productSelect").click(
			function () {
				var selected = $("#productSelect option:selected").val();
				handleProductSelection(selected);
			}
	);

	var citesFrameWidth = 120;
	var citesFrameHeight = 200;
	if ($.browser.msie) {
		citesFrameWidth = 120;
		citesFrameHeight = 250;
	}
	$("a#cites_inline").fancybox({
		'titlePosition'		: 'inside',
		'transitionIn'		: 'elastic',
		'transitionOut'		: 'elastic',
		'frameWidth'		: citesFrameWidth,
		'frameHeight'		: citesFrameHeight
		});

	// Setup intentions (ad type)
	updateIntention($("#productSelect option.active").val());

	// Setup image delete buttons
	$("a[id^='deleteimage']").click(function (e) {
		e.preventDefault();
		$("#recordMedias\\[" + $(this).attr("id").match(/\d+/) + "\\]\\.status").val("DELETE");
		formSubmit();
		$('#command').attr('action', $('#command').attr('action') + '#images');
		moveToPage(0);
	});

        $("#deleteVideo").click(function (e) {
		e.preventDefault();
                $("<input value=\"true\" name= \"deleteVideos\" type=\"hidden\">").appendTo("form#command");
                formSubmit();
		moveToPage(0);
	});

// Setup main image link. Clicking it will set the image index to 0 making it the main image.
	$("a[id^='mainimage']").click(function (e) {
		e.preventDefault();
		$("#recordMedias\\[" + $(this).attr("id").match(/\d+/) + "\\]\\.status").val("MAIN");
		formSubmit();
		$('#command').attr('action', $('#command').attr('action') + '#images');
		moveToPage(0);
	});

	// Setup image field
	$("input[name='IMG']").change(function (e) {
	  $("input[name='IMG']").css({display:"none", visibility:"hidden"});
		formSubmit();
		$('#command').attr('action', $('#command').attr('action') + '#images');
		moveToPage(0);
	});

	if (updateTitle) {
		$("#prodtype input").change(function () {
			updateSetTitle();
		});
		$("#prodmodelYear select").change(function () {
			updateSetTitle();
		});
	}


	$("input[name='intention']").click(function (e) {
	    $("input[name='price.priceFinal']").css({display:"block"});
	    document.getElementById("reqFieldprice").style.display="block";
		if (this.value == 'BUY') {
		   document.getElementById("reqFieldprice").style.display="none";
	       $("input[name='price.priceFinal']").css({display:"none"});
		   $("input[name='price.priceFinal']").val("");
		   showRequiredFields(requiredFields.buyFields);
		} else if (this.value == 'SELL') {
			showRequiredFields(requiredFields.sellFields);
		} else if (this.value == 'CHANGE') {
			showRequiredFields(requiredFields.changeFields);
		} else if (this.value == 'OTHER') {
			showRequiredFields(requiredFields.otherFields);
		} else if (this.value == 'WANTS_TO_RENT') {
			showRequiredFields(requiredFields.otherFields);
		} else {
			showRequiredFields(requiredFields.defaultFields);
		}
	});

	$("#title").charCounter(tempCountMax, {
		container: "<span id='titleCounter' style='display: none'></span>",
		format: "%1",
		pulse: false,
		callback: function() {
			$("#priceCounter, #titleCounter").change();
		}
	});

	$("#price").charCounter(tempCountMax, {
		container: "<span id='priceCounter' style='display: none'></span>",
		format: "%1",
		pulse: false,
		callback: function() {
			$("#priceCounter, #titleCounter").change();
		}
	});

	var descCountMax = 148;
	$("<span id='totalCounter' style='display: none'></span>").text(descCountMax).insertAfter($("textarea[name='description']"));

	$("textarea[name='description']").charCounter(descCountMax, {
		container: "#descCnt",
		classname: "counter",
		format: "%1",
		pulse: true,
		delay: 100,
		maxelement: "#totalCounter",
		clearcontent: false
	});

	$("#priceCounter, #titleCounter").change(function() {
		var priceCount = tempCountMax - parseInt($('#priceCounter').text());
		var titleCount = tempCountMax - parseInt($('#titleCounter').text());
		$("#totalCounter").text(descCountMax - priceCount - titleCount);
		$("textarea[name='description']").keyup();
	});

	$("textarea[name='longDescription']").charCounter(500, {
		container: "#longCnt",
		classname: "counter",
		format: "%1",
		pulse: true,
		delay: 100
	});

	$("#priceCounter, #titleCounter").change();

	$("#carProductCategory").change(function(e) {
		var carModelsArray = carModels.split(',');

		var found = false;
		var i = 0;
		while(i < carModelsArray.length) {
			if (this.value == carModelsArray[i]) {
				found = true;
				break;
			}
			i++;
		}

		if (!found) {
			$("#basicInfo").hide()
			$("#userInfo").hide()
			$("#vert_basic label").click()
		}

		var modelYearSelect = $("select[name='dataModel.modelYear']");
		carCategoryModelYearListUpdate(modelYearSelect, this.value);
		var inAugYearSelect = $("select[name='dataModel.inAugYear']");
		carCategoryModelYearListUpdate(inAugYearSelect, this.value);

	});

	if (intentionType == 'BUY') {
		document.getElementById("reqFieldprice").style.display="none";
		$("input[name='price.priceFinal']").css({display:"none"});
		$("input[name='price.priceFinal']").val("");
		showRequiredFields(requiredFields.buyFields);
	}

}


function carCategoryModelYearListUpdate(yearSelectList, categoryCode) {
	if (categoryCode == '00K001010005') {
		// Maastoautot, add into modelYear and inaugYear fields years all the way till 1960, inclusive (if there are not enough years yet).
		var minYear = 9999;
		yearSelectList.children().each(
			function(i, value) {
				var year = parseInt(value.value);
				if (year < minYear) {
					minYear = year;
				}
			}
		)
		if (minYear > 1960) {
			// Add the missing years into selection.
			for (var currentYear = minYear-1; currentYear >= 1960; currentYear--) {
				yearSelectList.append("<option value='" + currentYear + "'>" + currentYear + "</option>");
			}
		}
	}
	else {
		// Other than Maastoautot, remove the extra years that potentially are there.
		var valuesToRemove = [];
		yearSelectList.children().each(
			function(i, value) {
				if (i > 26) {
					// Older than 25 years, remove this option
					valuesToRemove.push(value.value);
				}
			}
		)
		for (i = 0; i < valuesToRemove.length; i++) {
			var year = valuesToRemove[i];
			yearSelectList.removeOption(year);
		}
	}
}


/**
 * This is to initialize the payment part of the
 * @return
 */
function initState2() {

	$("#prodcart").show();

	// Setup highlights on page load
	setBundles();
	setCart("#prodhighlight");

	$("#prodhighlight :radio, #prodhighlight :checkbox").click(function() {
		$('#highlights input').removeAttr("checked");
		setCart("#prodhighlight");
	});

	$("#clearHighlights").click(function(e) {
		e.preventDefault();
		$("#prodhighlight :radio, #prodhighlight :checkbox").attr({checked: false});
		setCart("#prodhighlight");
	});

	$("#bundle_i10").click(function() {
		if ($("#bundle_i10").is(":checked")) {
			$("a#huomioLink").trigger('click');
		}
	});

	$("#prodpaymentMethod").click(function() {
		// Delete the cancel/next/etc. buttons on payment click,
		// otherwise IE will send them as parameters.
		$("button[name^='_target']").remove();
	});

	$("button[name^='_target']").click(function() {
		// Delete the payment & next buttons on cancel/return/etc. click,
		// otherwise IE will send them as parameters.
		$("#prodpaymentMethod").remove();
		$("button[name='_finish']").remove();
	});

	var popupFrameWidth = 480;
	var popupFrameHeight = 310;
	if ($.browser.msie) {
		popupFrameWidth = 480;
		popupFrameHeight = 360;
	}

	var chosenPromo = null;

	huomioOpts = {
		'hideOnContentClick':	false,
		'zoomSpeedIn':			500,
		'zoomSpeedOut':			500,
		'frameWidth':			popupFrameWidth,
		'frameHeight':			popupFrameHeight,
		'overlayShow':			false,
		'callbackOnShow':		function() {
									if (chosenPromo != null) $("input[value=" + chosenPromo + "]").attr("checked","checked");
									$("#bundle_i10").attr("checked", "checked");
									$('div#fancy_div input[name="HUOM"]').live("click", function() {
										chosenPromo = $(this).val();
										$("input[name='HUOM']:checked").removeAttr("checked");
										$("input[value=" + chosenPromo + "]").attr("checked","checked");
										$("a#huomioLink").fancybox.close();
										setCart("#prodhighlight");
									});
								}
	};

	$("a#huomioLink").fancybox(huomioOpts);

	popupFrameWidth = 570;
	popupFrameHeight = 610;
	if ($.browser.msie) {
		popupFrameWidth = 625;
		popupFrameHeight = 500;
	}

	$("a.popup").fancybox({
		'imageScale':			false,
		'hideOnContentClick':	true,
		'zoomSpeedIn':			500,
		'zoomSpeedOut':			500,
		'frameWidth':			popupFrameWidth,
		'frameHeight':			popupFrameHeight,
		'overlayOpacity':		0.4,
		'overlayShow':			false
	});

}

function setBundles() {

	// Handle radiobuttons
	var nothingSet = true;
	$('input[name="bundle"]').each(function() {
		var stringToMatch = $(this).val().split(',').sort().toString();
		var checked = [];

		// Iterate everything but the bundles we know to be checkboxes
		$('#highlights input:checked:not(input[value="410"]):not(input[value="411"]):not(input[value="412"])')
			.each(function() {
			checked.push($(this).val());
		});
		checked.sort();

		if (stringToMatch == checked.toString()) {
			$(this).attr("checked", "checked");
			nothingSet = false;
		}
	});
	// Nothing has been selected, default to basic bundle
	if (nothingSet == true) {
		$('#prodhighlight input#bundle_i30').attr("checked", "checked");
		if ($('#prodhighlight input#bundle_i30').not(":checked"))
			// Couldn't find that bundle, check another
			$('#prodhighlight input#bundle_i11').attr("checked", "checked");
		setCart("#prodhighlight");
	}

	// Handle checkboxes
	$('input[name="bundle_check"]').each(function() {
		if($('#highlights input[value=' + $(this).val() + ']').attr("checked"))
			$(this).attr("checked", "checked")
	});

}

function setCart(path) {

	$("div#cartSummary")
		.children()
		.remove();

	$(path).find("li").each(function() {

		if ($(this)
			.find("input")
			.is(":checked")
			&&
			$(this)
			.find("input:checked")
			.parent().parent().parent()
			.attr("id") != "promoText") {

			$.each($(this).find("input").val().split(','), function(intIndex, objValue) {
				$('#highlights input[value=' + objValue + ']').attr("checked", "checked");
			});

			var line = $(this)
				.find("div.dotLeaderLight")
				.clone()
				.find("a.popup")
				.remove()
				.end()
				.find("a")
				.after('<span>' + $(this).find("a").text() +  '</span>')
				.remove()
				.end()
				.find("#huomioContent")
				.remove()
				.end();

			$(line).find('.cartText').text($(line).find('.cartText').text().replace(/[\. ]+$/, ''));

			if ($(line).find('.cartText').text().length > 58) {
				$(line).find('.cartText').text(jQuery.trim($(line).find('.cartText').text().substr(0,58)));
				$(line).find('.cartText').append("...");
			}

			$(line)
				.appendTo("div#cartSummary");

		}
	});

	updateTotal(path);
}


function updateTotal(path) {
	var totalPrice = 0;

	$(path).find("li").each(function() {
		if ($(this)
			.find("input")
			.is(":checked")) {

			var tempPrice = $(this)
				.find(".price")
				.text();

			if (tempPrice != "" &&
				tempPrice != null &&
				!isNaN(parseFloat(tempPrice.split(',').join('.'))) &&
				tempPrice.charAt(0) != ' ') {

				totalPrice += parseFloat(tempPrice.split(',').join('.'));
			}
		}
	});


	//Hide show the payment buttons
	if (totalPrice > 0) {
		$("#nextCont2").hide();
		$("#prodpaymentMethod").show();
	} else {
		$("#prodpaymentMethod").hide();
		$("#nextCont2").show();
	}

	var totalPriceText = totalPrice.toString().split('.').join(',').toString();
	if (totalPriceText.match(",.$")) {
		totalPriceText = totalPriceText + '0'; // Add missing decimal number...
	}

	$("#totalPrice").text(totalPriceText);
}

function changeCategorySet(item, callback, cbArg) {
	$("#mainProduct option").removeClass("active");
	$("#mainProduct option:selected").removeAttr("selected").addClass("active");
	$('#productSelect').html(categories[item.attr("id")]).css("width","200px"); // Set size for IE8 (KPMP-1648)

	if (typeof(callback) === 'function') {
		// (IE6 hack) short timeout to allow $('#productSelect').html(..) to finish
		setTimeout(function() {
			callback.call(this, cbArg);
		}, 100);
	}
}

/**
 * Selects the categories b4 sending the form
 * @return true
 */
function formSubmit() {
	if (page==0) {

		if ($("#productSelect option.active").length == 0) {
			$("#productSelect").html("<option value='' SELECTED></option>");
		}

		$("#productSelect option.active")
			.attr("selected","selected");
		$("#prodtitle input")
			.removeAttr("disabled");

	} else if (page==1) {

		// If Huomiologo is not checked...
		if ($("input#bundle_i10").is(':not(:checked)')) {
			$("#huomioContent").find("input:checked")
				// ...remove selection from popup...
				.removeAttr("checked");
		} else {
			// ...otherwise remove selection from 409 so we submit two of them.
			$('input[value="409"]').removeAttr("checked");
		}
	}
	return true;
}

function handleProductSelection(selected) {
	$("#productSelect option.active").removeClass("active");

	if (selected == '00K005045005') {
		// FancyBox for a CITES permission notification. If user selects "Muut lemmikkieläimet, then a CITES permission is required."
		$("a#cites_inline").click();
	}

	updateIntention(selected);

	$("#productSelect option:selected").removeAttr("selected").addClass("active");
	if (updateTitle) {
		updateSetTitle();
	}
}

function updateSetTitle() {
 	var intentionType = $("input[name='intention']:checked").val();
	if (intentionType == 'BUY') {
	    showRequiredFields(requiredFields.buyFields);
	}
	var titleLine = $.trim($("#mainProduct option.active").text());
	titleLine += " ";
	titleLine += $.trim($("#productSelect option.active").text());
	titleLine += " ";
	titleLine += $.trim($("#prodtype input").val());

	var modelYear = $("#prodmodelYear option:selected").val();
	if(modelYear != '') {
		titleLine += " -";
		titleLine += modelYear.slice(2);
	}

	$("#prodtitle input").val(titleLine);
	$("#titleCounter").text(tempCountMax - titleLine.length);
	$("#priceCounter, #titleCounter").change();
}

function updateIntention(selected) {
	if (jQuery.inArray(selected, intentionSettings.intentionOther.split(',')) != -1) {
		showIntention('OTHER,');
		// Intention changed. Updated required fields correspondingly.
		showRequiredFields(requiredFields.otherFields);
	} else if (jQuery.inArray(selected, intentionSettings.intentionWantsToRent.split(',')) != -1) {
		showIntention('WANTS_TO_RENT,');
		// Intention changed. Updated required fields correspondingly.
		showRequiredFields(requiredFields.otherFields);
	} else if (jQuery.inArray(selected, intentionSettings.intentionForRent.split(',')) != -1) {
		showIntention('FOR_RENT,');
		// Intention changed. Updated required fields correspondingly.
		showRequiredFields(requiredFields.defaultFields);
	} else {
		showIntention(intentionSettings.intentionDefault);
		// Intention changed. Updated required fields correspondingly.
		showRequiredFields(requiredFields.defaultFields);
	}
}

function showIntention(intentions) {
	$('#prodintention label').hide();
	$.each(intentions.split(','), function(intIndex, objValue) {
		$('#prodintention label:has(input[value=' + objValue + '])').show();
	});

	// If none of the visible ones is selected, select the first
	var foundChecked = false;
	$('#prodintention label:visible:has(input)').each(function() {
		if ($(this).find('input').is(':checked'))
			foundChecked = true;
	});
	if (foundChecked == false)
		$('#prodintention label:visible:first').find('input').attr("checked","checked");
}

/**
 * Set the form parameter so that move to page N could be done
 * @param N
 * @return
 */
function moveToPage(N) {
	$("#nextPage").attr('name','_target' + N);
	$("#command").submit();
}

function setField(field, value) {
	$(field).val(value);
}

function successLogin() {
	if (page == 0) {
		document.getElementById("command").doContacts.value="1";
		formSubmit();
		moveToPage(page);
	} else if (page == 1) {
		document.getElementById("toBeArchived").style.display="block";
	}
}

function hideRequiredFields() {
	$("h4[id^='reqField']").each(function(domElement) {
		this.style.backgroundImage='none';
	});
}

function showRequiredFields(reqList) {
	hideRequiredFields();
	var imgpath = "url(../../images/afs/extras/kepo/star.gif)";

	$.each(reqList.split(','), function(intIndex, obj) {
		$("h4[id='reqField" + obj + "']").each(function(domElement) {
			if(obj == "email" || obj == "phoneNumber") {
				this.style.backgroundImage = "url(../../images/afs/extras/kepo/star_red.gif)";
			}
			else {
				this.style.backgroundImage=imgpath;
			}
		});
	});
}


/**
 * Methods for automatic category finder
 */
function onTitleChange() {
    // Ignore if pressed key is del, shift or capslock
    if (lastKeyPressCode == 46 || (lastKeyPressCode > 8 && lastKeyPressCode < 32)) return;
    var v = $.trim($catInput.val());
    if (v == prevInput) return;
    prevInput = v;
    if (v.length >= 2) {
        requestCategoryData(v);
	}
}

function requestCategoryData(qStr) {
	prevKeyword = qStr;

    $.ajax({
        type: "GET",
        url: "/haku/ajax/categories?text=" + encodeURIComponent($.trim(qStr)),
        success: onCatSuccess,
		error: function() {
			// Clear results
            $catResults.html('');
        }
    });
}

function onCatSuccess(data) {
	var obj = parseCategoryJson(data);

	// Clear old results
	$catResults.html('');

	if (obj.categories) {
		for (var i = 0; i < obj.categories.length; i++) {

			// Get category id from json object
			var catId = obj.categories[i].name;
			var subCatId = "I" + catId;

			// Get main category from catId
			if (catId.length < 6) continue;
			var mainCatId = "I" + catId.substr(0, 9);

			// Get names for categories from list of categories
			var subCatName = '';
			var allSubCategories = $.trim(categories[mainCatId]);
			if ($(allSubCategories).length > 1) {
				var $catTemp = $("<span>").html($(allSubCategories));
				var subCatElem = $catTemp.find("option[value='" + catId + "']");
				subCatName = $.trim($(subCatElem).text());
				var mainCatName = $.trim($("#" + mainCatId).text());
			}

			// Create a link only if we know the category name
			if (subCatName != '') {

				// Create a link from category names
				var aLink = $('<a>').text(mainCatName + "\u00A0\u00BB\u00A0" + subCatName)
					.attr('href', '#')
					.attr('mainId', mainCatId)
					.attr('prodId', subCatId);

				// Clicking a link selects a category
				aLink.click(function(e) {
					e.preventDefault();
					$("#mainProduct  #" + $(this).attr('mainId')).attr("selected", true);

					var prodId = $(this).attr('prodId');
					changeCategorySet($("#mainProduct option:selected"), function(prodId) {
						var $selected = $("#productSelect #" + prodId);
						$selected.attr("selected", true);
						handleProductSelection($selected.val());
					}, prodId);
				});

				// Add link to results
				$catResults.append(aLink);
				$catResults.append('<br/>');
			}
		}

		// If content exists, add description
		var linkCount = $catResults.find('a').size();
		if (linkCount > 1) {
			$catResults.prepend("<h4 style='width: 300px;'>Kävisikö joku näistä osastoista? Valitse tästä.</h4>");

		} else if (linkCount > 0) {
			$catResults.prepend("<h4 style='width: 300px;'>Kävisikö osastoksi? Valitse tästä.</h4>");

		} else {
			// No results, try again with ' OR ' (but just once)
			if (prevKeyword.indexOf(' OR ', 0) == -1 &&
				prevKeyword.indexOf(' ', 0) != -1) {
				var searchString = prevKeyword.replace(/[ ]+/gi, ' OR ');
				requestCategoryData(searchString);
			}
		}

		if (linkCount > 0) {
			// Blink results
			$catResults.fadeOut(100).fadeIn(100).fadeOut(100).fadeIn(100);
		}
	}
}

function parseCategoryJson(data) {
	// Parse & evaluate json string to a javascript object.
	return (data.replace(/"(\\.|[^"\\])*"/g, '') &&
		eval('(' + data.replace(/&#034;/gi, "\"") + ')'));
}