/* common functions */

jQuery.fn.extend({
	scrollToThis: function(duration) {
		var t = duration || 20,
			g = jQuery(this).eq(0).offset().top; // only scrolls to first matched element
			smoothScroll = setInterval(function() {
				var distance = (document.body.scrollTop || document.documentElement.scrollTop) - g;
				
				if(Math.ceil(distance) < 0)
				{
					window.scrollBy(0, 0 - distance);
					clearInterval(smoothScroll);
				}
				
				if (Math.ceil(distance) > 5) {
					window.scrollBy(0, 0 - distance / 5);
				} else {
					clearInterval(smoothScroll);
				}
			}, t);
	}
});

var url = {
	/*
	*	Utitlity for inspecting URL
	* eg: url.get('vessel_name');   returns value of vessel name from query string
	*
	*/

	hostname: function() {
		return window.location.host.toString();
	},

	path: function() {
		return window.location.pathname.toString();
	},

	port: function() {
		return window.location.port.toString();
	},

	location: function() {
		return window.location.toString();
	},

	protocol: function() {
		return window.location.protocol.toString();
	},

	get: function(paramKey) {
		var parametersObj = this.parameters();
		return parametersObj[paramKey];
	},

	set: function(newParams) {
		var parameters = this.parameters() || {};
		for (name in newParams) {
			parameters[name] = newParams[name];
		}

		return parameters;
	},

	setFilter: function(newParams) {
		var parameters = this.parameters() || {};
		for (name in newParams) {
			parameters[name] = newParams[name];
		}

		parameters['pageNo'] = 1;

		return parameters;
	},

	parameters: function() {
		var queryString = window.location.search.toString().substring(1),
			queryParams = {};

		if (queryString.length > 0) {
			var queryPairs = queryString.split('&');

			for (var i = 0; i < queryPairs.length; i++) {
				var thisPair = queryPairs[i].split('=');
				queryParams[thisPair[0]] = thisPair[1] ? thisPair[1] : null;
			}
			return queryParams;

		} else {
			return null;
		}
	},

	make: function(urlString, queryParams) { // query string parameters as name/value object
		var devDirectory = (this.path().search(/^\/cfewaterways/) == 0) ? '/cfewaterways' : '/ewaterways',
			urlString = urlString || '',
			newURLString = 'http://';

		newURLString = this.protocol() + '//';

		newURLString += this.hostname();

		//newURLString += this.port() || '';

		if (this.hostname() != 'www.ewaterways.com' &&
		        this.hostname() != 'uat.ewaterways.com' &&
		        urlString.search(/^\/ewaterways/i) < 0) {
			newURLString += devDirectory;
		}

		newURLString += urlString;

		if (typeof queryParams === 'object') {
			newURLString += '?';

			for (name in queryParams) {
				newURLString += name + '=';
				newURLString += queryParams[name] !== null ? queryParams[name] : '';
				newURLString += '&';
			}

			newURLString = newURLString.slice(0, -1); // remove trailing ampersand
		}

		return newURLString;
	}
};

/*
	Home page concertina object
*/

