﻿;String.prototype.removeNonNumeric = function() { return this.replace(/\D/gi, ''); };
String.prototype.trim = function() { return this.toString().replace(/^\s*|\s*$/g, ""); };
String.removeNonNumeric = function(value) { return value.replace(/\D/gi, ''); };
String.trim = function(value) { return value.trim(); };
String.trimToSize = function(value, maxLength) { return (value.length > maxLength ? value.substr(0, maxLength) + '...' : value); };
String.truncate = String.trimToSize;
String.empty = '';
String.convertToLatin = function(value) { return toLatin(value); };

if(navigator.platform == 'iPad')
{
	// disable effects for iPad
	$.fx.off = true;
}

function timeSpan()
{
	this._date = null;
	this._ticks = null;
	this.days = null;
	this.hours = null;
	this.minutes = null;
	this.seconds = null;
	this.milliseconds = null;
};

timeSpan.prototype.toFlightTime = function(split)
{
	var pattern = '{0}h {1}m';
	var addzero = false;

	if(split == undefined || typeof (split) == undefined)
	{
		pattern = '{0}:{1}';
		addzero = true;
	}

	var sb = new Sys.StringBuilder();
	var hours = this.hours;
	var minutes = this.minutes;

	if(this.days != null && this.days > 0)
		hours += (this.days * 24);

	if(this.seconds > 0)
		minutes += 1;

	return String.format(pattern, ((hours.toString().length == 1 && addzero) ? '0' : '') + hours.toString(), ((minutes.toString().length == 1 && addzero) ? '0' : '') + minutes.toString())
}

timeSpan.fromTicks = function(ticks)
{
	var dtm = new Date(ticks);

	var d = Math.floor(ticks / 3600000 / 24); // KK-MOD
	var h = '0' + (Math.floor(ticks / 3600000) - (d * 24)); // KK-MOD
	var m = '0' + dtm.getMinutes();
	var s = '0' + dtm.getSeconds();
	var cs = '0' + Math.round(dtm.getMilliseconds() / 10);

	function _format(value)
	{
		return parseInt(value.length > 1 ? value.replace(/^0/gi, '') : value);
	}

	var tm = new timeSpan();
	tm._date = dtm;
	tm._ticks = ticks;
	tm.days = d;
	tm.hours = _format(h.substr(h.length - 2));
	tm.minutes = _format(m.substr(m.length - 2));
	tm.seconds = _format(s.substr(s.length - 2));
	tm.milliseconds = _format(cs.substr(cs.length - 2));

	return tm;
}

function Uri(url, secure)
{
	this.url = url;
	this.secure = (secure == null ? false : secure);
}

Uri.prototype.toString = function()
{
	var out = this.url;
	if(this.secure)
		out = String.format('{0}//{1}{2}', location.protocol, location.hostname, this.url);
	else if(!this.secure && location.protocol == 'http:')
		out = String.format('http://{0}{1}', location.hostname, this.url);

	return out;
}

var _p = {};
_p.x=function(url, secure){return new Uri(url, secure);}

timeSpan.fromSeconds = function(seconds) { return timeSpan.fromTicks(seconds * 1000); }
timeSpan.fromMinutes = function(seconds) { return timeSpan.fromTicks((seconds * 1000) * 60); }
timeSpan.fromHours = function(seconds) { return timeSpan.fromTicks(((seconds * 1000) * 60) * 60); }

Array.skip = function(value, count) { return value.slice(count); };
Array.take = function(value, count) { return value.slice(0, count); };
Array.where = function(value, predicate)
{
	var matches = [];
	if(value != null)
	{
		for(var i = 0;i < value.length;i++)
		{
			if(predicate(value[i], i))
				matches.push(value[i]);
		}
	}
	return matches;
};

Array.findIndex = function(value, predicate) { var position = -1;for(var i = 0;i < value.length;i++) { if(predicate(value[i], i)) { position = i;break; } } return position; };
Array.find = function(value, predicate) { var position = value.findIndex(predicate);return (position > -1 ? value[position] : null); };
Array.takeWhile = function(value, predicate)
{
	var matches = [];
	for(var i = 0;i < value.length;i++)
	{
		if(predicate(value[i], i))
			matches.push(value[i]);
		else
			break;
	}

	return matches;
}

Array.skipWhile = function(value, predicate)
{
	var matches = [];
	for(var i = 0;i < value.length;i++)
	{
		if(!predicate(value[i], i))
		{
			matches = value.slice(i);
			break;
		}
	}

	return matches;
}

Array.orderBy = function(value, keySelector)
{
	var _bubbleSort = function(input, method)
	{
		var x, y, holder;
		var compare = method || function _sort(a, b)
		{
			return (a > b ? 1 : (a < b ? -1 : 0));
		};

		// The Bubble Sort method.
		for(x = 0;x < input.length;x++)
		{
			for(y = 0;y < (input.length - 1);y++)
			{
				if(compare(input[y], input[y + 1]) == 1)
				{
					holder = input[y + 1];
					input[y + 1] = input[y];
					input[y] = holder;
				}
			}
		}

		return input;
	}

	if(keySelector == null)
	{
		value = _bubbleSort(value);
	}
	else if(typeof (keySelector) == 'function')
	{
		value = _bubbleSort(value, keySelector);
	}
	else
	{
		value = _bubbleSort(value, function(a, b)
		{
			return (a[keySelector] > b[keySelector] ? 1 : (a[keySelector] == b[keySelector] ? 0 : -1));
		});
	}

	return value;
}

Array.select = function(value, selector)
{
	var out = [];
	for(var i = 0;i < value.length;i++)
		out.push(selector(value[i], i));

	return out;
}

// Array.orderBy = function(
Array.forEachAsync = function(data, callback, settings, onComplete)
{
	var on = 0;
	var itemCount = data.length;

	var iter = function()
	{
		var done = 0;
		while(done++ < settings.per && on < itemCount)
		{
			callback(on, data[on]);
			on++;
		}

		if(on != itemCount)
			setTimeout(iter, settings.pause);
		else
			if(typeof (onComplete) == 'function')
				onComplete();
	}

	iter();
}

// install array extensions
Array.asEnumerable = function(value) { return new jsinq.Enumerable(value); };
Array.asQueryable = function(value) { return new jsinq.Enumerable(value); };

// install this helper
//Object.isEnumerable = function(value){return value instanceof(jsinq.Enumerable)};

var _json = {};
_json.serialize = Sys.Serialization.JavaScriptSerializer.serialize;
_json.deserialize = Sys.Serialization.JavaScriptSerializer.deserialize;
_json.parseDate = function(value)
{
	var expr = /^\/Date\((\d+)((\+\d+)?)\)\/$/;
	var out = value.replace(expr, "$1");
	return (out != null && out.toString().length > 0 ? new Date(Number(out)) : null);
}

// Jquery extensions
$.fn.extend({ 
    'alt' : function(bool, fn_true, fn_false){ (bool) ? fn_true() : fn_false(); return this; } 
    ,'if' : function(bool){ return (bool) ? this : jQuery(''); } 
});

// alert
var _alert, alert_message;

/* Alert Box */
var AlertBoxType = { Information: 1, Warning: 2 };

var AlertBox =
{
	defaults:
	{
		closeButton: true
		, type: AlertBoxType.Information
		, onClose: function() { }
	}

	, create: function(text, options)
	{
		var sb = new Sys.StringBuilder();

		var opts = $.extend(AlertBox.defaults, options);

		sb.append('<div class="ui-widget">');
		//if(opts.closeButton)
		//sb.append('<a title="close" href="javascript:" class="close-note" onclick="remove_alert_box(this);"></a>');
		sb.append(String.format('<div class="ui-state-{0} ui-corner-all ui-custom-alertbox">', (opts.type == AlertBoxType.Information ? 'highlight' : 'error')));
		sb.append('<p><span class="ui-icon ui-icon-info ui-custom-alertbox-span"></span>');
		sb.append(text);
		sb.append('</p></div></div>');

		var box = $(sb.toString());
		if(typeof (opts.onClose) == 'function')
			box.data('onClose', opts.onClose);

		return box;
	}

	, warning: function(text, closeButton)
	{
		var opts = AlertBox.defaults;
		if(closeButton != null)
			opts.closeButton = closeButton;
		opts.type = AlertBoxType.Warning;

		return AlertBox.create(text, closeButton);
	}

	, information: function(text, closeButton)
	{
		var opts = AlertBox.defaults;
		if(closeButton != null)
			opts.closeButton = closeButton;

		opts.type = AlertBoxType.Information;
		return AlertBox.create(text, closeButton);
	}
}

