﻿var D = {};

(function ($) {
    $(document).ready(function () {
        // Top Menu
        $('.navtop').children('li').click(function () {
            $(this).children('.dropdown').show();
        }).mouseleave(function () {
            $('.dropdown').hide();
        });
        // Lightbox
        $('.lightbox').lightBox();
        // Itinerary tabs
        $('ul.itinerary-tabs').tabs('div.itinerary-pages > div');
        $('ul.itinerary-tabs-1').tabs('div.itinerary-pages-1 > div');
        $('ul.itinerary-tabs-2').tabs('div.itinerary-pages-2 > div');
        $('ul.itinerary-tabs-3').tabs('div.itinerary-pages-3 > div');
        $('ul.itinerary-tabs-4').tabs('div.itinerary-pages-4 > div');
        $('ul.itinerary-tabs-5').tabs('div.itinerary-pages-5 > div');
        $('ul.itinerary-tabs-6').tabs('div.itinerary-pages-6 > div');
        // reveal-link
        $('.reveal-link').click(function(event) { $('.reveal-me').slideDown('fast'); $('.reveal-link').hide(); event.preventDefault(); event.stopPropagation(); return false; });
        // overlays
        $('.overlay-trigger').overlay({ mask: {
		    color: '#ebecff',
		    loadSpeed: 200,
		    opacity: 0.5
	    }, closeOnClick: true});   
   
    });
})(jQuery);

