// The next line enables jQuery IntelliSense in Visual Studio:
/// <reference path="/common/js/IntelliSense/jquery-1.3.1-vsdoc.js" />

$(document).ready(function() {

   	$('form:first *:input[type!=hidden]:first').focus();

	$("input.quantity").keydown(function(event) {
		switch (event.keyCode) {
			case 38:
				AddQuantity(this.id.replace('artikel_', '')); break;
			case 40:
				SubtractQuantity(this.id.replace('artikel_', '')); break;
		}
	});

	$("img.add_quantity").click(function() {
		AddQuantity(this.id.replace('add_', ''));
	});

	$("img.subtract_quantity").click(function() {
		SubtractQuantity(this.id.replace('subtract_', ''));
	});

	function AddQuantity(artikel_id) {
		// Note: because artikel_id contains a dot a selector like $("input#artikel_" + artikel_id) will not work
		var input = $(":input[name = 'artikel_" + artikel_id + "']")
		var value = input.attr("value") * 1;
		if (value + 1 > 0) {
			input.attr("value", value + 1);
		} else {
			input.attr("value", "1");
		}
		input.focus()
	}

	function SubtractQuantity(artikel_id) {
		// Note: because artikel_id contains a dot a selector like $("input#artikel_" + artikel_id) will not work
		var input = $(":input[name = 'artikel_" + artikel_id + "']")
		var value = input.attr("value") * 1;
		if (value - 1 > 0) {
			input.attr("value", value - 1);
		} else {
			input.attr("value", "0");
		}
		input.focus()
	}

	$("button.removeall").click(function() {
		if (confirm('Weet u zeker dat uw winkelwagen helemaal wilt leegmaken?')) {
			$("input.quantity").attr("value", "0");
			// Remove all other buttons because IE6 passes ALL <button type="submit"> elements back to the server on submit instead of just the clicked one.
			$("button:not(.removeall)").remove();
			return true;
		} else {
			return false;
		}
	});

	$("button.herberekenen").click(function() {
		// Remove all other buttons because IE6 passes ALL <button type="submit"> elements back to the server on submit instead of just the clicked one.
		$("button:not(.herberekenen)").remove();
	});

	$("button.removearticle").click(function() {
		if (confirm('Weet u zeker dat u dit artikel wilt verwijderen?')) {
			// Note: because the id contains a dot a selector like $("input#artikel_" ...) will not work
			$(":input[name = 'artikel_" + this.id.replace('removearticle_', '') + "']").attr("value", "0");
			return true;
		} else {
			return false;
		}
	});

	$("#toonallemerken a").click(function() {
		$("ul li.notselected").show();
		$("#toonallemerken").hide();
		$("#verfijnen").hide();
		$("#merken-shortlist ul li").removeClass("selected");
	});

	$("a#toonschoen").click(function() {
		$("#zoom-schoen").show();
		$("#zoom-zool").hide();
	});

	$("a#toonzool").click(function() {
		$("#zoom-zool").show();
		$("#zoom-schoen").hide();
	});

	$('.showOnGoogleMap').click(function() {
		$('.GoogleMapContainer').hide();
		showGoogleMap(this.title, this.rel, $('#address' + this.rel).html());
	});

	$('#SegmentToggle').click(function() { // Do not use the change event here because it's buggy in IE: http://www.quirksmode.org/dom/events/change.html
		var isChecked = this.checked; // 'Selecteer alle merken' has been checked or unchecked
		// Loop through all 'Toon het merk ..' and 'Toon het artikel ..' checkboxes and check them when 'Selecteer alle merken' has been checked (and vice versa)
		$('input.segment, input.item').each(function() { this.checked = isChecked });
		switch (isChecked) {
			case true: $('.segmentitems').show(); break;  // show all sub items when 'Selecteer alle merken' is checked
			case false: $('.segmentitems').hide(); break; // hide all sub items when 'Selecteer alle merken' is unchecked
		}
	});

	$('.ItemToggle').click(function() { // Do not use the change event here because it's buggy in IE: http://www.quirksmode.org/dom/events/change.html
		var id = this.id + '';
		var segmentId = id.substring(0, id.indexOf('_', 0));
		var isChecked = this.checked; // A '(De)selecteer al deze artikelen' has been checked or unchecked
		// Loop through all the 'Toon het artikel ..' checkboxes for this merk and check them when '(De)selecteer al deze artikelen' has been checked (and vice versa)
		$('#' + segmentId + 'Items input.item').each(function() { this.checked = isChecked });
		// Check this merk's 'Toon het merk ..' checkbox when '(De)selecteer al deze artikelen' has been checked (and vice versa)
		$('#' + segmentId).each(function() { this.checked = isChecked });
	});

	$('input.segment').click(function() { // Do not use the change event here because it's buggy in IE: http://www.quirksmode.org/dom/events/change.html
		var id = this.id + '';
		var isChecked = this.checked; // A 'Toon het merk ..' has been checked or unchecked
		// Loop through all the 'Toon het artikel ..' checkboxes for this merk and check them when '(De)selecteer al deze artikelen' has been checked (and vice versa)
		$('#' + id + 'Items input').each(function() { this.checked = isChecked });
		switch (isChecked) {
			case true: $('#' + id + 'Items').show(); break;  // show all sub items when this 'Toon het merk ..' is checked
			case false: $('#' + id + 'Items').hide(); break; // hide all sub items when this 'Toon het merk ..'  is unchecked
		}
	});

	$('input.item').click(function() { // Do not use the change event here because it's buggy in IE: http://www.quirksmode.org/dom/events/change.html
		var id = this.id + '';
		var segmentId = id.substring(0, id.indexOf('_', 0)); // A string like "Segment10"
		if (this.checked) { // A 'Toon het artikel ..' has been checked
			$('#' + segmentId).each(function() { this.checked = true }); // Check this merk's 'Toon het merk ..' checkbox
		} else { // A 'Toon het artikel ..' has been unchecked
			//alert($('input[id*=' + segmentId + '_]:checked.item').length)

			if ($('input[id*=' + segmentId + '_]:checked.item').length == 0) {
				// There are no checkboxes that:
				// 1) have an id that contains segmentId ('input[id*=' + segmentId + ']')
				// 2) are checked (':checked')
				// 3) have an 'item' class ('.item')
				$('#' + segmentId).each(function() { this.checked = false }); // Uncheck this merk's 'Toon het merk ..' checkbox
				$('#' + segmentId + '_Item_Toggle').each(function() { this.checked = false }); // Uncheck this merk's '(De)selecteer al deze artikelen' checkbox
			};
		};
	});



});