function Concertina (targetDiv, contentDiv) {
	if ( !$(targetDiv) ) {
		return false;
	}
	
	var that = this,
		headingOffset = 34,
		imageOffset = [-180, -66, -70, -168, -105, -162];
	
	this.panels = [];
	this.contentPanel = new ContentPanel(contentDiv, this);

	jQuery(targetDiv).children('div').each(function() {
		that.panels.push(new ConcertinaPanel(this, that));
	});

	$('*', targetDiv).attr('tabIndex', -1);

	for (var i=0; i < this.panels.length; i++) {
		var positionOffset = (headingOffset * i)
		this.panels[i].position = {
			left:     positionOffset,
			right:    jQuery(targetDiv).width() - (headingOffset * (this.panels.length - i)),
			overview: parseInt($(targetDiv).width() / this.panels.length * i)	
		}

		this.panels[i].imageOffset = imageOffset[i];
		$(this.panels[i].panel).css('left', this.panels[i].position.overview + 'px');
		this[this.panels[i].panel.id] = this.panels[i];
	}

	this.overview = function() {
		for (var i=0; i < this.panels.length; i++) {
			this.panels[i].overview();
		}
		that.contentPanel.reset();
	}

	/*
		Concertina panel object 
	*/

	function ConcertinaPanel(targetDiv, parentConcertina) {
		var that = this;

		this.panel = targetDiv;
		this.parent = parentConcertina;

		$(this.panel).find('p.back').after('<h4>' + $(targetDiv).find('h3 span').text() + '</h4>');

		this.mainImage = $(this.panel).children('img').get(0);
		this.descriptionHTML = $(this.panel).children('div.description').html();
		this.descriptionHeight = $(this.panel).children('div.description').height() + 10;

		$(this.panel).css({
			cursor: 'pointer',
			width: "115px", 
			position: "absolute" 
		})

		$(this.panel).click(function() {
			if ( !$(this).hasClass('open') ) {
				$(this).prevAll().andSelf().each(function() {
					that.parent[this.id].open();
					$(this).removeClass('open');
				});
				$(this).nextAll().each(function() {
					that.parent[this.id].close();
					$(this).removeClass('open');
				});
				that.parent.contentPanel.show(that.descriptionHTML, that.descriptionHeight);
				$(this).addClass('open');
			}
		});
	}

	ConcertinaPanel.prototype.move = function(panelX, panelW, imagePosX) {
		var that = this,
			posX = panelX || this.position.left,
			panelW = panelW || this.mainImage.width,
			imagePosX = imagePosX || 0;

		$(this.panel).animate({
			left: panelX + 'px',
			width: panelW + 'px' 
		}, {
			duration: 700,
			easing: 'easeOutQuad'
		});

		$(this.mainImage).animate({
			left: imagePosX + 'px'
		}, {
			duration: 700
		})
	}

	ConcertinaPanel.prototype.open = function() {
		return this.move(this.position.left)
	}

	ConcertinaPanel.prototype.close = function() {
		return this.move(this.position.right)
	}

	ConcertinaPanel.prototype.overview = function() {
		return this.move(this.position.overview, 129, this.imageOffset)
	}
	
	/*
		Content display object
	*/
	
	function ContentPanel(targetDiv, parentConcertina) {
		var that = this;
		
		$(targetDiv).contents().wrapAll('<div class="description"></div>');
		
		this.div = $(targetDiv).children().get(0);
		this.origHeight = $(this.div).height();
		this.origContent = $(this.div).html();
		this.parent = parentConcertina;

		this.show = function(contentHTML, contentHeight) {
			function injectContent () {
				$(that.div).html(contentHTML).fadeIn();
				$(that.div).find('p.back a').click(function() { // back to overview
					that.parent.overview();
					return false;
				});
			}

			$(that.div).fadeOut()
				.parent().animate({
					height: contentHeight + 'px' 
				}, {
					easing: 'easeOutQuad',
					complete: injectContent
				});
		}

		this.reset = function() {
			that.show(that.origContent, that.origHeight);
		}

	}
}