/* Server Date */
Date.now = function() { return new Date(__viva.date) };
Date.now.addDays = function(days) { return new Date(Date.now().setDate(Date.now().getDate() + days)) };

/* Gooogle tracking & more */
var Google = {};
Google.goal = function(virtualPage) { _gaq.push(['_trackPageview', '/' + virtualPage]); }
Google.trackEvent = function(category, action, label, value)
{
	if(value == null)
		_gaq.push(['_trackEvent', category, action, label]);
	else
		_gaq.push(['_trackEvent', category, action, label, 0]);
};
Google.ecommerceTracking = function(args)
{
	// track ecommerce data
	EcommerceTracking(args);
}

var WhosOn = {}
WhosOn.trackPage = function(url, query, referrer)
{
	var full = null;
	if(url != null && url.length > 0)
		full = escape(String.format('{0}{1}{2}', url, (query != null && query.length > 0 ? '?' : ''), (query != null ? query : '')));

	_trackWOPageView(full, referrer);
};

// create load script method
$.loadScript = function(path, callback)
{
	var __scriptCallbacks = (window['_callbacks'] || (window['_callbacks'] = {}));
	var random = Math.random().toString().substring(2);

	// set a reference to callback
	var key = 'cb_' + random;
	__scriptCallbacks[key] = callback;

	var script = document.createElement('script');
	script.type = 'text/javascript';
	script.async = true;
	script.id = 'script_' + random;
	script.src = path + (path.indexOf('?') == -1 ? '?' : '&') + 'id=' + random;

	var s = document.getElementsByTagName('script')[0];
	s.parentNode.insertBefore(script, s);
};

function loadScript_handler(id, data)
{
	var __scriptCallbacks = (window['_callbacks'] || (window['_callbacks'] = {}));
	var key = 'cb_' + id;

	// try to lookup for the callback
	if(key in __scriptCallbacks);
	__scriptCallbacks[key](data);
}

$.makeCorners = function(selector)
{
	$(selector).each(function()
	{
		var c = $(this).attr('corner');
		var p = $(this).attr('cornerplacement');

		// set corners
		$(this).corner(c + 'px ' + p);

		// remove attributes
		$(this)
			.removeAttr('corner')
			.removeAttr('cornerplacement');
	});
};

/* AlertBox Handlers */
function remove_alert_box(caller)
{
	$(caller).closest('div.ui-widget').fadeOut('slow', function()
	{
		var callback = $(this).data('onClose');
		if(typeof (callback) == 'function')
			callback();

		// destroy alert box
		$(this).remove();
	});
}

var ProgressBar =
{
	_id: '#progressbar'
	, _statusId: '#progress_status'
	, _timer: null
	, _time: 10000
	, _interval: 200
	, _element: null
	, _step: 0.5
	, _steps: null
	, _destroyCallback: null
	, _status: null

	, get_value: function() { return parseFloat($(this._element).progressbar('value')); }
	, set_value: function(value) { $(this._element).progressbar('value', value); }

	, get_status: function() { return $(this._statusId).find('span').first().html(); }
	, set_status: function(value) { $(this._statusId).find('strong').first().html(value); }

	, start: function(time, interval, callback)
	{
		this._time = (time != null ? time : this._time);
		this._interval = (interval != null ? interval : this._interval);
		this._destroyCallback = (callback != null ? callback : this._destroyCallback);

		this._steps = (this._time / this._interval);
		this._step = parseFloat(100 / this._steps);

		if(this._element == null)
			this._element = $(this._id);

		this.reset();
		this.set_value(this._step);

		this._increment();

		$(this._statusId).show();
	}

	, stop: function()
	{
		window.clearTimeout(ProgressBar._timer);
	}

	, pause: function()
	{
		this.set_status(ProgressBarStatus.paused);
		window.clearTimeout(ProgressBar._timer);
	}

	, unpause: function()
	{
		this.set_status(ProgressBarStatus.searching);
		ProgressBar._increment();
	}

	, complete: function(callback)
	{
		if(callback != null)
			this._destroyCallback = callback;

		ProgressBar.set_value(100);
		ProgressBar.set_status(ProgressBarStatus.completed);

		setTimeout(function()
		{
			ProgressBar.destroy();

			$(ProgressBar._statusId).hide();
		}, 200);
	}

	, reset: function()
	{
		this._element
			.show()
			.progressbar({ value: 0 });

		this.set_status(ProgressBarStatus.searching);
	}

	, destroy: function(callback)
	{
		if(callback != null)
			this._destroyCallback = callback;

		window.clearTimeout(ProgressBar._timer);

		$(this._element).fadeOut('fast', function()
		{
			$(this).progressbar('destroy').hide();
			if(ProgressBar._destroyCallback != null)
				ProgressBar._destroyCallback();
		});
	}

	, _increment: function()
	{
		var current = ProgressBar.get_value();

		if(current > 99)
			ProgressBar.destroy();
		else
		{
			ProgressBar.set_value(ProgressBar.get_value() + ProgressBar._step);
			ProgressBar._timer = setTimeout(ProgressBar._increment, ProgressBar._interval);
		}
	}
}

function Payment_Fade(div)
{
	with($(div.id == 'left' ? '#right' : '#left'))
	{
		fadeTo('fast', 0.5);
		css({ 'border': '2px solid #ffffff' });
		css({ 'display': 'none' });
	}

	with($('#' + div.id))
	{
		fadeTo('fast', 1);
		css({ 'border': '2px solid #1d4989' });
	}
}

function Payment_DeliveryMethodChanged() { }
function forceUpperCaseLatinCharacters(obj) { $(obj).val(toGreeklish($(obj).val())); }

function toLower(letter)
{
	var letterIsProblematic = false;
	var problematicChars = 'ΤΥΎΫΦΧΨΩΏ';
	for(var i = 0;i < problematicChars.length;i++)
	{
		if(letter == problematicChars.charAt(i))
		{
			lettIsProblematic = true;

			switch(letter)
			{
				case 'Τ':
					return ('τ');
					break;
				case 'Υ': case 'Ύ': case 'Ϋ':
					return ('υ');
					break;
				case 'Φ':
					return ('φ');
					break;
				case 'Χ':
					return ('χ');
					break;
				case 'Ψ':
					return ('ψ');
					break;
				case 'Ω': case 'Ώ':
					return ('ω');
					break;
			}
		}
	}
	return (letter.toLowerCase());
}

