// instantiate global variables
var schoolProfile;
var map;
var panoLayer;
var wikiLayer;

var discountImage = ' <image src="http://www.eurolanguages.com/images/special_small_0217.gif" />';


$(document).ready(function() 
{
	// bind filterSchools function to the change event of the filters
	$("#school_filter #city").change(filterSchools);
	$("#school_filter #course_type").change(filterSchools);
	//$("#school_filter #month").change( function() { if ($("#school_filter #year").val() != "") filterSchools(); } );
	//$("#school_filter #year").change( function() { if ($("#school_filter #month").val() != "") filterSchools(); } );
	$("#school_filter #weeks").change(filterSchools);
	$("#school_filter #flexible").change(filterSchools);

	// bind updateSchools function to the click event of the update list button
	$("#school_filter #update_list").click(updateSchools);

	// initialise tablesorter 
	$("#school_listing table").tablesorter( { sortList:[[2,1], [3,0]] } );

	// initialise school listing
	initialiseSchoolListing();

	// initialise the carousel
	$("#carousel").jcarousel( { scroll: 1, visible: 1 } );

	// bind initialisation of the carousel to the click event of the info link
	$("#school_window #info_link").click(function() {
		// info tab MUST be visible to be initialised correctly
		$("#school_window #info_tab").show();

		// initialise the carousel
		$("#carousel").jcarousel( { scroll: 1, visible: 1 } );
	});

	// bind showSchoolMap function to the click event of the map link
	$("#school_window #map_link").click(showSchoolMap);

	// bind function to send enquiry button
	$("#school_window #send_enquiry").click(function() {
		var school_name = $("#school_window #school_name span").html();
		$("#enquiry_box #enquiry_subject").val("Enquiry for "+school_name+" (eurolanguages)");
		$("#enquiry_box #enquiry_to").html(school_name);
	});

	// initialise map controls
	initialiseMapControls();
});


$(document).unload(function()
{
	// prevents memory leaks
	GUnload();
});


function initialiseTabs()
{
	// initialise tabs 
	$("#school_window #tabs #tab_list").tabs();
}


function initialiseSchoolListing() 
{
	// show school profile for first school in listing
	if ($("#school_window #school_name").html() == "") {
		$("#school_listing td.school_link:first").each(showSchoolProfile);
	}

	// bind showSchoolProfile function to the click event of each school in the school listing
	$("#school_listing td.school_link").click(showSchoolProfile);

	// bind hightlight and remove functions to the star and delete for each school in the school listing
	$("#school_listing td.star").click(function() {
		if ($(this).parent().attr("class") == "highlighted" || $(this).parent().attr("class") == "selected highlighted" || $(this).parent().attr("class") == "highlighted selected") {$(this).parent().removeClass("highlighted");}
		else {
			$(this).parent().addClass("highlighted");
			$(this).each(showSchoolProfile);
		}
	});

	$("#school_listing td.remove").click(function() {
		$(this).parent().remove();

		// resort school listing
		$("#school_listing table").trigger('reSort');
	});
}


function filterSchools() 
{
	// show loading animation
	$("#school_filter #number_of_schools").html('<img src="http://www.eurolanguages.com/images/loading_blue.gif" />');
	
	// get the values of the filters
	var city = $("#school_filter #city").val();
	var course_type = $("#school_filter #course_type").val();
	//var month = $("#school_filter #month").val();
	//var year = $("#school_filter #year").val();
	var weeks = $("#school_filter #weeks").val();

	// load the remote ajax file using a http post request
	$.ajax({
		type: "POST",
		dataType: "html",
		url: "http://www.eurolanguages.com/ajax.php",
		data: "action=getNumberOfSchools&search_city="+city+"&search_course_type="+course_type+"&search_weeks="+weeks,
		success: function(num) 
		{	
			// update the number of schools found
			if (num == 1) {
				$("#school_filter #number_of_schools").html("&raquo; "+num);
			}
			else {
				$("#school_filter #number_of_schools").html("&raquo; "+num);
			}
		}
	});
}