/*
	Search panel functionality
*/
var searchPanels = {
	destinationsService: url.make('/services/AjaxJson.svc/GetDestinations'), // auto complete service
	vesselService: url.make('/services/AjaxJson.svc/GetVessels'),
	submitURI: '/results/?',
	defaultNoRows: '15',
	containers: [], // array of div elements
	tabs: [],       // menu tabs

	init: function() {
		this.containers = jQuery('#search_module_round_corn .container');
		this.tabs = jQuery('#search_module_round_corn h3');

		jQuery(this.tabs[1]).css('right', '0');
		
		if (window.location.toString().search(/\/vessel\//) >= 0) {
			this.containers.hide().eq(1).show(); // show vessel search panel if we are showing vessel search results
			jQuery(this.tabs[1]).addClass('current');
		} else {
			this.containers.hide().eq(0).show();
			jQuery(this.tabs[0]).addClass('current');
		};

		if (jQuery('#cruise_type_search option:selected').val() != 'all') {
			jQuery('#cruise_destination_search').removeClass('validate_notnull').siblings().children('abbr').hide();
		}

		autocompleteObj = jQuery('#cruise_destination_search').autocomplete(this.destinationsService, {
			autoFill: true,
			selectFirst: true
		});

		autocompleteObj = jQuery('#vessel_name_search').autocomplete(this.vesselService, {
			autoFill: true,
			selectFirst: true
		});

		jQuery(this.tabs).children('a').click(function() {
			var thisTab = jQuery(this);
			jQuery(searchPanels.containers).hide();
			jQuery(thisTab.attr('href')).show();
			jQuery(searchPanels.tabs).removeClass('current');
			jQuery(this).parent().addClass('current');
			return false;
		});

		//$('button#cruise_search').click(function() {
		function findCruise() {


			var validSearch = true,
				errorMessage = '',
				searchUri = [],
				searchParams = {};

			searchUri[0] = 'cruise';

			searchUri.push(jQuery('#cruise_type_search').val());
			searchUri.push(jQuery('#cruise_destination_search').val().toLowerCase());
			if ($('#cruise_month_search option:selected').val().length > 0) searchParams['departure_month'] = jQuery('#cruise_month_search option:selected').val();
			validSearch = validation.check('#cruise_search');
			errorMessage = 'cruise destination';

			if (validSearch) {
				window.location = url.make('/' + encodeURI(searchUri.join('/')), searchParams);
			}
			else {
				alert(['Please supply a ', errorMessage, ' to perform your search.'].join(''));
			}
			return false;
		};

		$('a#vessel_search').click(function() {
			var veselName = $('#vessel_name_search').val();
			if (veselName == 0) {
				$('a#vessel_search').change('button#cruise_search')
				findCruise();
				return false;
			}
			var validSearch = true,
				errorMessage = '',
				searchUri = [],
				searchParams = {};

			searchUri[0] = 'vessel';

			searchUri.push(jQuery('#vessel_name_search').val().toLowerCase());
			if (jQuery('#cruise_month_search option:selected').val().length > 0) searchParams['departure_month'] = jQuery('#cruise_month_search option:selected').val();
			validSearch = validation.check('#vessel_search');
			errorMessage = 'Vessel name';

			if (validSearch) {
				window.location = url.make('/' + encodeURI(searchUri.join('/')), searchParams);
				// window.location = url.make('/' + encodeURI(searchUri.join('/')));
			}
			else {
				alert(['Please supply a ', errorMessage, ' to perform your search.'].join(''));
			}
			return false;
		});

		/*jQuery('button', this.containers).click(function() {
		var validSearch = true,
		errorMessage = '',
		searchUri = [],
		searchParams = {};
				
		searchUri[0] = jQuery(this).parents().filter('.container').eq(0).attr('id').replace(/_search$/, ''); 
				
		if (searchUri[0] == 'vessel') {
		searchParams['departure_month'] = jQuery('#vessel_month_search  option:selected').val();
		validSearch = validation.check('#vessel_search');
		errorMessage = 'Vessel name';
		} else {
		searchUri.push(jQuery('#cruise_type_search').val());
		searchParams['departure_month'] = jQuery('#cruise_month_search option:selected').val();;
		validSearch = validation.check('#cruise_search');
		errorMessage = 'cruise Destination';
		}
				
		if (validSearch) {
		window.location = url.make('/' + encodeURI(searchUri.join('/')), searchParams);
		} else {
		alert(['Please supply a ', errorMessage, ' to perform your search.'].join(''));
		}

	 	 	 return false;
		});*/


		jQuery('input, select', this.containers).focus(function(e) {
			jQuery(this).bind('keypress', function(e) {
				if (e.which == 13) {
					$(this).unbind('keypress'); // unbind to prevent firing when user hits return to dismiss dialog box
					jQuery(e.currentTarget).parent().siblings('button').click();
					return false;
				}
			});
		});

		jQuery('#cruise_type_search').change(function() {
		
			if (jQuery(this).val().match(/0/i)) {
				jQuery('#cruise_destination_search').addClass('validate_notnull').siblings().children('abbr').show();
			} else {
				jQuery('#cruise_destination_search').removeClass('validate_notnull').siblings().children('abbr').hide();
			}

		});
	},

	serialize: function(container) { // jQuery function requires a form element
		if (!container) {
			return null;
		}
		var paramterString = "",
			noRows = "";

		jQuery(container).contents().find('input, select').each(function() {
			paramterString += jQuery(this).attr('name') + '=' + jQuery(this).val() + '&';
		});

		noRows = $('#results_per_page option:selected').val() || this.defaultNoRows;

		paramterString += 'noRows=' + noRows + '&pageNo=0&';

		return paramterString += jQuery(container).attr('id');
	}

}

function Carousel(targetDiv, imagesDisplayed, totalStops) {
	if ( !jQuery(targetDiv) ) { 
		return false;  
	}  

	var me = this;
	this.stops = new Array(totalStops); // collection of offsets in pixels to move the UL to
	this.currentStop = 0; // pointer for this.stops
	this.scrollDistancePx = jQuery(targetDiv).find('.viewport li').eq(0).width() + parseInt(jQuery(targetDiv).find('.viewport li').eq(0).css('marginRight'));
	
	jQuery(targetDiv).find('.navigate').before('<p class="indicator"></p>');
	
	for (var i=0; i < this.stops.length; i++) {
		this.stops[i] = 0 - (this.scrollDistancePx * i * imagesDisplayed);
		jQuery(targetDiv).find('.indicator').append('<span></span>');
	}
	
	// indicators show the current displayed thumbnails relative to the whole carousel
	this.indicators = jQuery(targetDiv).find('.indicator span');
	$(this.indicators[0]).addClass('current'); // setup first indicator as active

	this.scrollDistancePx = this.scrollDistancePx * imagesDisplayed;
	
	if (this.stops.length <= 1) {
		jQuery('.navigate', targetDiv).css('visibility', 'hidden');
	} else {
		jQuery(targetDiv).find('.navigate a').html(''); // hide text links

		jQuery(targetDiv).find('.navigate a').click(function(e) {
			var positionX;
			if (jQuery(this).parent().hasClass('next')) {
				me.currentStop = (me.currentStop >= me.stops.length - 1) ? 0 : me.currentStop + 1;
			} else { // previous button
				me.currentStop = (me.currentStop == 0) ? me.stops.length - 1 : me.currentStop - 1;
			}
			positionX = me.stops[me.currentStop];

			jQuery(targetDiv).find('.viewport ul').stop().animate({
				left: positionX + 'px'
			}, {
				duration: 800,
				easing: 'easeOutQuad'
			});
			jQuery(me.indicators).removeClass('current')
				.eq(me.currentStop).addClass('current');

			this.blur();	

			return false; // cancel click event
		});

	}


}

// form validation
var validation = {
	errorStack: [],
	check: function(formDiv) {
		var validData = true;
		var parentDiv = $(formDiv);

		validation.errorStack = [];
		validation.parentStack = [];

		$(formDiv).filter(':visible').find('select:not([disabled]), input:not([disabled])').each(function() {
			var fieldValue;

			if ($(this).is('select')) {
				fieldValue = $(this).find('option:selected').val();
				if (fieldValue == 'select') {
					fieldValue = '';
				}

			} else {
				fieldValue = $(this).val();
			}

			if ($(this).attr('type') == 'checkbox') {
				if ($(this).is(':checked')) {
					fieldValue = 'checked';
				}
				else {
					fieldValue = '';
				}
			}

			if ($(this).hasClass('validate_notnull')) {
				if ($(this).is('select')) {
					var selectValid = true; // For multiple selects which make up one field, like dates
					$(this).siblings('select.validate_notnull').andSelf().each(function() {
						if ($(this).val() == 'select') {
							selectValid = false;
						}
					});
					if (!selectValid) {
						if ($(this).parent().is('span')) {
							validation.highlight($(this).parent().parent());
						} else {
							validation.highlight($(this).parent());
						}
						validation.errorStack.push($(this).attr('name'));

						validData = false;
					} else {
						if ($(this).parent().is('span')) {
							validation.removeHighlight($(this).parent().parent());
						} else {
							validation.removeHighlight($(this).parent());
						}
					}
				}
				else { // For normal text inputs
					if (fieldValue == '' || fieldValue.length == 0) {
						if ($(this).parent().is('span')) {
							validation.highlight($(this).parent().parent());
						} else {
							if ($(this).attr('type') == 'checkbox') {
								validation.highlight($(this).next('span'));
							}
							else {
								validation.highlight($(this).parent());
							}
						}

						validation.errorStack.push($(this).attr('name'));

						validData = false;
					} else {
						if ($(this).parent().is('span')) {
							validation.removeHighlight($(this).parent().parent());
						} else {
							if ($(this).attr('type') == 'checkbox') {
								validation.removeHighlight($(this).next('span'));
							}
							else {
								validation.removeHighlight($(this).parent());
							}
						}
					}
				}
			}

			if ($(this).hasClass('validate_day')) {
				var dayField = this, monthField = $(this).siblings('.validate_month').get(0), yearField = $(this).siblings('.validate_year').get(0);
				var daysInMonth = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
				var day = $(dayField).val(), month = $(monthField).val(), year = $(yearField).val();
				var validDate = false;
				if (day != 'select' && month != 'select' && year != 'select') {
					var leapYear = (year % 4 == 0 ? (year % 100 == 0 ? (year % 400 == 0 ? true : false) : true) : false);
					if (leapYear) daysInMonth[1] = 29;
					if (day > daysInMonth[month - 1]) {
						validDate = false;
					}
					else {
						validDate = true;
					}
				}
				else {
					validDate = false;
				}

				if (!validDate) {
					if ($(this).parent().is('span')) {
						validation.highlight($(this).parent().parent());
					} else {
						validation.highlight($(this).parent());
					}
					validation.errorStack.push($(this).attr('name'));
					validData = false;
				} else {
					if ($(this).parent().is('span')) {
						validation.removeHighlight($(this).parent().parent());
					} else {
						validation.removeHighlight($(this).parent());
					}
				}

			}

			if ($(this).hasClass('validate_email')) {
				if ($(this).val().length == 0 && !$(this).hasClass('validate_notnull')) {
					if ($(this).hasClass('validate_email_confirm') && ($(this).parent().prev().find('input.validate_email')).val() != $(this).val()) {
						validation.highlight($(this).parent());
						validation.errorStack.push($(this).attr('name'));
						validData = false;
					}
					else {
						validation.removeHighlight($(this).parent());
					}
				}
				else {
					if (!fieldValue.match(/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i)) {
						validation.highlight($(this).parent());
						validation.errorStack.push($(this).attr('name'));
						validData = false;
					} else {
						if ($(this).hasClass('validate_email_confirm') && ($(this).parent().prev().find('input.validate_email')).val() != $(this).val()) {
							validation.highlight($(this).parent());
							validation.errorStack.push($(this).attr('name'));
							validData = false;
						}
						else {
							validation.removeHighlight($(this).parent());
						}
					}
				}
			}

			if ($(this).hasClass('validate_password')) {
				if (!fieldValue.match(/(.*)\d/g) || fieldValue.length < 7 || fieldValue.length > 15) {
					validation.highlight($(this).parent());
					validation.errorStack.push($(this).attr('name'));
					validData = false;
				} else {
					if ($(this).hasClass('validate_password_confirm') && ($(this).parent().prev().find('input.validate_password')).val() != $(this).val()) {
						validation.highlight($(this).parent());
						validation.errorStack.push($(this).attr('name'));
						validData = false;
					}
					else {
						validation.removeHighlight($(this).parent());
					}
				}
			}


			if ($(this).hasClass('validate_isnumber')) {
			  if (fieldValue.length > 0 && !fieldValue.match(/^\d+$/)) {
					validation.highlight($(this).parent());
					validation.errorStack.push($(this).attr('name'));
					validData = false;
				}
			}
		});
		return validData;
	},

	highlight: function(element) {
		$(element).addClass('validation_error');
	},

	removeHighlight: function(element) {
		$(element).removeClass('validation_error');
	},

	submit: function(formDiv) {
		var serializedData = '';

		$(formDiv).find('input, select, textarea').each(function() {
			serializedData += jQuery(this).attr('name') + '=' + jQuery(this).val() + '&';
		});
	},

	_notnull: function(value) {
		if (value == '' || value.length == 0) {
			return false;
		} else {
			return true;
		}

	},

	_email: function() {

	}
}

getCountryFromUrl = function() {
    var currentUrl = window.location.toString();
    var segments = currentUrl.split('?');
	segments = segments[0].split('/');
    var countryName;
    if (segments[segments.length -1].length > 0 &&
	        segments[segments.length -1].indexOf('.') == -1) {
        countryName = segments[segments.length -1];
    } else {
        countryName = segments[segments.length -2];
    }
    
    return countryName.split("-").join(" ");
}

var GoogleWeatherMap = function() {
    var month = "avg";
    var type = "temp";
    var gZoom = 0;
    
    var currentTime = new Date();
    var monthIndex = currentTime.getMonth()
    $("#MapMonthSelect option").each(function(i, val) {
        if (i==monthIndex) {
            $(val).attr('selected', 'selected');
        } else {
             $(val).removeAttr('selected');
        }
    });
    
    month = $("#MapMonthSelect option:selected").val();
    
    var bounds = new GLatLngBounds( new GLatLng(-90, -180)
                              , new GLatLng(90, 180)
                               );
    var copyright = new GCopyright( 'your-copyright'
                              , bounds
                              , 0
                              , "(c) 2008 Your Organization " +
                                "<http://www.example.org/>"
                               );
    copyrights = new GCopyrightCollection();
    copyrights.addCopyright(copyright);
    var heatmap = new GTileLayer(copyrights, 0, 20);
    heatmap.getTileUrl = function (tile, zoom) {
            gZoom = zoom;
            url = 'http://weather.ewaterways1.com/ImageOverlay.ashx?type=' + type +
                '&month=' + month +
                '&transparency=0.6' +
                '&zoom=' + zoom +
                '&tilex=' + tile.x +
                '&tiley=' + tile.y;
            return url;
        }
    heatmap.isPng = function () {return true;}
    heatmap.getOpacity = function () {return 1.0;}
    
    var overlay = null;
    map = new GMap2(document.getElementById("weather_canvas"));
    var country = getCountryFromUrl();
          
    jQuery.dotNetJSONGet("../../Services/AjaxJson.svc/GetLocationDetail",
        "location=" + country,
        function(data, textStatus) {
            if (data != null && data.d != null) {
                var point = new GLatLng(data.d.Latitude, data.d.Longitude);
                map.setCenter(point, data.d.Zoom);
                overlay = new GTileLayerOverlay(heatmap)
                map.addOverlay(overlay);
                map.addControl(new GLargeMapControl());
                map.addControl(new GMapTypeControl());
            }
        },
        function(XMLHttpRequest, textStatus, errorThrown) {
            alert(textStatus);
        });
        
        
    $('#GetCentreButton').click(function() {
        var cp = map.getCenter();
        alert(cp.lat() + "| " + cp.lng() + "| " + gZoom);
    });
    
    $('#MapTypeSelect').change(function() {
        type = $("#MapTypeSelect option:selected").val();
        if (type == 'temp') {
            $("#RainMapKey").css("display", "none");
            $("#TemperatureMapKey").css("display", "block");
        } else {
            $("#TemperatureMapKey").css("display", "none");
            $("#RainMapKey").css("display", "block");
        }
        map.removeOverlay(overlay)
        map.addOverlay(overlay);
    });
    
    $('#MapMonthSelect').change(function() {
        month = $("#MapMonthSelect option:selected").val();
        map.removeOverlay(overlay)
        map.addOverlay(overlay);
    });
}

function makeExternalLinksPopup() {
	jQuery('a[rel=external]').click(function() {
		window.open(this.href, "_blank");
		return false;
	});
}

function isIframe() {
	return (window.parent !== window);
}

function continent(latitude, longitude, zoomLevel, filename) {
	this.latitude = latitude;
	this.longitude = longitude;
	this.zoomLevel = zoomLevel;
	this.filename = filename;
}

var kmlUrl = window.location.protocol + '//';
var host = window.location.hostname;
host == 'localhost' ? kmlUrl += 'altsys.co.uk' : kmlUrl += host;
if (host != 'www.ewaterways.com') kmlUrl += '/ewaterways';
kmlUrl += '/mapsearch/kmls';
var continents = new Array();
continents['africa'] = new continent(1.5, 17.5, 3, kmlUrl + '/africa.kml');
continents['northamerica'] = new continent(40, -100, 3, kmlUrl + '/northamerica.kml');
continents['southamerica'] = new continent(-20, -60, 3, kmlUrl + '/southamerica.kml');
continents['america'] = new continent(12, -80, 2, null);
continents['asia'] = new continent(30, 100, 3, kmlUrl + '/asia.kml');
continents['europe'] = new continent(50, 12, 4, kmlUrl + '/europe.kml');
continents['middleeast'] = new continent(28, 55, 4, kmlUrl + '/middleeast.kml');
continents['southpacific'] = new continent(-20, 135, 3, kmlUrl + '/southpacific.kml');
continents['antarctica'] = new continent(-70, 5, 2, kmlUrl + '/antarctica.kml');

// Timeout variable for markers on location Google map.
var t = [];
// location page tab's switch; its important to call tabs correct: (#arctic) and for images give name: (location_arctic.jpg)
$(function() {
	$('#tabs_switch > ul').tabs();
	$('#tabs_switch_guide > ul').tabs();

	if ($('#weather .pt').html() == null || $('#weather .pt').html().replace(/^\s\s*/, '').replace(/\s\s*$/, '') == "") $('#tabs_switch_guide > ul').tabs("remove", 1)
	if ($('#whereTogo .pt').html() == null || $('#whereTogo .pt').html().replace(/^\s\s*/, '').replace(/\s\s*$/, '') == "") $('#tabs_switch_guide > ul').tabs("remove", 1)
	if ($('#needToKnow .pt').html() == null || $('#needToKnow .pt').html().replace(/^\s\s*/, '').replace(/\s\s*$/, '') == "") $('#tabs_switch_guide > ul').tabs("remove", 1);
	if ($('#overview .pt').html() == null || $('#overview .pt').html().replace(/^\s\s*/, '').replace(/\s\s*$/, '') == "") $('#tabs_switch_guide > ul').tabs("remove", 0);

	$('#tabs_switch ul li a').click(function(event) {
		if ($('#contintent_img').is(':visible')) {
			var current_img_src = $('#contintent_img img').attr('src'); //link to image
			var img_id = $('#contintent_img img'); //getting img which source code we will change
			if ((img_id.length) > 0) { //this true only if there is img in page to change
				var link_value = $(this).attr('href'); //name of image such: as #america
				var next_img = (link_value.replace(/#/, ''));
				var img_link = (current_img_src.replace(/_+[a-zA-Z0-9-]+\./, '_' + next_img + '.'));
				$(img_id).attr('src', img_link);
			}
		}
		else {
			var continentName = $(this).attr('className');
			var thisContinent = continents[continentName.replace('-', '')];
			for (j = 0; j < t.length; j++) {
				clearTimeout(t[j]);
			}
			t = [];
			map.clearOverlays();
			map.setCenter(new GLatLng(thisContinent.latitude, thisContinent.longitude), thisContinent.zoomLevel);
			var geocoder = new GClientGeocoder();
			var i = 0;
			$('div#' + continentName + ' ul li a').each(function() {
				var link = this;
				var country = $(link).text();
				t.push(setTimeout(function() {
					geocoder.getLocations(country, function(response) {
						if (!response || response.Status.code != 200) {
							// alert(country + ' not found');
						}
						else {
							place = response.Placemark[0];
							point = new GLatLng(place.Point.coordinates[1],
                        place.Point.coordinates[0]);
							var marker = new GMarker(point, { icon: ewIcon, title: country });
							GEvent.addListener(marker, 'click', function() {
								window.location = $(link).attr('href');
							});
							map.addOverlay(marker);
							arrMarkers[country] = marker;
						}
					});
				}, 500 * i));

				i++;
				// $(this).click(function() { map.panTo(arrMarkers[country].getLatLng()); return false; });
			});
		}
	});
	//for temperature and percipitation tabs ======
	$('#tabs_switch_guide li a').click(function() {
		$('#location_tabs').children().addClass('inactive');
		tab_id = $(this).attr('id');
		switch (tab_id) {
			case 'overview_click':
				$('.advert_img').removeClass('inactive');
				break;
			case 'weather_click':
				$('.weather_map').removeClass('inactive');
				if (typeof (gWeatherMap) == 'undefined') {
					gWeatherMap = new GoogleWeatherMap();
				}

				break;
			default:
				return false;
		}
	});
	/* $('#map_t_p').change(function() {
	show_map = $(this).val();
	switch (show_map) {
	case 'Temperature':
	$('#temp_map').removeClass('inactive');
	$('#precip_map').addClass('inactive');
	break;
	case 'Precipitation':
	$('#precip_map').removeClass('inactive');
	$('#temp_map').addClass('inactive');
	break;
	default:
	return false;
	}

	});
	*/
	//making PanelTypes same height on 'Sign in' page
	$(function() {
		var pt_left = $('#bookingflow_registration .pt').eq(0).height();
		var pt_right = $('#bookingflow_registration .pt').eq(1).height();
		var pt_middle = $('#bookingflow_registration .pt').eq(2).height();
		var pt_size = (Math.max(pt_left, pt_middle, pt_right)) + 10;
		$('#bookingflow_registration .pt').height(pt_size);
		$('#bookingflow_registration .pt').css({ position: 'relative' });
		$('#bookingflow_registration .pt p.buttons_holder').css({ position: 'absolute', right: 0, bottom: 0 });
	});
	//product nav menu small hack for ie6 showing hover
	$(function() {
		$('#product_nav ul#addons_menu li').hover(
      function() {
      	$(this).addClass('zipHover');
      },
      function() {
      	$(this).removeClass('zipHover');
      }
    );
	});
});
// Cabins page
function populateCabinRow(row, title, price) {
	$(row).find('p.price').text(price);
	$(row).find('p.cabin_title').text(title);
}

jQuery.fn.extend({
  headlines: function() { // BBC style headline panel
    $(this).each(function() {
      var container = $(this);
      if (container.width() < 300) {
        // $('p', container).addClass('smallHeadline');
      }
      if ($.browser.msie && $.browser.version <= '6.0') {
        $('ul.headlines', container).width(container.width() - 132);
      }
      else {
        $('ul.headlines', container).width(container.width() - 130);
      }
      var image = $('<img />').addClass('headlineImage');
      $('.headlines', container).before(image);
      $(container).append($('<div></div>').css({ clear: 'both', height: '0px' }));
      selectHeadline($('.headlines li', container).get(0));


      $('.headlines li', container).mouseover(function() {
        selectHeadline(this);
      });

      function selectHeadline(listItem) {
        $('.headlines li', container).removeClass('current');
        $(image).attr('src', $('img', listItem).attr('src'));
        $(listItem).addClass('current');
      }
    });
  },
  imageGallery: function() { // Create image galleries
    $(this).each(function() {
      var gallery = this; // Keep a reference to the gallery div
      $(gallery).width($(gallery).parent().width() - 6);
      $(gallery).nextAll('.galleryPrev, .galleryNext, .galleryPosition, .galleryText').remove();
      if ($('li img', gallery).length > 0) { // Check there is at least one image
        var imgWidth = $('li img', gallery).eq(0).width() + 4; // Get the width of the first image, add 4 to include the padding
        var lastWidth = $('li img:last', gallery).width() + 4; // Get the width of the last image, add 4 to include the padding
        var offset = ($(gallery).width() - imgWidth) / 2; // Get the offset value needed to centre the images

        // Loop through all the images getting to find the total width of the list
        var log = '';
        var totalWidth = 0;
        $('li img', gallery).each(function(i) {
          totalWidth += $(this).width() + 4;
          log += 'image' + i + ': ' + $(this).width() + '\n';
        });
        $('ul', gallery).width(totalWidth + lastWidth / 2); // Set the
        // alert($('ul', gallery).width());
        // alert(log);
        if (offset > 0) $('ul', gallery).css('paddingLeft', offset); // Set the padding to centre the first image

        var galleryText = $('<div></div>').addClass('galleryText'); // Create the text div
        $(gallery).after(galleryText); // and add it under the gallery

        // Position Marker list
        var positionMarkers = $('<ul></ul>').addClass('galleryPosition'); // Create list of markers to show currently selected image
        $('ul li', gallery).each(function() { // Add a position marker for each img
          $(positionMarkers).append($('<li></li>'));
        });
        var listwidth = 180, numImgs = $('li', positionMarkers).length; // get the number of images in the gallery
        var liWidth = (listwidth / numImgs) - 2; // work out the width of each position marker
        if (liWidth <= 0) liWidth = 1; // Make sure the position markers are at least 1px wide
        $('li', positionMarkers).width(liWidth); // Set the position markers width



        $(gallery).after(positionMarkers); // Place the position marker list under the images

        var controls = $('<div></div>').addClass('galleryControls');

        $(gallery).after(controls);

        var next = $('<div><span>Next</span></div>').addClass('galleryNext'), prev = $('<div><span>Previous</span></div>').addClass('galleryPrev'); // Create the next and prev buttons
        $(gallery).after(prev).after(next); // Add the next and prev buttons under the images
        $(controls).append(prev).append(positionMarkers).append(next).append($('<div></div>').addClass('shim'));

        var currentImg = $('ul li:first', gallery).get(0); //Set the current image to be the first one
        $('li', positionMarkers).eq($('ul li', gallery).index(currentImg)).addClass('current');
        $(gallery).scrollTo(currentImg, 100, { axis: 'x', offset: -1 * offset });
        $(galleryText).html($('div', currentImg).html());

        // Next button
        $(next).click(function() {
          if ($(currentImg).next('li').get(0)) { // Check if there is a next image
            currentImg = $(currentImg).next('li').get(0); // Change currentImg to point to the next image
            scrollImage(currentImg); // Scroll to the current image
          }
        });

        // Previous button
        $(prev).click(function() {
          if ($(currentImg).prev('li').get(0)) {
            currentImg = $(currentImg).prev('li').get(0);
            scrollImage(currentImg);
          }
        });


        $('li', positionMarkers).click(function() {
          var index = $('li', positionMarkers).index(this);
          // $(gallery).scrollTo($('li', gallery).eq(index), 400);
          currentImg = $('li', gallery).eq(index).get(0);
          scrollImage(currentImg);
        });
      }
      function scrollImage(element) {
        $('li', positionMarkers).removeClass('current');
        var offset = ($(gallery).width() - ($('img', element).width() + 4)) / 2;
        $('li', positionMarkers).eq($('ul li', gallery).index(element)).addClass('current');
        $(gallery).stop().scrollTo(element, 500, { axis: 'x', offset: -1 * offset });
        $(galleryText).empty().html($('div', element).html());
      }
      $('.galleryControls').nextAll().css({ 'display': 'none' });
    });


  }

});

//JQuery .Net JSON call
if (typeof(jQuery) !== "undefined" && jQuery && typeof(JSON) !== "undefined" && JSON) {
    jQuery.dotNetJSONGet = function(theUrl, theData, successCallback, errorCallback) {     
        jQuery.ajax({
           type: "GET",
           dataType: "json",
           contentType: "application/json; charset=utf-8",
           url: theUrl,
           data: theData,
           error: errorCallback,
           success: successCallback
         });
    };
}

anchor = {
init: function(elements) {
    $(elements).click(function() {
      elementClick = $(this).attr("href")
      $.scrollTo(elementClick, 1500);
      return false;
    })
  }
}

