/***************************************************************************************************
* General stuff                                                                                    *
***************************************************************************************************/
var initFlash = function () {
	if ($('img.dynamicFlash').length == 0) {
		return false;
	}
	
	var validTags = new Array('img');//'div', (Not sure how to get the src / href from div)
	for (var i = 0; i < validTags.length; i++) {
		$(validTags[i] + '.dynamicFlash').each(function () {
			if (!this.id || this.id == '') {
				this.id = 'dynamicFlash_' + Number(Math.random());
			}
			var src = this.src.replace(/\.(gif|jpg|png|jpeg)$/i, '.swf');
			
			// Check if parent is an anchor
			var bannerLink = '';
			var elements = $(this).parents();
			for (var j in elements) {
				if (typeof elements[j] != 'function') {
					if (elements[j].tagName == 'A') {
						bannerLink = elements[j].href;
						break;
					}
				}
			}
			
			// embedSWF: function (swfUrlStr, replaceElemIdStr, widthStr, heightStr, swfVersionStr, xiSwfUrlStr, flashvarsObj, parObj, attObj, callbackFn)
			swfobject.embedSWF(src, this.id, this.width, this.height, "9.0.0", null, { bannerLink: bannerLink }, { wmode: "transparent" }, {});
		});
	}
}

var initListTreeExpanding = function () {
	// Quick check to see if component is used
	if ($('dl.listTreeExpanding').length < 1) {
		return false;
	}
	
	$('dl.listTreeExpanding dd').hide();
	$('dl.listTreeExpanding dt').attr('class', 'closed');
	$('dl.listTreeExpanding dt').click(function () {
		if ($(this).next().is('dd')) {
			$(this).next().toggle('fast', function () {
				if ($(this).css('display') == 'none') {
					$(this).prev().attr('class', 'closed');
				} else {
					$(this).prev().attr('class', 'opened');
				}
			});
			return false;
		}
		return true;
	});
}

var initPrintButton = function () {
	// Quick check to see if component is used
	if ($('.printButton').length < 1) {
		return false;
	}
	
	if (window.print) {
		$('.printButton').show();
		$('.printButton').click(function () {
			window.print();
			return false;
		});
	}
}

// Run startup scripts
$(document).ready(function () {
	initFlash();
	initListTreeExpanding();
	initPrintButton();
	//initGoogleMaps(); // Initialised on demand
});

/***************************************************************************************************
* Google maps                                                                                      *
***************************************************************************************************/
var googleMaps;
var initGoogleMaps = function () {
	if (!googleMaps) {
		googleMaps = new googleMapsHelper();
	}
}