function toLatin(greekText)
{
	var lett = '';
	var lettIsProblematic = false;
	var lett0 = '';
	var lett2 = '';
	var lett3 = '';
	var newlett = '';
	var str = '';
	var result = '';
	var isUpper = false;
	var isUpper0 = false;
	var isUpper2 = false;

	for(var i = 0;i < greekText.length;i++)
	{
		lett = greekText.charAt(i);
		lett0 = i > 0 ? greekText.charAt(i - 1) : '';
		lett2 = i <= greekText.length - 1 ? greekText.charAt(i + 1) : '';
		lett3 = i <= greekText.length - 2 ? greekText.charAt(i + 2) : '';
		isUpper = lett.toUpperCase() == lett && lett != 'ς';
		isUpper0 = lett0.toUpperCase() == lett0;
		isUpper2 = lett2.toUpperCase() == lett2;
		lett = toLower(lett);
		lett0 = toLower(lett0);
		lett2 = toLower(lett2);
		lett3 = toLower(lett3);
		newlett = '';
		switch(lett)
		{
			case 'α':
				switch(lett2)
				{
					case 'υ': case 'ύ':
						str = 'βγδζλμνραάεέηήιίϊΐοόυύϋΰωώ';
						if(str.indexOf(lett3) != -1 && lett3 != '')
						{
							newlett = 'av';
							i++;
						}
						str = 'θκξπστφχψ';

						if(str.indexOf(lett3) != -1 || lett3 == '')
						{
							newlett = 'af';
							i++;
						}
						break;
					default:
						newlett = 'a';
				}
				break;
			case 'ά':
				newlett = 'a';
				break;
			case 'β':
				newlett = 'v';
				break;
			case 'γ':
				switch(lett2)
				{
					case 'γ':
						newlett = 'ng';
						i++;
						break;
					case 'ξ':
						newlett = 'nx';
						i++;
						break;
					case 'χ':
						newlett = 'nch';
						i++;
						break;
					default:
						newlett = 'g';
				}
				break;
			case 'δ':
				newlett = 'd';
				break;
			case 'ε':
				switch(lett2)
				{
					case 'υ': case 'ύ':
						str = 'βγδζλμνραάεέηήιίϊΐοόυύϋΰωώ';
						if(str.indexOf(lett3) != -1 && lett3 != '')
						{
							newlett = 'ev';
							i++;
						}
						str = 'θκξπστφχψ';

						if(str.indexOf(lett3) != -1 || lett3 == '')
						{
							newlett = 'ef';
							i++;
						}
						break;
					default:
						newlett = 'e';
				}
				break;
			case 'έ':
				newlett = 'e';
				break;
			case 'ζ':
				newlett = 'z';
				break;
			case 'η': case 'ή':
				switch(lett2)
				{
					case 'υ': case 'ύ':
						str = 'βγδζλμνραάεέηήιίϊΐοόυύϋΰωώ';
						if(str.indexOf(lett3) != -1 && lett3 != '')
						{
							newlett = 'iv';
							i++;
						}
						str = 'θκξπστφχψ';

						if(str.indexOf(lett3) != -1 || lett3 == '')
						{
							newlett = 'if';
							i++;
						}
						break;
					default:
						newlett = 'i';
				}
				break;
			case 'θ':
				newlett = 'th';
				break;
			case 'ι': case 'ί': case 'ϊ': case 'ΐ':
				newlett = 'i';
				break;
			case 'κ':
				newlett = 'k';
				break;
			case 'λ':
				newlett = 'l';
				break;
			case 'μ':
				if(lett2 == 'π')
				{
					newlett = (lett0 == '' || lett3 == '' || lett0 == ' ' || lett3 == ' ') ? 'b' : 'mp';
					i++;
				} else
					newlett = 'm';
				break;
			case 'ν':
				newlett = 'n';
				break;
			case 'ξ':
				newlett = 'x';
				break;
			case 'ο':
				if((lett2 == 'υ' || lett2 == 'ύ') && lett != 'ό')
				{
					newlett = 'ou';
					i++;
				} else
					newlett = 'o';
				break;
			case 'ό':
				newlett = 'o';
				break;
			case 'π':
				newlett = 'p';
				break;
			case 'ρ':
				newlett = 'r';
				break;
			case 'σ': case 'ς':
				newlett = 's';
				break;
			case 'τ':
				newlett = 't';
				break;
			case 'υ': case 'ύ': case 'ϋ': case 'ΰ':
				newlett = 'y';
				break;
			case 'φ':
				newlett = 'f';
				break;
			case 'χ':
				newlett = 'ch';
				break;
			case 'ψ':
				newlett = 'ps';
				break;
			case 'ω': case 'ώ':
				newlett = 'o';
				break;
			default:
				newlett = lett;
		}
		if(isUpper)
			newlett = newlett.charAt(0).toUpperCase() + (isUpper2 ? newlett.substr(1).toUpperCase() : toLower(newlett.substr(1)));
		result += newlett;
	}

	return result;
}

String.convertToSearchable = function(greekText)
{
	var lett = '';
	var lettIsProblematic = false;
	var lett0 = '';
	var lett2 = '';
	var lett3 = '';
	var newlett = '';
	var str = '';
	var result = '';
	var isUpper = false;
	var isUpper0 = false;
	var isUpper2 = false;

	for(var i = 0;i < greekText.length;i++)
	{
		lett = greekText.charAt(i);
		lett0 = i > 0 ? greekText.charAt(i - 1) : '';
		lett2 = i <= greekText.length - 1 ? greekText.charAt(i + 1) : '';
		lett3 = i <= greekText.length - 2 ? greekText.charAt(i + 2) : '';
		isUpper = lett.toUpperCase() == lett && lett != 'ς';
		isUpper0 = lett0.toUpperCase() == lett0;
		isUpper2 = lett2.toUpperCase() == lett2;
		lett = toLower(lett);
		lett0 = toLower(lett0);
		lett2 = toLower(lett2);
		lett3 = toLower(lett3);
		newlett = '';

		switch(lett)
		{
			case 'α':
			case 'ά':
				switch(lett2)
				{
					case 'υ': case 'ύ':
						str = 'βγδζλμνραάεέηήιίϊΐοόυύϋΰωώ';
						if(str.indexOf(lett3) != -1 && lett3 != '')
						{
							newlett = 'av';
							i++;
						}
						str = 'θκξπστφχψ';

						if(str.indexOf(lett3) != -1 || lett3 == '')
						{
							newlett = 'af';
							i++;
						}
						break;

					case 'ι':
					case 'ί':
						newlett = 'e';
						i++;
						break;

					default:
						newlett = 'a';
				}
				break;
			case 'β':
				newlett = 'v';
				break;
			case 'γ':
				switch(lett2)
				{
					case 'γ':
						newlett = 'ng';
						i++;
						break;
					case 'ξ':
						newlett = 'nx';
						i++;
						break;
					case 'χ':
						newlett = 'nch';
						i++;
						break;
					default:
						newlett = 'g';
				}
				break;
			case 'δ':
				newlett = 'd';
				break;
			case 'ε':
			case 'έ':
				switch(lett2)
				{
					case 'υ': case 'ύ':
						str = 'βγδζλμνραάεέηήιίϊΐοόυύϋΰωώ';
						if(str.indexOf(lett3) != -1 && lett3 != '')
						{
							newlett = 'ev';
							i++;
						}
						str = 'θκξπστφχψ';

						if(str.indexOf(lett3) != -1 || lett3 == '')
						{
							newlett = 'ef';
							i++;
						}
						break;

					case 'ι':
					case 'ί':
						newlett = 'i';
						i++;
						break;
					default:
						newlett = 'e';
				}
				break;
			case 'ζ':
				newlett = 'z';
				break;
			case 'η':
			case 'ή':
				switch(lett2)
				{
					case 'υ': case 'ύ':
						str = 'βγδζλμνραάεέηήιίϊΐοόυύϋΰωώ';
						if(str.indexOf(lett3) != -1 && lett3 != '')
						{
							newlett = 'iv';
							i++;
						}
						str = 'θκξπστφχψ';

						if(str.indexOf(lett3) != -1 || lett3 == '')
						{
							newlett = 'if';
							i++;
						}
						break;
					default:
						newlett = 'i';
				}
				break;
			case 'θ':
				newlett = 'th';
				break;
			case 'ι':
			case 'ί':
			case 'ϊ':
			case 'ΐ':
				newlett = 'i';
				break;
			case 'κ':
				newlett = 'k';
				break;
			case 'λ':
				newlett = 'l';
				break;
			case 'μ':
				if(lett2 == 'π')
				{
					newlett = (lett0 == '' || lett3 == '' || lett0 == ' ' || lett3 == ' ') ? 'b' : 'mp';
					i++;
				}
				else
					newlett = 'm';
				break;
			case 'ν':
				newlett = 'n';
				break;
			case 'ξ':
				newlett = 'x';
				break;
			case 'ο':
			case 'ό':
				if((lett2 == 'υ' || lett2 == 'ύ') && lett != 'ό')
				{
					newlett = 'ou';
					i++;
				}
				else if(lett2 == 'ι' || lett2 == 'ί' || lett2 == 'ϊ')
				{
					newlett = 'i';
					i++;
				}
				else
					newlett = 'o';
				break;
			case 'π':
				newlett = 'p';
				break;
			case 'ρ':
				newlett = 'r';
				break;
			case 'σ': case 'ς':
				newlett = 's';
				break;
			case 'τ':
				newlett = 't';
				break;
			case 'υ': case 'ύ': case 'ϋ': case 'ΰ':
				newlett = 'y';
				break;
			case 'φ':
				newlett = 'f';
				break;
			case 'χ':
				newlett = 'ch';
				break;
			case 'ψ':
				newlett = 'ps';
				break;
			case 'ω': case 'ώ':
				newlett = 'o';
				break;
			default:
				newlett = lett;
		}
		if(isUpper)
			newlett = newlett.charAt(0).toUpperCase() + (isUpper2 ? newlett.substr(1).toUpperCase() : toLower(newlett.substr(1)));
		result += newlett;
	}

	return result;
}