function updateSchools() 
{
	// remove schools from list
	$("#school_listing tbody").html('<tr><td colspan="5"> Loading schools...</td></tr>');

	// get the values of the filters
	var city = $("#school_filter #city").val();
	var course_type = $("#school_filter #course_type").val();
	//var month = $("#school_filter #month").val();
	//var year = $("#school_filter #year").val();
	var weeks = $("#school_filter #weeks").val();

	// get the currency
	var currency = $("#school_filter #currency").val();

	// load the remote ajax file using a http post request
	$.ajax({
		type: "POST",
		dataType: "json",
		url: "http://www.eurolanguages.com/ajax.php",
		data: "action=getSchoolListing&search_city="+city+"&search_course_type="+course_type+"&search_weeks="+weeks+"&user_currency="+currency,
		success: function(json) 
		{
			// remove schools from list
			$("#school_listing tbody").empty();

			var new_schools = new Array("");

			// iterate through json array and create new school listing
			$.each(json, function(i, school) {
				var tr_class = ($("#school_window #school_name span").html() == school.school_name) ? ' class="selected"' : '';
				new_schools.push('<tr id="');
				new_schools.push(school.school_profile_id);
				new_schools.push('"');
				new_schools.push(tr_class);
				new_schools.push('><td id="school_name" class="school_link" title="Click to view school">');
				new_schools.push(school.school_name);
				new_schools.push('</td><td class="school_link" title="Click to view school">');
				new_schools.push(school.city);
				new_schools.push('</td><td class="school_link rating" title="Click to view school">');
				new_schools.push(school.average_rating);
				new_schools.push('</td><td class="school_link price" title="Click to view school">');
				new_schools.push(school.min_price);
				new_schools.push('</td><td class="school_link lessons" title="Click to view school">/');
				new_schools.push(school.lessons);
				new_schools.push('</td><td></td></tr>');
			});

			// check if no schools were returned
			if (json.length == 0) {
				new_schools.push('<tr><td colspan="5">&nbsp;</td></tr>');			
			}
			
			// add new schools to school list
			$("#school_listing tbody").html(new_schools.join(""));

			// resort school listing
			$("#school_listing table").trigger('reSort');

			// reinitialise school listing
			initialiseSchoolListing();
		}
	});
}


function showSchoolProfile() 
{
	// if the map tab is currently selected then show info tab
	if ($("#school_window #tabs #tab_list").tabsSelected() == 2)
	{
		$("#school_window #map_tab").hide();
		$("#school_window #info_tab").show();
	}

	// reset reviews tab label
	$("#school_window #tabs #tab_list #reviews_tab_label").html("Reviews");

	// remove text from top
	$("#school_window #top").html("");
	
	// show loading tab and hide content in all tabs
	$("#school_window #tabs .content").hide();
	$("#school_window #tabs #loading_tab").show();

	// remove content from map tab
	$("#school_window #map").html("");

	// remove the selected class from all schools in the school listing
	$("#school_listing tr").removeClass("selected");
	
	// add the selected class to the newly selected school in the school list
	$(this).parent().addClass("selected");

	// get the values of the filters
	var city = $("#school_filter #city").val();
	var month = $("#school_filter #month").val();
	var year = $("#school_filter #year").val();
	var weeks = $("#school_filter #weeks").val();

	// get the currency
	var currency = $("#school_filter #currency").val();

	// get the school id of the newly selected school
	var school_id = $(this).parent().attr("id");

	// load the remote ajax file using a http post request
	$.ajax({
		type: "POST",
		dataType: "json",
		url: "http://www.eurolanguages.com/ajax.php",
		data: "action=getSchoolDetails&search_month="+month+"&search_year="+year+"&search_weeks="+weeks+"&user_currency="+currency+"&id="+school_id+"&user_language=en",
		success: function(json) 
		{
			// if the map tab is currently selected then show info tab
			if ($("#school_window #tabs #tab_list").tabsSelected() == 2)
			{
				$("#school_window #tabs #tab_list").tabsClick(1);
			}

			// hide loading message and show content in all tabs EXCEPT for the map tab
			$("#school_window #tabs #loading_tab").hide();
			$("#school_window #tabs .content").show();

			// page title
			document.title = json.school_name+" - Learn Spanish in "+json.city+", "+json.country;

			// replace html (using our super-fast function)
			replaceHtml("top", json.top);
			replaceHtml("facts", json.facts);
			replaceHtml("photos", json.photos);
			replaceHtml("closed_dates", json.school_closed_dates);
			replaceHtml("quick_courses", json.quick_courses);
			replaceHtml("quick_course_details", json.quick_course_details);
			replaceHtml("quick_accommodations", json. quick_accommodations);
			replaceHtml("quick_accommodation_details", json. quick_accommodation_details);
			replaceHtml("facilities_icons", json.facilities_icons);
			replaceHtml("facilities", json.facilities);
			replaceHtml("description_start", json.description_start);
			replaceHtml("description_end", json.description_end);
			replaceHtml("directions", json.directions);
			//replaceHtml("courses", json.courses);
			//replaceHtml("accommodation", json.accommodations);
			replaceHtml("reviews", json.reviews);

			// number of reviews
			if (json.number_of_reviews > 0) {
				replaceHtml("reviews_tab_label", "Reviews ("+json.number_of_reviews+")");
			}

			// initialise the carousel
			$("#carousel").jcarousel( { scroll: 1, visible: 1 } );

			// clear and setup shadowbox
			Shadowbox.setup();

			// bind function to send enquiry button
			$("#school_window #send_enquiry").click(function() {
				var school_name = $("#school_window #school_name span").html();
				$("#enquiry_box #enquiry_subject").val("Enquiry for "+school_name);
				$("#enquiry_box #enquiry_to").html(school_name);
			});

			// set the global schoolProfile variable
			schoolProfile = json;
		}
	});
}