var googleMapsHelper = function () {
	this.debug = false;
	this.gmarkers = new Array();
	this.i = 0;
	this.map;
	this.gdir;
	this.geocoder = new GClientGeocoder();
	this.localSearch = new GlocalSearch();
	this.locale = 'EN';

	this.createMarker = function(point, name, html, editing, idlemarker) {//alert(name);
		var icon = new GIcon();
		if (idlemarker) {
			icon.image = baseUrl + '/images/content/google_marker_idle.gif';
		} else {
			icon.image = baseUrl + '/images/content/google_marker.gif';
		}
		icon.iconSize = new GSize(30,31);
		icon.iconAnchor = new GPoint(15,15);
		icon.infoWindowAnchor = new GPoint(30, 0);
		
		if (editing) {
			var marker = new GMarker(point, {draggable: true});
			GEvent.addListener(marker, "click", function() {
				marker.openInfoWindowHtml(html);
			});
			GEvent.addListener(marker, "dragend", function() {
				$('#latitude').val(gmarkers[0].getPoint().lat());
				$('#longitude').val(gmarkers[0].getPoint().lng());
			});
		} else {
			var marker = new GMarker(point, icon);
			GEvent.addListener(marker, "click", function() {
				marker.openInfoWindowHtml(html);
			});
		}
		
		googleMaps.gmarkers[googleMaps.i] = marker;
		googleMaps.i++;
		return marker;
	};
	
	this.doMapClick = function(i) {
		GEvent.trigger(gmarkers[i], "click");
	};
	
	this.onGDirectionsLoad = function() {
		$("#driving_directions").html('');
	};
	
	this.getDirections = function(fromAddress, toAddressLat, toAddressLng) {
		if (googleMaps.gdir) {alert("from: " + fromAddress.lat + "," + fromAddress.lng + " to: " + toAddressLat + "," + toAddressLng);
			googleMaps.gdir.load("from: " + fromAddress.lat + "," + fromAddress.lng + " to: " + toAddressLat + "," + toAddressLng, { "locale": googleMaps.locale });
		}
		if (window.event) { window.event.cancelBubble = true; }
		return false;
	};
	
	this.showHideDirections = function() {
		if ($("#driving_directions").html() == 'Show driving directions') {
			$("#driving_directions").html('Hide driving directions');
			$('#driving_directions').show();
		} else {
			$("#driving_directions").html('Show driving directions');
			$('#driving_directions').hide();
		}
		if (window.event) { window.event.cancelBubble = true; }
		return false;
	};
	
	this.handleErrors = function() {
		if (debug == true) {
			if (gdir.getStatus().code == G_GEO_UNKNOWN_ADDRESS)
				alert("No corresponding geographic location could be found for one of the specified addresses. This may be due to the fact that the address is relatively new, or it may be incorrect.\nError code: " + gdir.getStatus().code);
			else if (gdir.getStatus().code == G_GEO_SERVER_ERROR)
				alert("A geocoding or directions request could not be successfully processed, yet the exact reason for the failure is not known.\n Error code: " + gdir.getStatus().code);
			else if (gdir.getStatus().code == G_GEO_MISSING_QUERY)
				alert("The HTTP q parameter was either missing or had no value. For geocoder requests, this means that an empty address was specified as input. For directions requests, this means that no query was specified in the input.\n Error code: " + gdir.getStatus().code);
			//else if (gdir.getStatus().code == G_UNAVAILABLE_ADDRESS)  <--- Doc bug... this is either not defined, or Doc is wrong
			//	alert("The geocode for the given address or the route for the given directions query cannot be returned due to legal or contractual reasons.\n Error code: " + gdir.getStatus().code);
			else if (gdir.getStatus().code == G_GEO_BAD_KEY)
				alert("The given key is either invalid or does not match the domain for which it was given. \n Error code: " + gdir.getStatus().code);
			else if (gdir.getStatus().code == G_GEO_BAD_REQUEST)
				alert("A directions request could not be successfully parsed.\n Error code: " + gdir.getStatus().code);
			else alert("An unknown error occurred.");
		} else {
			alert('An error occurred, please try again later.');
		}
	};
	
	this.gotoPostcode = function(postcode, toAddressLat, toAddressLng) {
		// Search for postcode and pan to it
		if (!postcode.match(/( |,)uk$/i)) {
			postcode+= ', UK';
		}
		googleMaps.localSearch.setSearchCompleteCallback(null, 
			function () {
				if (googleMaps.localSearch.results[0]) {		
					var resultLat = googleMaps.localSearch.results[0].lat;
					var resultLng = googleMaps.localSearch.results[0].lng;
					var point = new GLatLng(resultLat,resultLng);
					if (toAddressLat && toAddressLng) {
						googleMaps.getDirections(googleMaps.localSearch.results[0], toAddressLat, toAddressLng);
						googleMaps.showHideDirections();
					} else {
						googleMaps.map.setZoom(10);
						googleMaps.map.panTo(point);
					}
				} else {
					alert(postcode + " not found");
				}
			}
		);
		googleMaps.localSearch.execute(postcode);
		
		if (window.event) { window.event.cancelBubble = true; }
		return false;
	};
};

/***************************************************************************************************
* Form stuff                                                                                       *
***************************************************************************************************/
var handleHearAbout = function () {
	$('#hear_about_store_tr').hide();
	$('#hear_about_cinema_tr').hide();	
	$('#hear_about_details_tr').hide();
	switch ($('select[name="hear_about"]').val()) {
		case 'Tesco Store':
			$('#hear_about_store_tr').show();
			handleHearAboutStore();
			break;
		case 'Local Cinema':
			$('#hear_about_cinema_tr').show();
			handleHearAboutStore();
			break;			
		case 'Other':
			$('#hear_about_details_tr').show();
			$('#hear_about_details_tr label').html('Specify Other:');
			break;
		case 'People Newspaper':
			$('#hear_about_details_tr').show();
			$('#hear_about_details_tr label').html('People Ref. No.');
			break;
	}
	//alert($('select[name="hear_about"]').val());
};

var handleHearAboutStore = function () {
	if (($('select[name="hear_about"]').val()=='Tesco Store' && $('select[name="hear_about_store"]').val() == 'Other') || ($('select[name="hear_about"]').val()=='Local Cinema' && $('select[name="hear_about_cinema"]').val() == 'Other')) {
		$('#hear_about_details_tr').show();
		$('#hear_about_details_tr label').html('Specify Other:');
	} else {
		$('#hear_about_details_tr').hide();
	}
	//alert($('select[name="hear_about_store"]').val());
};

var handleTescoStore= function () {
	if ($('input:radio[name="is_tesco_staff"]:checked').val() == '1') {
		$('#tesco_staff_tr').show();
	} else {
		$('#tesco_staff_tr').hide();
	}
	//alert($('select[name="hear_about_store"]').val());
};