function toGreeklish(value)
{
	return toLatin(value).toUpperCase();
}

/* global methods for alerting */
// modal dialog helper
function get_dialog()
{
	var dg = $('#dialog-modal');
	if(dg.size() == 0)
		dg = $('div.sgtk').after(String.format('<div id="dialog-modal" style="display:none;" title="{0}"></div>', ferries_resources.Caution));
	return dg;
}

_alert = alert_message = function(title, message, opts)
{
	setTimeout(function()
	{
		alert_opener(title, message, opts);
	}, 0);
}

function alert_opener(title, message, opts)
{
	// get alert box element
	var dg = get_dialog();

	// create opts if empty
	opts = (opts || {});

	// default width / height
	if(opts.height == null)
	{
		var _width = ((opts != null && opts.width) || 300);
		var _height = calculateHeight(message, _width);

		opts.width = _width;
		opts.height = _height + (opts.buttons == null ? 50 : 130);
	}

	var dialog_options =
	{
		resizable: false
		,draggable: false
		,height: 100
		,modal: true
		,open: function()
		{
			var value = $(this).css('overflow-x');
			$(document.body).data('prev', value).css('overflow-x', 'hidden');
		}
		,buttons: null
		,width: 300
	}

	var defaultClose = function()
	{
		$(document.body).css('overflowX', function()
		{
			var d = $(this).data('prev');
			return (d == null ? 'auto' : d);
		});

		if($.browser.msie) // patch for ie bug with modal window
			$('#sticky-footer-push').remove();
	}

	if(opts != null)
		dialog_options = $.extend(dialog_options, opts);

	// set content
	dg.html(message);

	// set dialog options
	dg.dialog(
	{
		title: title
		, bgiframe: true
		, draggable: dialog_options.draggable
		, resizable: dialog_options.resizable
		, minHeight: dialog_options.height
		, width: dialog_options.width
		, height: dialog_options.height
		, modal: dialog_options.modal
		, open: dialog_options.open
		, dialogClass: dialog_options.dialogClass
		, close: function()
		{
			if(window._fixAlertBox != null)
			{
				defaultClose();

				if(dialog_options.close != null)
					dialog_options.close();
			}

			if($.browser.msie && $.browser.version < 9)
				$('body').css('overflow-x', '')
		}
		, buttons: dialog_options.buttons
	});

	// fix ie7 bug with height
	if(window._fixAlertBox == null)
	{
		// fix stupid error
		dg.dialog('close').dialog('destroy');

		// re-open
		setTimeout(function()
		{
			alert_opener(title, message, opts);
		}, 5);


		window._fixAlertBox = true;
	}

	return dg;
}

function _warning(message, onClose, size)
{
	var opts =
	{
		buttons:
		{
			'OK': function()
			{
				$(this).dialog('close');
			}
		}
	}

	if(onClose != null)
		opts.close = onClose;

	if(size != null)
		$.extend(opts, size);

	alert_message(air_resources.Warning, message, opts);
}

function _confirm(message, actionYes, actionNo)
{
	alert_message(air_resources.Warning, message
	, {
		buttons:
		{
			'Ναι': function()
			{
				$(this).dialog('close');
				actionYes();
			}
			, 'Όχι': function()
			{
				$(this).dialog('close');
				actionNo();
			}
		}
	})
}

function is_valid_date(value)
{
	var valid = false;
	try { $.datepicker.parseDate('dd/mm/yy', value);valid = true; } catch(ex) { }
	return valid;
}

$(document).ready(function()
{
/* JQuery Cookie Plugin */
// @author Klaus Hartl/klaus.hartl@stilbuero.de
jQuery.cookie = function(name, value, options)
{
	if(typeof (value) != 'undefined')
	{ // name and value given, set cookie
		options = options || {};

		if(value === null)
		{
			value = '';
			options.expires = -1;
		}

		var expires = '';
		if(options.expires && (typeof (options.expires) == 'number' || options.expires.toUTCString))
		{
			var date = null;
			if(typeof options.expires == 'number')
			{
				date = new Date();
				date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
			}
			else
				date = options.expires;
			expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
		}

		// CAUTION: Needed to parenthesize options.path and options.domain
		// in the following expressions, otherwise they evaluate to undefined
		// in the packed version for some reason...
		var path = options.path ? '; path=' + (options.path) : '';
		var domain = options.domain ? '; domain=' + (options.domain) : '';
		var secure = options.secure ? '; secure' : '';
		document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
	}
	else
	{
		// only name given, get cookie
		var cookieValue = null;
		if(document.cookie && document.cookie != '')
		{
			var cookies = document.cookie.split(';');
			for(var i = 0;i < cookies.length;i++)
			{
				var cookie = jQuery.trim(cookies[i]);
				// Does this cookie string begin with the name we want?
				if(cookie.substring(0, name.length + 1) == (name + '='))
				{
					cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
					break;
				}
			}
		}
		return cookieValue;
	}
};
});

function SaveCookie(name, value, exp)
{
	var COOKIE_NAME = name;
	var options = { path: '/', expires: exp };
	$.cookie(COOKIE_NAME, value, options);
}

String.prototype.startsWithRange = function(range)
{
	var result = false;
	for(var i = 0;i < range.length;i++)
	{
		if(this.startsWith(range[i]))
		{
			result = true;
			break;
		}
	}
	return (this.length > 0 && result);
}