function showGoogleMap(addressCityCountry, mapId, markerHTML) {
	//var relVal = this.rel + '';
	$('#map' + mapId).jmap('SearchAddress', {
		'query': addressCityCountry,
		'returnType': 'getLocations'
	}, function(result, options) {
		var valid = Mapifies.SearchCode(result.Status.code);
		if (valid.success) {
			$('#GoogleMapContainer' + mapId).slideDown('slow'); // hiding the map itself causes off-center marker placement
			$('#map' + mapId).jmap('CheckResize'); // Check if a map container element has been resized or toggled from show/hide
			$.each(result.Placemark, function(i, point) {
				$('#map' + mapId).jmap('AddMarker', {
					'pointLatLng': [point.Point.coordinates[1], point.Point.coordinates[0]]
                         , 'pointHTML': markerHTML //point.address
                         , 'centerMap': true
				});
			});
		} else {
			alert(valid.message);
		}
	});

}

function addOptionToListBox(name, value, label, selected) {
	var selectedAttribute;
	if (selected) selectedAttribute = "selected=\"selected\""
	$("select[name='" + name + "']").append("<option value=\"" + value + "\" " + selectedAttribute + ">" + label + "</option>")
}

function reloadPhoto(id) {
	var src = $("#photo" + id).attr("src");
	$("#photo" + id).attr("src", src + "reload/?rnd=" + Math.floor(Math.random() * 1000000)); // add a random number to prevent caching
	src = $("#photozool" + id).attr("src");
	$("#photozool" + id).attr("src", src + "reload/?rnd=" + Math.floor(Math.random() * 1000000)); // add a random number to prevent caching
}

// Replaces all instances of the given substring.
String.prototype.replaceAll = function(
	strTarget, // The substring you want to replace
	strSubString // The string you want to replace in.
	){
	var strText = this;
	var intIndexOfMatch = strText.indexOf( strTarget );
	
	// Keep looping while an instance of the target string
	// still exists in the string.
	while (intIndexOfMatch != -1){
	// Relace out the current instance.
	strText = strText.replace( strTarget, strSubString )
	
	// Get the index of any next matching substring.
	intIndexOfMatch = strText.indexOf( strTarget );
	}
	
	// Return the updated string with ALL the target strings
	// replaced out with the new substring.
	return( strText );
}