function showSchoolMap()
{
	// if the map has not yet been initialised
	if ($("#school_window #map").html() == "")
	{
		// if the school profile has a latitude and longitude value
		if ((schoolProfile.latitude && schoolProfile.longitude) && GBrowserIsCompatible()) 
		{
			// map MUST be visible to be initialised correctly
			$("#school_window #map_tab").show();

			// create map and add controls
			map = new GMap2(document.getElementById("map"));	
			map.addControl(new GLargeMapControl());
			map.addControl(new MapControls());
			//map.addControl(new GMapTypeControl());

			// set centre of map to coordinates of school and add zoom and map type controls
			var center = new GLatLng(schoolProfile.latitude, schoolProfile.longitude);
			map.setCenter(center, 15);	
	
			// create marker icon
			var schoolIcon = new GIcon();
			schoolIcon.image = "http://maps.google.com/mapfiles/kml/pal2/icon10.png"; //"http://www.eurolanguages.com/images/gmap_icon.png";
			schoolIcon.shadow = "http://maps.google.com/mapfiles/kml/pal2/icon10s.png"; //"http://www.eurolanguages.com/images/gmap_icon_shadow.png";
			schoolIcon.iconSize = new GSize(32, 32);
			schoolIcon.shadowSize = new GSize(56, 32);
			schoolIcon.iconAnchor = new GPoint(16, 32);
			schoolIcon.infoWindowAnchor = new GPoint(16, 0);

			// set html for marker
			var html = new Array('<div id="map_marker"><div id="icon"><img src="http://www.eurolanguages.com/images/school_photos/');
			html.push(schoolProfile.icon);
			html.push('" width="82" align="left" /></div><div><div id="title">');
			html.push(schoolProfile.school_name);
			html.push('</div><div id="address">');
			html.push(schoolProfile.street_address);
			html.push('<br/>');
			html.push(schoolProfile.city);
			html.push('<br/>');
			html.push(schoolProfile.country);
			html.push('<br/>(<a href="#directions_text">Directions</a>)</div></div></div>');
			html = html.join("");
	
			// create a marker with an info window
			var point = new GLatLng(schoolProfile.latitude, schoolProfile.longitude);
			var marker = new GMarker(center, {icon: schoolIcon, title: schoolProfile.school_name});
			GEvent.addListener(marker, "click", function() {marker.openInfoWindowHtml(html);});

			// add marker to map
			map.addOverlay(marker);

			// open html window
			marker.openInfoWindowHtml(html);

			// define layers
			panoLayer = new GLayer("com.panoramio.all");
			wikiLayer = new GLayer("org.wikipedia.en");
		}
	}
}