var __Validators =
{

	is_validPhoneNumber: function(number)
	{

		var patterns =
		{
			number: new RegExp(/^\d{7,25}/)
			, local: new RegExp(/^(2\d{9}|302\d{9}|(69|70)\d{8}|30(69|70)\d{8}|(800|801|806|812|825)\d{7}|30(800|801|806|812|825)\d{7})$/)
		}

		var valid = false;

		return patterns.number.test(number);

		if(patterns.number.test(number))
		{
			if(number.startsWith('00'))
			{
				if(number.startsWithRange(['00302', '00306']) && number.substring(5).length == 9)
					valid = true;
				else if(number.startsWithRange(['00302', '00306']) && number.substring(5).length != 9)
					valid = false;
				else if(number.startsWithRange(['0030801', '0030800']) && number.substring(7).length == 7)
					valid = true;
				else if(number.startsWithRange(['0030801', '0030800']) && number.substring(7).length != 7)
					valid = false;

				else if(number.startsWithRange(['0030806', '0030812']) && number.substring(7).length == 7)
					valid = true;
				else if(number.startsWithRange(['0030806', '0030812']) && number.substring(7).length != 7)
					valid = false;

				else if(number.startsWithRange(['0030825']) && number.substring(7).length == 7)
					valid = true;
				else if(number.startsWithRange(['0030825']) && number.substring(7).length != 7)
					valid = false;

				else if(number.startsWith('00700700') && number.substring(8).length == 4)
					valid = true;
				else if(number.startsWith('00700700') && number.substring(8).length != 4)
					valid = false;
				else if(number.substring(2).length >= 9)
					valid = true;
				else
					valid = false;
			}
			else
			{
				valid = patterns.local.test(number);
			}
		}

		return valid;

	}

	, is_email: function(email)
	{
		//		var supported = 0;
		//		var result = false;
		//		
		//		if(window.RegExp)
		//		{
		//			var tempStr = "a";
		//			var tempReg = new RegExp(tempStr);
		//			if (tempReg.test(tempStr)) supported = 1;
		//		}
		//		
		//		if (!supported) 
		//			result = (email.indexOf(".") > 2) && (email.indexOf("@") > 0);
		//		else
		//		{
		//			var r1 = new RegExp("(@.*@)|(\\.\\.)|(@\\.)|(^\\.)");
		//			var r2 = new RegExp("^.+\\@(\\[?)[a-zA-Z0-9\\-\\.]+\\.([a-zA-Z]{2,3}|[0-9]{1,3})(\\]?)$");
		//			result = (!r1.test(email) && r2.test(email));
		//		}
		var r = new RegExp(/^([a-zA-Z0-9_\-])+(\.([a-zA-Z0-9_\-])+)*@((\[(((([0-1])?([0-9])?[0-9])|(2[0-4][0-9])|(2[0-5][0-5])))\.(((([0-1])?([0-9])?[0-9])|(2[0-4][0-9])|(2[0-5][0-5])))\.(((([0-1])?([0-9])?[0-9])|(2[0-4][0-9])|(2[0-5][0-5])))\.(((([0-1])?([0-9])?[0-9])|(2[0-4][0-9])|(2[0-5][0-5]))\]))|((([a-zA-Z0-9])+(([\-])+([a-zA-Z0-9])+)*\.)+([a-zA-Z])+(([\-])+([a-zA-Z0-9])+)*))$/)

		return r.test(email);
	}

	, is_vat: function(value)
	{
		var valid = false;

		if(value.match(/[^0-9]/g) > 0 || value.length != 9)
			valid = false;
		else
		{
			var total = 0;

			for(var i = 0;i < 8;i++)
				total += value.substr(i, 1) * (1 << (9 - i - 1));

			valid = true;

			if(!(((total % 11) % 10) == value.substr(9 - 1)) || (value == "000000000"))
				valid = false;
		}

		return (valid);
	}

	, is_identity: function(value)
	{
		var valid = false;
		var r = new RegExp(/^[Α-Ω]{1,2}[0-9]{6}$/);

		valid = r.test(value.toUpperCase());

		return (valid);
	}

	, is_creditCard: function(value)
	{
		var r = /^((4\d{3})|(5[1-5]\d{2})|(6011)|(6364))-?\d{4}-?\d{4}-?\d{4}|3[4,7]\d{13}$/;
		var len = /^(\d){15,16}$/;

		var scope = $('select[scope=cardType]').children('option[selected]').attr('cvv');
		if(scope != null)
			len = (scope == 'amex' ? /^(\d){15}$/ : /^(\d){16}$/);

		return len.test(value) && r.test(value);
	}

	, is_guid: function(value)
	{
		return /^([0-9a-f]{8})\-(([0-9a-f]{4})\-){3}([0-9a-f]{12})$/gi.test(value);
	}

	, customValidators: {}
};

__Validators.customValidators =
{
	validateEmail: function(sender, args)
	{
		args.IsValid = __Validators.is_email(args.Value);
	}
	, validatePhoneNumber: function(sender, args)
	{
		args.IsValid = __Validators.is_validPhoneNumber(args.Value);
	}
	, validateVAT: function(sender, args)
	{
		args.IsValid = __Validators.is_vat(args.Value);
	}
	, validateIdentity: function(sender, args)
	{
		args.IsValid = __Validators.is_identity(args.Value);
	}
	, validateCreditCard: function(sender, args)
	{
		args.IsValid = __Validators.is_creditCard(args.Value);
	}
	, validateChecked: function(sender, args)
	{
		alert(args.Value);
		//args.IsValid = 
	}
}

/* Credit card */
function validate_cardnumber(source, args)
{
	var r = /^((4\d{3})|(5[1-5]\d{2})|(6011))-?\d{4}-?\d{4}-?\d{4}|3[4,7]\d{13}$/;
	args.IsValid = r.test(args.Value);
}

function validate_expirationdate(sender, args)
{
	var month = $('select[id$=ddlCardExpirationMonth]');
	var year = $('select[id$=ddlCardExpirationYear]');
	return is_validExpirationDate(month.val(), year.val());
}

function validateCCTermsChecked(sender, args) { args.IsValid = $('input[type=checkbox][id$=TermsAgreementCreditCard]').is(':checked'); }
function validatePaypalTermsChecked(sender, args) { args.IsValid = $('input[type=checkbox][id$=TermsAgreementPaypal]').is(':checked'); }
function validateBankTermsChecked(sender, args) { args.IsValid = $('input[type=checkbox][id$=TermsAgreementBank]').is(':checked'); }
function validateCashTermsChecked(sender, args) { args.IsValid = $('input[type=checkbox][id$=TermsAgreementCash]').is(':checked'); }
function validateCashOnDeliveryTermsChecked(sender, args) { args.IsValid = $('input[type=checkbox][id$=TermsAgreementCashOnDelivery]').is(':checked'); }

function validate_acceptTermsOfUse(sender, args)
{
	var selector = 'input[type=checkbox][id$=' + $(sender).attr('_target') + ']'
	args.IsValid = $(selector).is(':checked');
}

function validate_cvv(sender, args)
{
	var patterns = { other: /^[0-9]{3}$/, amex: /^[0-9]{4}$/ };
	var selection = $('select[scope=cardType]').children().filter('[selected]');
	args.IsValid = patterns[selection.attr('cvv')].test(args.Value);
}

function formatDate(date)
{
	var parts = date.split('/');

	if(parts[1].length == 1)
		parts[1] = '0' + parts[1].toString();

	return parts[0] + '/' + parts[1];
}

function is_validExpirationDate(month, year)
{
	var now = new Date();
	var isvalid = true;

	var expiration = formatDate(year + '/' + month);
	var current = formatDate(now.getFullYear() + '/' + (now.getMonth() + 1));

	return (expiration >= current);
}

function calculateHeight(html, width)
{
	var div = $('<div style="width: ' + width + 'px; display: block;"> ' + html + '</div>').appendTo($('body'));
	var height = div.get(0).offsetHeight;
	div.remove();

	return height;
}

function validate_vivaTransactionCode(sender, args) { args.IsValid = (args.Value.length == 10); }

function _googleAnalytics()
{
	
	var ga = document.createElement('script');
	ga.type = 'text/javascript';
	ga.async = true;
	if($.browser.msie)
		ga.defer = true;
	ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';

	var s = document.getElementsByTagName('script')[0];
	s.parentNode.insertBefore(ga, s);
	
}

function _click2chat()
{
	if(self == top)
	{
		if(location.protocol == 'http:')
		{
			var wo = document.createElement('script');
			wo.type = 'text/javascript';
			wo.async = true;
			wo.src = 'http://wogateway2.viva.gr/include.js?domain=travel.viva.gr&rnd=' + Math.random();
			var _onLoad = function()
			{
				sWOResponse = '';
				sWOInvite = 'N'; //(location.protocol == 'http:' ? 'Y' : 'N');
				sWOUrlEmbedAsync = 'Y';
				sWOEmbedTarget = 'div.sgtk';

				if(typeof (sWOTrackPage) == 'function')
					sWOTrackPage();
			}

			// for ie
			if(window.ActiveXObject)
			{
				wo.onreadystatechange = function()
				{
					if(this.readyState == 'loaded')
						_onLoad();
				}
			}
			else // firefox
				$(wo).load(_onLoad);

			if($.browser.msie)
				wo.defer = true;

			var s = document.getElementsByTagName('script')[0];s.parentNode.insertBefore(wo, s);
		}
		else
		{
			// track
			if($.browser.msie && $.browser.version < 9)
				$(window).load(_trackWOPageView);
			else
				_trackWOPageView();
		}
	}
}