(function ($) {

	// Ajax Wrapper

	var ajaxCounter = 0;
	var ajaxRetries = 0;

	// Modified version of JSON2 (http://www.json.org/json2.js) by Crockford.  Modification just 
	// fixes up dates passed back from the server as strings (either in ISO or MSAJAX format)
	var Json = function() {

		function f(n) {
			// Format integers to have at least two digits.
			return n < 10 ? '0' + n : n;
		}

		Date.prototype.toJSON = function(key) {
			return this.getUTCFullYear() + '-' +
				 f(this.getUTCMonth() + 1) + '-' +
				 f(this.getUTCDate()) + 'T' +
				 f(this.getUTCHours()) + ':' +
				 f(this.getUTCMinutes()) + ':' +
				 f(this.getUTCSeconds()) + 'Z';
		};

		Number.prototype.toJSON =
		Boolean.prototype.toJSON = function(key) {
			return this.valueOf();
		};

		String.prototype.toJSON = function(key) {
			return this.valueOf();
		};

		var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
		escapeable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
		gap,
		indent,
		meta = {    // table of character substitutions
			'\b': '\\b',
			'\t': '\\t',
			'\n': '\\n',
			'\f': '\\f',
			'\r': '\\r',
			'"': '\\"',
			'\\': '\\\\'
		},
		rep;

		function quote(string) {

			escapeable.lastIndex = 0;
			return escapeable.test(string) ?
		'"' + string.replace(escapeable, function(a) {
			var c = meta[a];
			if (typeof c === 'string') {
				return c;
			}
			return '\\u' + ('0000' +
					(+(a.charCodeAt(0))).toString(16)).slice(-4);
		}) + '"' :
		'"' + string + '"';
		}

		function str(key, holder) {
			var i,          // The loop counter.
			k,          // The member key.
			v,          // The member value.
			length,
			mind = gap,
			partial,
			value = holder[key];

			if (value && typeof value === 'object' &&
			typeof value.toJSON === 'function') {
				value = value.toJSON(key);
			}

			if (typeof rep === 'function') {
				value = rep.call(holder, key, value);
			}

			switch (typeof value) {
				case 'string':
					return quote(value);

				case 'number':
					return isFinite(value) ? String(value) : 'null';

				case 'boolean':
				case 'null':
					return String(value);

				case 'object':
					if (!value) {
						return 'null';
					}

					gap += indent;
					partial = [];

					if (typeof value.length === 'number' &&
						!(value.propertyIsEnumerable('length'))) {

						length = value.length;
						for (i = 0; i < length; i += 1) {
							partial[i] = str(i, value) || 'null';
						}

						v = partial.length === 0 ? '[]' :
							gap ? '[\n' + gap +
							partial.join(',\n' + gap) + '\n' +
							mind + ']' :
							'[' + partial.join(',') + ']';
						gap = mind;
						return v;
					}

					if (rep && typeof rep === 'object') {
						length = rep.length;
						for (i = 0; i < length; i += 1) {
							k = rep[i];
							if (typeof k === 'string') {
								v = str(k, value);
								if (v) {
									partial.push(quote(k) + (gap ? ': ' : ':') + v);
								}
							}
						}
					} else {
						for (k in value) {
							if (Object.hasOwnProperty.call(value, k)) {
								v = str(k, value);
								if (v) {
									partial.push(quote(k) + (gap ? ': ' : ':') + v);
								}
							}
						}
					}
					v = partial.length === 0 ? '{}' :
						gap ? '{\n' + gap + partial.join(',\n' + gap) + '\n' +
						mind + '}' : '{' + partial.join(',') + '}';
					gap = mind;
					return v;
			}
		}

		return {
			stringify: function(value, replacer, space) {
				var i;
				gap = '';
				indent = '';

				if (typeof space === 'number') {
					for (i = 0; i < space; i += 1) {
						indent += ' ';
					}
				} else if (typeof space === 'string') {
					indent = space;
				}

				rep = replacer;
				if (replacer && typeof replacer !== 'function' &&
				(typeof replacer !== 'object' ||
				 typeof replacer.length !== 'number')) {
					throw new Error('JSON.stringify');
				}
				return str('', { '': value });
			},

			parse: function(text, reviver) {
				var j;

				function walk(holder, key) {
					var k, v, value = holder[key];
					if (value && typeof value === 'object') {
						for (k in value) {
							if (Object.hasOwnProperty.call(value, k)) {
								v = walk(value, k);
								if (v !== undefined) {
									value[k] = v;
								} else {
									delete value[k];
								}
							}
						}
					}
					return reviver.call(holder, key, value);
				}

				cx.lastIndex = 0;
				if (cx.test(text)) {
					text = text.replace(cx, function(a) {
						return '\\u' + ('0000' +
						(+(a.charCodeAt(0))).toString(16)).slice(-4);
					});
				}

				if (/^[\],:{}\s]*$/.
					test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@').
					replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']').
					replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) {

					j = eval('(' + text + ')');

					return typeof reviver === 'function' ? walk({ '': j }, '') : j;
				}
				throw new SyntaxError('JSON.parse');
			},

			parseWithReviver: function(text) {
				return Json.parse(text, function(key, value) {
					if (value && typeof value === "string") {
						// Revive MSAJAX dates
						var a = /^\/Date\((d|-|.*)\)[\/|\\]$/.exec(value);
						if(a){
                        	var b = a[1].split(/[-+,.]/);
                        	return new Date(b[0] ? +b[0] : 0 - +b[1]);
						}
						// Revive ISO dates
						a = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/.exec(value);
						if(a)
                        	return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4], +a[5], +a[6]));
					}
					return value;
				});
			}
		};
	} ();

	// Extensions to jQuery's wonderful $.ajax method
	// Store the original version of the method
	$._ajax = $.ajax;

	$.extend($, {

		toJson: function(value) {
			return Json.stringify(value);
		},

		fromJson: function(value) {
			return Json.parseWithReviver(value);
		},

		ajax: function (s) {
			s.ajaxCounter = ajaxCounter++;
			if(!s._retry) {
				s._error = s.error;
				s._success = s.success;
				s.type = s.type || 'POST';
				s.contentType = s.contentType || "application/json; charset=utf-8";
				s.beforeSend = function (xhr) { xhr.setRequestHeader("Content-type", s.contentType); };
				s.dataType = s.dataType || "text"; // Not Json - we will parse
				s.data = s.contentType == "application/json; charset=utf-8" ? $.toJson(s.data || {}) : s.data;
				s.success = function (result) {
					if(!s._success) return;
					if(s.contentType == "application/json; charset=utf-8" && s.dataType == "text")
						result = $.fromJson(result); // Using our Json convertor fixes the issue with server side dates
					s._success(result.d);
				};
				s.error = function (xhr, errorType, e) {
					// If this request has retries left the retry it
					if(s.retries > 0 && s.retries <= 3) {
						ajaxRetries++;
						s._retry = true;
						s.retries--;
						$.ajax(s);
						return;
					}
					// Analyse the xhr to see if we can extract a useful error message, otherwise set a default error message
					var err = { Message: "Communication link with the server has been lost.  Please try again or refresh the page." };
					if (xhr.responseText && xhr.responseText.length > 0 && xhr.responseText.charAt(0) == '{') {
						err = $.fromJson(xhr.responseText);
					}
					if(err.Message) err.message = err.Message;
					// TODO: Should we catch certain types of errors here (e.h. Http Error codes)?
					// If we were given an error handling method then call it,  otherwise raise the error ourselves
					if(s._error) {
						s._error(err);
					} else {
					    alert(err.Message);
					}
				};
			}
			$._ajax(s);
		},

        webMethod: function(service, method, data, success) {
            $.ajax({
                url: "/WebServices/" + service + ".asmx/" + method,
                data: data,
                success: success
            });
        },

        pageMethod: function(method, data, success) {
            var url = window.location.pathname;
            $.ajax({
                url:  url + "/" + method,
                data: data,
                success: success
            });
        }
	});

    var stopAutoRotate = false;

    function manualRotate(event) {
        var x = event.pageX - $('div.banner-rotator').offset().left;
        var y = event.pageY - $('div.banner-rotator').offset().top;
        if(y < 85 || y > 105) return;
        if(x < 690 || x > 940) return;
        var n = parseInt((x - 690)/25);
        if(n < 0) n = 0;
        if(n > 9) n = 9;
        var next = $($('div.banner-rotator ul li')[n])
        if(next.hasClass('show')) return;
        rotateTo(next);
        stopAutoRotate = true;
        return false;
    }
 
    function rotateTo(next) {
	    var current = ($('div.banner-rotator ul li.show')?  $('div.banner-rotator ul li.show') : $('div.banner-rotator ul li:first'));        
        if ( current.length == 0 ) current = $('div.banner-rotator ul li:first');
	    next.css({opacity: 0.0})
	    .addClass('show')
	    .animate({opacity: 1.0}, 1000);
	    current.animate({opacity: 0.0}, 1000)
	    .removeClass('show');
    }

    function autoRotate() {	
        if(stopAutoRotate) return;
	    var current = ($('div.banner-rotator ul li.show')?  $('div.banner-rotator ul li.show') : $('div.banner-rotator ul li:first'));
        if ( current.length == 0 ) current = $('div.banner-rotator ul li:first');

	    var next = ((current.next().length) ? ((current.next().hasClass('show')) ? $('div.banner-rotator ul li:first') :current.next()) : $('div.banner-rotator ul li:first'));
	    //Un-comment the 3 lines below to get the images in random order
	    //var sibs = current.siblings();
        //var rndNum = Math.floor(Math.random() * sibs.length );
        //var next = $( sibs[ rndNum ] );
        rotateTo(next);
    };

    // Rotator
    function startAutoRotate() {
	    $('div.banner-rotator ul li').css({opacity: 0.0});
	    $('div.banner-rotator ul li:first').css({opacity: 1.0});
	    setInterval(autoRotate , 7500);
    }

    $(document).ready(function() {		

        // Load the images for the banner
        $("div.banner-rotator img").each(function(i, e) {
            $(e).attr('src', "/assets/content/images/banners/home_page/banner_" + (i+1) + ".jpg");
        });

        $("img[data-src]").each(function(i, e) {
            $(e).attr('src', $(e).attr('data-src'));
        });

	    //Load the slideshow
	    startAutoRotate();
	    $('div.banner-rotator').fadeIn(3000);
        $('div.banner-rotator ul li').fadeIn(3000); // tweek for IE
        $('div.banner-rotator').click(manualRotate);
    });

})(jQuery);