function updateQuickCourse(course_type)
{
	// get course id, weeks, start date and price
	var course_id = $("#"+course_type+"_lessons").val();
	var course_weeks = $("#"+course_type+"_"+course_id+"_weeks").val();
	var start_date = $("#"+course_type+"_"+course_id+"_start_dates").val();
	var price = $("#"+course_type+"_"+course_id+"_weeks option:selected").attr("title");

	// show appropriate link, weeks, start dates, and price
	$("#"+course_type+"_links a").hide();
	$("#"+course_type+"_"+course_id+"_link").show();
	$("#"+course_type+"_weeks select").hide();
	$("#"+course_type+"_"+course_id+"_weeks").show();
	$("#"+course_type+"_start_dates select").hide();
	$("#"+course_type+"_"+course_id+"_start_dates").show();
	$("#"+course_type+"_price").html(price);

	// update course details
	var weeks = $("#"+course_type+"_"+course_id+"_weeks option:selected").html();
	var start_date = $("#"+course_type+"_"+course_id+"_start_dates").val();
	$("#course_details_"+course_id+" #weeks").html(weeks);
	$("#course_details_"+course_id+" #start_date").html(start_date);
	$("#course_details_"+course_id+" #price").html(price);

}


function updateQuickAccommodation(accommodation_type)
{
	// get accommodation id, weeks and price
	var accommodation_id = $("#"+accommodation_type+"_board_types").val();
	var accommodation_weeks = $("#"+accommodation_type+"_"+accommodation_id+"_weeks").val();
	var price = $("#"+accommodation_type+"_"+accommodation_id+"_weeks option:selected").attr("title");

	// show appropriate link, weeks, button and price
	$("#"+accommodation_type+"_links a").hide();
	$("#"+accommodation_type+"_"+accommodation_id+"_link").show();
	$("#"+accommodation_type+"_weeks select").hide();
	$("#"+accommodation_type+"_"+accommodation_id+"_weeks").show();
	$("#"+accommodation_type+"_price").html(price);

	// update accommodation details
	var weeks = $("#"+accommodation_type+"_"+accommodation_id+"_weeks option:selected").html();
	$("#accommodation_details_"+accommodation_id+" #weeks").html(weeks);
	$("#accommodation_details_"+accommodation_id+" #price").html(price);
}


function bookQuickCourse(course_type)
{
	// get course id and weeks
	var course_id = $("#"+course_type+"_lessons").val();
	var course_weeks = $("#"+course_type+"_"+course_id+"_weeks").val();

	// get start date and price from shadowbox
	var start_date = $("#shadowbox_content #"+course_type+"_"+course_id+"_start_dates").val();
	var course_level = $("#shadowbox_content #"+course_type+"_"+course_id+"_course_level").val();

	// if not found in shadowbox
	if (!start_date) {
		var start_date = $("#"+course_type+"_"+course_id+"_start_dates").val();
		var course_level = $("#"+course_type+"_"+course_id+"_course_level").val();
	}

	// update form inputs
	$("#quick_courses_form #course_id").val(course_id);
	$("#quick_courses_form #course_weeks").val(course_weeks);
	$("#quick_courses_form #start_date").val(start_date);
	$("#quick_courses_form #course_level").val(course_level);

	$("#quick_courses_form").submit();
}


function showPanoLayer()
{
	if ($("#pano_checkbox").attr("checked")) {map.addOverlay(panoLayer);}
	else {map.removeOverlay(panoLayer);}
}


function showWikiLayer()
{
	if ($("#wiki_checkbox").attr("checked")) {map.addOverlay(wikiLayer);}
	else {map.removeOverlay(wikiLayer);}
}


function replaceHtml(el, html) 
{
	var oldEl = typeof el === "string" ? document.getElementById(el) : el;

	/*@cc_on // Pure innerHTML is slightly faster in IE
		oldEl.innerHTML = html;
		return oldEl;
	@*/

	var newEl = oldEl.cloneNode(false);
	newEl.innerHTML = html;
	oldEl.parentNode.replaceChild(newEl, oldEl);

	return newEl;
}