function __gc(name)
{
	var cookieValue = null;
	if(document.cookie && document.cookie != '')
	{
		var cookies = document.cookie.split(';');
		for(var i = 0;i < cookies.length;i++)
		{
			var cookie = jQuery.trim(cookies[i]);
			// Does this cookie string begin with the name we want?
			if(cookie.substring(0, name.length + 1) == (name + '='))
			{
				cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
				break;
			}
		}
	}
	return cookieValue;
}

function _trackWOPageView(url, referrer)
{
	// build request
	var u = escape(__gc('whoson'));
	var p = (url || escape(document.location.href));
	var r = (referrer || escape(document.referrer));
	var rnd = Math.random().toString();

	var img = $(String.format('<img src="/cmstemplates/vivatravelaspx/data/common/whoson.ashx?u={0}&p={1}&r={2}&rnd={3}" />', u, p, r, rnd)).css({
		position: 'absolute'
		, zIndex: 100
		, left: -1000
		, top: -1000
	});

	// append to page tracking image
	$('body').append(img);

	// remove after image load
	$(img).load(function()
	{
		setTimeout(function()
		{
			// remove from collection
			$(img).remove();
		}, 100);
	});
}

$.fn.shuffle = function()
{
	var allElems = this.get()
		, getRandom = function(max)
		{
			return Math.floor(Math.random() * max);
		}
		, shuffled = $.map(allElems, function()
		{
			var random = getRandom(allElems.length)
				, randEl = $(allElems[random]).clone(true)[0];
			allElems.splice(random, 1);
			return randEl;
		});

	this.each(function(i)
	{
		$(this).replaceWith($(shuffled[i]));
	});

	return $(shuffled);
};


function amountAnalysis(caller, type)
{
	var div = $('div[amountAnalysis=' + type + ']');
	var span = $('div[analysis=' + type + ']');
	var a = $(caller);

	a.removeClass().addClass(function()
	{
		return String.format('amount-analysis {0}', (div.is(':visible') ? 'green-expand-plus' : 'green-expand-minus'));
	});

    var ie78 = ($.browser.msie && ($.browser.version == 7 || $.browser.version == 8));
    
    if (!ie78)
    {
	    var pos = span.position();
	    var width = 0;
	    div.css({ left: (pos.left + width), top: (pos.top + 31) });
	}

	// call
	var method = (div.is(':visible') ? (ie78 ? 'slideUp' : 'hide') : (ie78 ? 'slideDown' : 'show'));
	div[method]('fast');
}

/* payment related items */
function _live()
{
	// bind hidden events for elements
	$('input[live],select[live],textarea[live]').each(function()
	{
		var text = $(this).attr('live');
		var funcs = eval("(" + text + ")");
		for(var name in funcs)
		{
			var item = funcs[name];
			var method = ($.isFunction(item) ? funcs[name] : funcs[name].h);

			// bind event handler now
			$(this).bind(name, method);

			// if item is not a function and call is true execute it
			if(!$.isFunction(item) && item.c)
				$(this).trigger(name);
		};
	});
}

function apply_creditCardRules()
{
	var cvv = $(this.options[this.selectedIndex]).attr('cvv');
	$('img[cvv],span[cvv]')
		.hide()
		.filter('[cvv=' + cvv + ']')
		.show();

	$('input[scope=cardNumber]').attr('maxlength', function()
	{
		return (cvv == 'other' ? 16 : 15);
	}).val(function()
	{
		return this.value.substring(0, this.maxLength);
	});
};

/* Phone Verification Helper */
function phoneverification_display(id, prefix, phone)
{
	// push an event for phone verification
	Google.trackEvent('Alerts', 'CreditCard', 'PhoneVerification');

	var p = $('div#phoneverificationTemplate').clone().attr('id', 'phoneverification').appendTo($('body'));
	p.find('[role]').each(function()
	{

		$(this).attr('role', function()
		{
			return $(this).attr('role').replace(/\-template$/gi, '');
		});
	}).filter('input[type=text]').keydown(function(event)
	{
		if(event.keyCode == 13)
		{
			var button = $(this).closest('table').find('input[type=button][role]');
			button.click();
			return (false);
		};
	});

	// set phone
	var phone = $('[role=verification-phone]').val(phone);
	setTimeout(function()
	{
		phone.focus();
	}, 50);

	// set verification id
	$('[role=verificationId]', p).val(id);

	// set prefix
	p.find('[role=prefix]').html('+' + prefix);

	// transform all buttons
	p.find('input[type=button]').button();

	// push div
	alert_message(air_resources.PhoneVerTitle, p.show(),
	{
		width: 500
		, height: 180
		, open: function()
		{
			$(this).dialog('option', 'height', $(this).height() + 40);
		}
	});
}

function double_alert_box(message, onClose)
{
	var dg = $('<div></div>');

	dg.dialog(
	{
		title: air_resources.PhoneVerTitle
		, modal: true
		, resizable: false
		, draggable: false
		, buttons:
		{
			'OK': function()
			{
				$(this).dialog('close');
				if(onClose != null)
					onClose();
			}
		}
	}).html(message);
}

function phoneverification_call()
{
	var div = $('div#phoneverification');
	var phone = div.find('[role=verification-phone]');
	var r = new RegExp(/^[0-9]{7,36}$/);

	if(phone.val() == null || phone.val().length == 0)
	{
		double_alert_box(air_resources.PhoneVerFillPhone, function()
		{
			phone.focus();
		});
	}
	else if(!r.test(phone.val()))
	{
		double_alert_box(air_resources.PhoneVerInvalidPhone, function()
		{
			phone.focus().select();
		});
	}
	else
	{
		// block ui
		div.block();

		var unblock = function()
		{
			// unblock div
			div.unblock();

			// show verification input
			$('[role=verification]', div)
				.show()
				.find('input[role=validationKey]')
				.focus();

			// resize to show all
			var dg = get_dialog();
			dg.dialog('option', 'height', 270);
		}

		// send request for call
		var id = $('[role=verificationId]').val();
		var action = { a: '0', v: phone.val() };
		var query = String.format('v={0}&ac={1}', id, Sys.Serialization.JavaScriptSerializer.serialize(action));

		$.ajax(
		{
			url: '/cmstemplates/vivatravelaspx/data/common/phonever.ashx'
			, data: query
			, dataType: 'json'

			, success: function(result)
			{
				// track
				Google.trackEvent('Alerts', 'CreditCardVerification', 'VerificationCall');

				unblock();
			}
			, error: function(x, f, e)
			{
				// unspecified error in call
				double_alert_box(air_resources.PhoneVerUnspecifiedError);
				unblock();
			}
		});
	}
}

function phoneverification_validate()
{
	var div = $('div#phoneverification');
	var id = $('[role=verificationId]', div).val();
	var key = $('[role=validationKey]', div);

	var value = key.val();

	if(value == null || value.length == 0)
	{
		double_alert_box(air_resources.PhoneVerFillKey, function()
		{
			key.focus();
		});
	}
	else if(!/^[0-9]{4}$/.test(value))
	{
		double_alert_box(air_resources.PhoneVerInvalidKey, function()
		{
			key.focus().select();
		});
	}
	else
	{
		// block ui
		div.block();

		var unblock = function(result)
		{
			// unblock ui
			div.unblock();

			if(result == 0)
			{
				// track
				Google.trackEvent('Alerts', 'CreditCardVerification', ' WrongPIN');

				// resize to show all
				var dg = get_dialog();
				dg.dialog('option', 'height', (result == 0 ? 310 : 310));

				var vf = $('[role=verification]', div)
				vf.find('div.ui-widget,div.hsep10').remove();

				// append a new message box
				vf.append('<div class="hsep10"></div>')
					.append(AlertBox.create(air_resources.PhoneVerResult0, { type: AlertBoxType.Warning }));
			}
			else if(result == 2)
			{
				// track
				Google.trackEvent('Alerts', 'CreditCardVerification', 'RejectedTooManyAttempts');

				var _buttons = {};
				_buttons[air_resources.PhoneVerResult2Button1] = function() { $(this).dialog('close'); };
				_buttons[air_resources.PhoneVerResult2Button2] = function()
				{
					$(this).dialog('close');

					// go back
					switch_page(2, false);

					// change tab
					location.hash = 'bank-tab';

					// check terms of use
					$('input[type=checkbox][id$=TermsAgreementBank]').attr('checked', true);

					setTimeout(function()
					{
						// call book-now trigger
						validate_payment_form(__paymentTypes.bank);
					}, 10);
				}

				// show message
				alert_message(air_resources.PhoneVerTitle, air_resources.PhoneVerResult2,
				{
					width: 450
					, height: 240
					, buttons: _buttons
				});
			}
			else if(result == 1)
			{
				// track
				Google.trackEvent('Alerts', 'CreditCardVerification', 'CorrectPIN');

				// on success trigger credit card payment
				validate_payment_form(__paymentTypes.creditCard);

				// try to fix height
				setTimeout(function()
				{
					var dg = get_dialog();
					dg.dialog('option', 'height', 170);
				}, 40);
			}
		}

		// send request for call
		var id = $('[role=verificationId]').val();
		var action = { a: '1', v: value };
		var query = String.format('v={0}&ac={1}', id, Sys.Serialization.JavaScriptSerializer.serialize(action));
		$.ajax(
		{
			url: '/cmstemplates/vivatravelaspx/data/common/phonever.ashx'
			, dataType: 'json'
			, data: query
			, success: function(result)
			{
				var code = 0;
				if(result != null && result.s == 200)
					code = result.d;
				// set code
				unblock(code);
			}
			, error: function(x, f, e)
			{
				unblock(0);
			}
		});

	}
}

function doAddSubscriber(email, source, guid, onsuccess, onerror)
{
	$.ajax(
	{
		url: "/cmstemplates/vivatravelaspx/data/common/subscriptions.ashx"
		, data: "email=" + email + "&source=" + source + "&id=" + guid
		, type: "GET"
		, contentType: "application/json"
		, dataType: "json"
		, success: onsuccess
		, error: onerror
	});

	var lang = $('input[type=hidden][name=lang]').val().toUpperCase(),
        part = 1;
	if(lang.indexOf('EN') > -1)
		part = 0;
	lang = lang.split('-')[part];

	Google.trackEvent('Newsletter', 'Registration', lang);
}

function doSendInterestEmailForPackage(url, id, name, email, telephone, comments, guid, onsuccess, onerror)
{
	$.ajax(
	{
		url: "/cmstemplates/vivatravelaspx/data/common/holidaypackages.ashx"
		, data: "packageurl=" + url + "&packageid=" + id + "&name=" + name + "&email=" + email + "&telephone=" + telephone + "&comments=" + comments + "&id=" + guid
		, type: "GET"
		, contentType: "application/json"
		, dataType: "json"
		, success: onsuccess
		, error: onerror
	});

	//    var lang = $('input[type=hidden][name=lang]').val().toUpperCase(),
	//        part = 1;
	//    if (lang.indexOf('EN') > -1)
	//        part = 0;
	//    lang = lang.split('-')[part];

	//    Google.trackEvent('HolidayPackages', 'InterestEmail', lang);
}

function validate_pin(callback, queryArgs)
{
	var pin = $('input[id$=txtPIN]').val()
		, query = '';

	if(pin.length > 0)
	{
		query = 'pin=' + pin.trim() + (queryArgs != null && queryArgs.length > 0 ? queryArgs : String.empty);

		$.ajax(
		{
			url: _urlMappings.validatepin_handler
			, data: query
			, dataType: 'json'
			, success: function(data)
			{
				// store resposne in coupon container
				$('div#couponcontainer').data('coupon', data);

				if(!data.maxOccurs)
				{
					if(data.status == 1) //Valid
					{
						$('span#PINDiscount').text(data.discount);
						$('table#defaultView').hide();
						$('table#successView').show();
					}
					else
					{
						if(pin.length > 0)
						{
							$('tr#notvalidpin').show();
							$('input[id$=txtPIN]').val('');
						}
					}
				}
				else
					$('a#pinvl_btn').hide();

				if(callback != null && typeof (callback) == 'function')
					callback(data);
			}
			, error: function(xhr, ajaxOptions, thrownError) { }
		});
	}
	else
	{
		$('input[id$=txtPIN]').effect('highlight', {}, 400).focus();
		$('tr#notvalidpin').hide();
	}
}

function cp_expand_collapse(caller)
{
	$('.discounts-disabled, #discounts-disabled').toggle('fast', function()
	{
		$(caller).text($(this).is(':visible') ? ferries_resources.Hide : ferries_resources.ReadMore)
                 .toggleClass('clps');
	});
}

// Insurances
var TravelInsurance =
{
	initialize: function()
	{
		var active_label = $('#ins_accdr dt label.actv');

		this.bindEventHandlers();

		this.setActiveInsurance(active_label);
	}

	, bindEventHandlers: function()
	{
		var labels = $('#ins_accdr dt label'),
			container = $('div.ins_webpart_container'),
			toggler = $('.ins_webpart_header'),
			toggler_link = $('a#ins_toggler', toggler);


		labels.bind('click', function()
		{
			var label = $(this);
			if(!label.hasClass('actv'))
				TravelInsurance.setActiveInsurance(label, null);
		});

		toggler.click(function()
		{
			toggler_link.toggleClass('exp');
			container.slideToggle('slow');
		});
	}

	, bindprograms: function()
	{
		$('input[id$=InsuranceBindTrigger]').click();
	}

	, setActiveInsurance: function(obj, callback)
	{
		var radio = obj.find('input[type=radio]');

		$('#ins_accdr dd').slideUp();
		$('#ins_accdr dt label').removeClass('actv');
		obj.addClass('actv').parent().next().slideDown();
		radio.attr('checked', true);

		if(callback != null && typeof (callback) == 'function')
			callback(radio);
	}
};

function _safego(url)
{
	var segments = url.split('?');
	var params = segments[1].split('&');
	var sb = new Sys.StringBuilder();

	sb.append(String.format('<form id="_go" action="{0}" method="GET" target="_parent">', segments[0]));
	$.each(params, function()
	{
		var param = this.split('=');
		sb.append(String.format('<input type="hidden" name="{0}" value="{1}" />', param[0], param[1]));
	});
	sb.append('<input type="submit" /></form>');

	$(sb.toString()).appendTo('body').submit();
}

// Validation
function validateNormalGroup(groupName)
{
	var valid = Page_ClientValidate(groupName);
	var validators = Array.select(Page_Validators, function(item)
	{
		return item.validationGroup == groupName;
	});

	var controls = [];
	$(validators).each(function()
	{
		var control = this.controltovalidate;
		if(typeof (control) != 'undefined' && Array.indexOf(controls, control) == -1)
			controls.push(control);
	});

	Array.forEach(controls, function(control, index)
	{
		// get all validators validation current control
		var list = $(validators).filter('[controltovalidate=' + control + ']');
		var state = null;

		// try to find state by parsing all validators except customs
		var other = $(list).filter(function()
		{
			return this.evaluationfunction != CustomValidatorEvaluateIsValid;
		});

		//for(var i = 0; i < other.length; i++)
		$.each(other, function(i, item)
		{
			//state = other[i].isvalid;
			state = item.isvalid;
			if(!state)
				return (false);
		});

		if(state) // validation test passed
		{
			// try to find custom validators
			var custom = $(list).filter(function()
			{
				return this.evaluationfunction == CustomValidatorEvaluateIsValid; // we maybe have a problem here with validate empty text
			}); // only one

			// parse custom validators
			if(custom.size() > 0)
			{
				//for(var i = 0; i < custom.length; i++)
				$.each(custom, function(i, item)
				{
					state = item.isvalid;

					if(!state)
						return (false);
				});
			}
		}

		// set state
		$('#' + control)
			.removeClass('isvalid-true')
			.removeClass('isvalid-false')
			.addClass(String.format('isvalid-{0}', state.toString()));

	});

	return valid;
}

function validateGroup(groupName)
{
	var fields = $(String.format('input[_validation][validationGroup={0}],select[_validation][validationGroup={0}]', groupName));
	var errors = [];
	var exclude = (arguments[1] || []);
	var custom = (arguments[2] || []);

	// remove background color
	fields
		.removeClass('isvalid-true')
		.removeClass('isvalid-false');

	var list = fields.filter(function()
	{
		return !Array.contains(exclude, this.id);
	}).each(function()
	{
		var validation = $(this).data('validation');
		var valid = true;
		var value = $(this).val();

		if(validation.required && value.length == 0)
		{
			var message = (validation.messages.required != null ? validation.messages.required : String.format('{0} is required', this.id));
			errors.push([this.id, message]);

			valid = false;
		}

		if(valid && value.length > 0 && validation.pattern != null)
		{
			var r = new RegExp(validation.pattern);
			valid = r.test(value);

			if(!valid)
			{
				var message = (validation.messages.pattern != null ? validation.messages.pattern : String.format('{0} invalid (pattern)', this.id));
				errors.push([this.id, message]);
			}
		}

		if(valid && validation.method != null)
		{
			valid = validation.method(this);

			if(!valid)
			{
				var message = (validation.messages.method != null ? validation.messages.method : String.format('{0} invalid (method)', this.id));
				errors.push([this.id, message]);
			}
		}
	});

	// validate custom methods
	if(custom != null && custom.length > 0)
	{
		Array.forEach(custom, function(item, index)
		{
			if(!item.method())
				errors.push([this.id, message]);
		});
	}

	Array.forEach(errors, function(item, index)
	{
		// mark field as invalid
		$('#' + item[0]).addClass('isvalid-false');
	});

	return errors;
}

function expand_validators()
{
	var fields = $('input[_validation],select[_validation]').not('[validationGroup]');
	fields.each(function()
	{
		var meta = $.extend(new validationArgs(), eval('(' + $(this).attr('_validation') + ')'));
		$(this)
			.attr('validationGroup', meta.group)
			.data('validation', meta);
	});

}

function get_errorMessages(validationGroup)
{
	var validators = Page_Validators;
	var messages = [];

	//for(var i = 0; i < validators.length; i++)
	$.each(validators, function(i, validator)
	{
		//var validator = validators[i];
		if((validator.enabled == null || !validator.enabled) && validator.validationGroup == validationGroup && !validator.isvalid)
		{
			messages.push([validator.id, validator.errormessage]);
		}
	});

	return messages;
}

function extract_messages(input)
{
	var messages = [];
	//for(var i = 0; i < input.length; i++)
	$.each(input, function(i, item)
	{
		messages.push(item[1]);
	});
	return messages;
}

function extract_validatorName(validator)
{
	var parts = validator.split('_');
	var out = validator;
	if(parts.length > 0)
	{
		out = parts[parts.length - 1];
		if(parts.length > 1)
		{
			if(parts[parts.length - 2].startsWith('ctl'))
			{
				var value = parts[parts.length - 2].replace('ctl', '').replace(/^0/gi, '');
				out = String.format('{0}_{1}', parts[parts.length - 1], parseInt(value));
			}
		}
	}

	return out;
}

function extract_section_names(sections)
{
	var sb = new Sys.StringBuilder();
	for(var i in sections)
	{
		if(!sb.isEmpty())
			sb.append(';');
		sb.append(i);
	}

	return sb.toString();
}

function extract_validators(section)
{
	var items = [];
	//for(var i = 0; i < section.length; i++)
	$.each(section, function(i, item)
	{
		items.push(extract_validatorName(item[0]));
	});

	return items;
}

// -Validation

(function($)
{
	// Create a placeholder jQuery object with a length of 1. The single item
	// is completely arbitrary and will be replaced.
	var jq = $([1]);

	$.fn.each2 = function(fn)
	{
		var i = -1;
		while(
		// Set both the first element AND context property of the placeholder
		// jQuery object to the DOM element. When i has been incremented past the
		// end, this[++i] will return undefined and abort the while loop.
      (jq.context = jq[0] = this[++i])

		// Invoke the callback function in the context of the DOM element,
		// passing both the index and the placeholder jQuery object in. Like
		// .each, if the callback returns `false`, abort the while loop.
      && fn.call(jq[0], i, jq) !== false
    ) { }

		// Return the initial jQuery object for chainability.
		return this;
	};
})(jQuery);

/* tooltip plugin here */
var tooltip = function() { var o = "tt", m = 5, j = -23, k = 300, h = 10, i = 20, g = 100, b = 0, a, q, e, d, f, p, n, c = document.all ? true : false, l = navigator.userAgent.indexOf("MSIE 6") > -1;return { show: function(h, g, b) { l && this._hideDropDowns(true);if(a == null) { a = document.createElement("div");a.className = "tooltip_container";e = document.createElement("div");d = document.createElement("div");a.appendChild(e);a.appendChild(d);document.body.appendChild(a);a.style.opacity = 0;a.style.filter = "alpha(opacity=0)";if(arguments.length < 4) document.onmousemove = this.pos } e.className = "tooltip_" + g + "_content";d.className = "tooltip_" + g + "_bottom";a.style.display = "block";e.innerHTML = h;a.style.width = b ? b + "px" : "auto";if(!b && c) { d.style.display = "none";a.style.width = a.offsetWidth;d.style.display = "block" } if(a.offsetWidth > k) a.style.width = k + "px";f = parseInt(a.offsetHeight) + m;clearInterval(a.timer);a.timer = setInterval(function() { tooltip.fade(1) }, i);return this }, pos: function(b) { var e = c ? event.clientY + document.documentElement.scrollTop : b.pageY, d = c ? event.clientX + document.documentElement.scrollLeft : b.pageX;a.style.top = e - f + "px";a.style.left = d + j + "px" }, position: function(b, d) { var h = c ? b.clientY + document.documentElement.scrollTop : b.pageY, g = c ? b.clientX + document.documentElement.scrollLeft : b.pageX;a.style.top = h - f + "px";a.style.left = g + j + "px";if(d != null) { var e = $(d).offset();a.style.top = parseInt(e.top - f + 10) + "px";a.style.left = parseInt(e.left + $(d).width() / 2 - 10) + "px" } }, fade: function(d) { var c = b;if(c != g && d == 1 || c != 0 && d == -1) { var e = h;if(g - c < h && d == 1) e = g - c;else if(b < h && d == -1) e = c;b = c + e * d;a.style.opacity = b * .01;a.style.filter = "alpha(opacity=" + b + ")" } else { clearInterval(a.timer);if(d == -1) a.style.display = "none" } }, hide: function(b) { if(b == "fast") { a.style.opacity = 1;a.style.filter = "alpha(opacity=100)";a.style.display = "none" } else { clearInterval(a.timer);a.timer = setInterval(function() { tooltip.fade(-1) }, i);l && this._hideDropDowns(false) } }, _hideDropDowns: function(a) { $("select").css("visibility", a ? "hidden" : "visible") } } } ();
