

















// ==ClosureCompiler==
// @output_file_name default.js
// @compilation_level SIMPLE_OPTIMIZATIONS
// ==/ClosureCompiler==

/*
* Code initialisation based here
* Currently includes:
* clear-inputs.js
* validate.js
* choose-locale.js
* console.js
* see-and-do.js
* set-heights.js
* vertical-ticker.js
*
* Code minified using
* http://closure-compiler.appspot.com/home
*/

(function($) { 
$.ti = $.prototype = {
    
    requiredPlugins: {
        tiTicker: true
    },
    
    ie6: false,
    
    initCommon: function() {
        // Check for ie6
        $.ti.check.ie6();

        // Clear inputs
        $("form").tiClearInputs();
        
        // Header flash linked carousel
        if($('#seeAndDo').length > 0) {
            $.ti.seeAndDo.init();   
        }        
        
        // Select Locale drop down
        $.ti.chooseLocale.init();
        
        // Set homepage teaser module heights to be the same
        $.ti.heights.set('.columns', '.height-controller' );
        $.ti.heights.set('.row', '.height-controller');
        
        // Plan visit
        var tiAccordion = $('#planVisit');
        if(tiAccordion.length) {
            $(tiAccordion).accordion({                
                header: 'h3',
                animated: 'bounceslide'
            }).bind('accordionchangestart', function(event, ui) {                
                $('.ui-icon', ui.newHeader).fadeOut(500);
                $('.ui-icon', ui.oldHeader).fadeIn(500);                
            });
           $("li:first > h3 > .ui-icon", tiAccordion).fadeOut();
           $.ti.heights.tweakPromos();
        }
        
	
	
        // Hot offers - vertical ticker
        if($.ti.requiredPlugins.tiTicker) {
            var newsTicker = $('#verticalTicker');
            if(newsTicker.length) {
		    
                newsTicker.tiTicker();         
            }
        }
        
        // E-zine form validation
        $('#eZineSignUp').click(function(event){
			event.preventDefault();
			$.ti.validate.check('#getEzine', {
                rules: {
                    title: {
                        'cannotBe'  : ["UNKNOWN", "Kies een aanspreektitel "]
                    },
					first_name: {
						'required'	: "Voornaam is verplicht"						
					},
                    last_name: {
                        'required'	: "Achternaam is verplicht"
                    },
                    email: {
                        'required'  : "Een e-mail adres is verplicht",
                        'email'     : "Dit e-mail adres is niet geldig"
                    },
                    confirm_email: {
                        'required'  : "Bevestig uw e-mail adres",
                        'matchVal'	: ['#email', "De bevestiging van het e-mail adres moet overeenstemmen"]
                    }
                },
                
                errorTarget: "#submitEZine",
                showAll: false,
                success: $.ti.submitForm,
                failure: $.ti.formFail
            });
        });
        
    $.ti.offersMoreContent.init();
	$.ti.brochures.init();
    $.ti.silver.init();
    //$.ti.goVideoPopup.init();
	$.ti.videoOverlay.init('.modal');
	$.ti.carousel.init();
	$.ti.sidebarCollapsible.init();
	$.ti.sortBy.init();
    },
    
    submitForm: function(theForm) {
        theForm.submit();
    },
    
    formFail: function(theForm) {
        // do nothing at this point
    }
};

$.ti.sortBy = {
	init: function() {
		$('#sort-preference').change(function(){
				$('#sort-offers').submit();
		}).parent().find('button').hide();
	}
};

$.ti.sidebarCollapsible = {
	init: function() {
		// Offers sidebar accordion
		var tiCollapsible = $('.sidebar-collapsible');
		if(tiCollapsible.length) {
			$('li.open .ui-icon',tiCollapsible).animate({'opacity':'toggle'},0);
			$('li:not(.open) div',tiCollapsible).css('display','none');
			tiCollapsible.each(function(){
				 $('li', this).each(function(){
					 var block = this;
					$('h3',block).click(function(){
						$(block).toggleClass('open');
						$('.ui-icon',block).animate({opacity: 'toggle'}, 'slow');
						$('div',block).slideToggle('slow');
					});
				 });
		    });
		}
	}
};

$.ti.carousel = {
	init: function() {
		if($().jFlow) {
			$("#similar-offers-pages").jFlow({
			    slides: "#similar-offers-slides",
			    width: "506px",
			    height: "100px",
			    duration: 400
			});
		}
	}
};

$.ti.offersMoreContent  = {
	init: function() {   
		
		$('.travel-offers-more-content').hide();
	    
		$('.travel-offers-more-link a').click(function() {
		    $(this).toggleClass('active').blur().parents('.travel-offers-offer').next().slideToggle('slow');
		    return false;
		});
		
		$('.travel-offers-more-link a:first').click();	
	}
};

$.ti.brochures = {
	init: function() { 
		if ($.fancybox) {
			$('.s-ireland-plan-your-visit .modal-pdf').fancybox({
				speedIn: 700,
				speedOut: 400,
				scrolling: 'no',
				autoScale:false,
				onComplete:function(){
					
					$('#download_dialog').hide();
					$.fancybox.resize();
					//feedback_form2($.urlParam(this.ajax.url, 'brochureurl'), $.urlParam(this.ajax.url, 'title'));
					$.ti.brochures.formReplacements($.ti.brochures.urlParam(this.ajax.url, 'brochureurl'), $.ti.brochures.urlParam(this.ajax.url, 'title'));
					$('#vl.download').click(function(){
						
						$.fancybox.close();
						//feedback_form(); 
						webtrends_hack_bronchure('downloadable_EBrochures',this,'downloadablebrochures',this.href+this.title);
						
					});
					$('#download.download').click(function(){
						$.fancybox.close();
						//download_dialog();
						webtrends_hack_bronchure('downloadable_EBrochures',this,'downloadablebrochures',this.href+this.title);
					});
					$('#getEzine-brochure').submit(function() {						
						$.ajax({  
							type: "POST",  
							url: "/nl/forms/newezine",  
							data: $(this).serialize(),  
							success: function() {  
								$('#feedback_form').hide();
								$('#download_dialog').fadeIn(2000);
								$.fancybox.resize();
							}  
						}); 
						return false;
					});					
					// E-zine form validation
					$('#eZineSignUp-brochure').click(function(event){
						event.preventDefault();
						$.ti.validate.check('#getEzine-brochure', {
							rules: {
								'title-brochure': {
									'cannotBe'  : ["UNKNOWN", "Kies een aanspreektitel "]
								},
								'first_name-brochure': {
									'required'	: "Voornaam is verplicht"						
								},
								'last_name-brochure': {
									'required'	: "Achternaam is verplicht"
								},
								'email-brochure': {
									'required'  : "Een e-mail adres is verplicht",
									'email'     : "Dit e-mail adres is niet geldig"
								},
								'confirm_email-brochure': {
									'required'  : "Bevestig uw e-mail adres",
									'matchVal'	: ['#email-brochure', "De bevestiging van het e-mail adres moet overeenstemmen"]
								}
							},
						
							errorTarget: "#submitEZine-brochure",
							showAll: false,
							success: function(){
								$('#getEzine-brochure').submit(); 
							},
							failure: function(){
								$.fancybox.resize();
								$.ti.formFail();
							}
						});
					});
					
		
				}
			});
		}
	},
	formReplacements: function(link, title) {
		$('#vlDoc').attr('value',  link + '\t' + title);
		$('#confirmation').attr('value',  link);
		$('#vl').attr('href',  link);
		$('#vl').attr('title',  $.ti.brochures.URLDecode(title));
		$('#download').attr('href',  link);
		$('#download').attr('title',  $.ti.brochures.URLDecode(title));
		return false;
	},
	urlParam: function(url, param){
		var results = new RegExp('[\\?&]' + param + '=([^&#]*)').exec(url);
		if (!results) { return 0; }
		return results[1] || 0;
	},
	URLDecode:function(s){
	    var o=s;
	    var binVal,t;
	    var r=/(%[^%]{2})/;
	    while((m=r.exec(o))!=null && m.length>1 && m[1]!=''){
		b=parseInt(m[1].substr(1),16);
		t=String.fromCharCode(b);o=o.replace(m[1],t);
	    }return o;
	}
};

$.ti.silver = {
	init: function() { 
		if ($.fancybox) {
			$('.has_fancybox .modal-pdf').fancybox({
				speedIn: 700,
				speedOut: 400,
				titleShow:false,
				scrolling: 'no',
				autoScale:false,
                onClosed: function(){dcsMultiTrack('DCS.dcsuri', window.location.pathname +'form/Silver Surfers Brochure Request Form/Close','WT.ti','Silver Surfers Brochure Request Form - Close')},
				onComplete:function(){
                	//$('#fancybox-close').attr('onclick', "dcsMultiTrack('DCS.dcsuri','/nl/snippets/Brandify/ti-brandify-min/form/Silver Surfers Brochure Request Form/Close','WT.ti','Silver Surfers Brochure Request Form - Close');");
                  					
					$('#download_dialog').hide();
					$.fancybox.resize();
					//feedback_form2($.urlParam(this.ajax.url, 'brochureurl'), $.urlParam(this.ajax.url, 'title'));
					$.ti.brochures.formReplacements($.ti.brochures.urlParam(this.ajax.url, 'brochureurl'), $.ti.brochures.urlParam(this.ajax.url, 'title'));
					$('#vl.download').click(function(){						
						$.fancybox.close();
						//feedback_form(); 
						//webtrends_hack_bronchure('downloadable_EBrochures',this,'downloadablebrochures',this.href+this.title);						
					});
					$('#download.download').click(function(){
						$.fancybox.close();
						//download_dialog();
						//webtrends_hack_bronchure('downloadable_EBrochures',this,'downloadablebrochures',this.href+this.title);
					});
					$('#getEzine-brochure').submit(function() {						
						$.ajax({  
							type: "POST",  
							url: "/nl/forms/newezine",  
							data: $(this).serialize(),  
							success: function() {  
								$('#feedback_form').hide();
								$('#download_dialog').fadeIn(2000);
								$.fancybox.resize();
							}  
						}); 
						return false;
					});					
					// E-zine form validation
					$('#eZineSignUp-brochure').click(function(event){
						event.preventDefault();
						$.ti.validate.check('#getEzine-brochure', {
							rules: {
								'title-brochure': {
									'cannotBe'  : ["UNKNOWN", "Kies een aanspreektitel "]
								},
								'first_name-brochure': {
									'required'	: "Voornaam is verplicht"						
								},
								'last_name-brochure': {
									'required'	: "Achternaam is verplicht"
								},
								'email-brochure': {
									'required'  : "Een e-mail adres is verplicht",
									'email'     : "Dit e-mail adres is niet geldig"
								},
								'confirm_email-brochure': {
									'required'  : "Bevestig uw e-mail adres",
									'matchVal'	: ['#email-brochure', "De bevestiging van het e-mail adres moet overeenstemmen"]
								},
								'age_group': {
									'checked'	: [true, "???kainos.silversurferagegroup.required???"]
								}
							},
							errorTarget: "#submitEZine-brochure",
							showAll: false,
							success: function(){
                            	dcsMultiTrack('DCS.dcsuri','/nl/snippets/Brandify/ti-brandify-min/form/Silver Surfers Brochure Request/Submit','WT.ti','Silver Surfers Brochure Request - Submit','WT.si_n','Silver Surfers Brochure Request','WT.si_x','8');                                
								$('#getEzine-brochure').submit(); 
							},
							failure: function(){
								$.fancybox.resize();
								$.ti.formFail();
							}
						});
					});
					
		
				}
			});
		}
	},
	formReplacements: function(link, title) {
		$('#vlDoc').attr('value',  link + '\t' + title);
		$('#confirmation').attr('value',  link);
		$('#vl').attr('href',  link);
		$('#vl').attr('title',  $.ti.brochures.URLDecode(title));
		$('#download').attr('href',  link);
		$('#download').attr('title',  $.ti.brochures.URLDecode(title));
		return false;
	},
	urlParam: function(url, param){
		var results = new RegExp('[\\?&]' + param + '=([^&#]*)').exec(url);
		if (!results) { return 0; }
		return results[1] || 0;
	},
	URLDecode:function(s){
	    var o=s;
	    var binVal,t;
	    var r=/(%[^%]{2})/;
	    while((m=r.exec(o))!=null && m.length>1 && m[1]!=''){
		b=parseInt(m[1].substr(1),16);
		t=String.fromCharCode(b);o=o.replace(m[1],t);
	    }return o;
	}
};

$.ti.videoOverlay = {
    init: function(target) {
        
        $(target).each(function() {            
            $(this).bind('click.showVideo', function(event){
                var url;
                
                event.preventDefault();
                url = $(this).attr('href');                
                url = $.ti.videoOverlay.updateUrl(url);                
                $.ti.videoOverlay.launch(url);
            });
        });
        $('#autoOpen').click();       
    },
    
    // Add cache busting random number string query to url
    cacheBustUrl: function(url) {
        var random = '&' + Math.floor(Math.random() * 10001);
        url += random;
         
        return url;  
    },
    
    // convert /video/ to /video-inner/
    updateUrl: function(url) {
        return url.replace(/\/video\//, '/video-inner/');
    },
    
    launch: function(url) {        
        url = $.ti.videoOverlay.cacheBustUrl(url);
        url = $.ti.videoOverlay.updateUrl(url);
        
        $.get(url, function(data){
            $.ti.popup.init({
                "content": data,
                "width": "808px",
                "callback": $.ti.videoOverlay.nextVideo
            });
        });
    },
    
    nextVideo: function() {
        $('.replace-video-popup', '#swapable').bind('click.showNextVideo', function(event) {
            var url;
            
            event.preventDefault();
            url = $.ti.videoOverlay.cacheBustUrl($(this).attr('href'));
            url = $.ti.videoOverlay.updateUrl(url);
            
            $.get(url, function(data){                
                $('#swapable').empty().append(data);
                $.ti.videoOverlay.nextVideo();                
            });            
        });
    }
    
};

$.ti.check = $.prototype = {
    ie6: function() {
        if($.browser.msie) {
            var version = parseInt($.browser.version, 10);
            if(version === 6) {
                $.ti.ie6 = true;
            }
        }
    }
};

$.fn.tiClearInputs = function(options) {
    
    var defaults = {
	};
	
	options = $.extend(defaults, options);
	
	return this.each(function() {
		$(':input', this).each(function() {			
			// Not sure about this implemenetation - needs some proper CSS testing!
			// If viable could expand to all inputs actually
			if(this.type === "password") {				
				var overlayLabel = $(this).siblings('label[class=passwordOverlay]');
				$(overlayLabel).click(function(){						
						$(this).css({'left' : '-9999em'});
					});
				$(this).blur(function(){
						if(this.value === '') {
							$(overlayLabel).css({'left' : ''});
						}
					});						
			} else if(this.type === "text" || this.type === "textarea") {
				$(this).blur(function() {
					if(this.value === '') {
						this.value = this.defaultValue;
					}
				});
			}
		});
    });
};

$.ti.heights = $.prototype = {
    set: function(container, element) {
        
        $(container).each(function(){
            // Get greatest height
		var maxHeight = 0;
            $(element, this).each(function(){          
                var elementHeight = $(this).height();                
                if(elementHeight > maxHeight) {
                    maxHeight = elementHeight;                    
                }
            });
            
            // Set all to that height
            $(element, this).each(function(){                
                $(this).height(maxHeight);                
            });
        });
    },
    
    // Non generic function for the 3 promos
    // Some silly and convoluted height control attempts go on here - if the markup for these modules change - undoubtedly this module will need to!
    tweakPromos: function() {
        var heights = {
            contentPadding: (parseInt($('.content', '#plan-visit').css('paddingTop'), 10) +1),
            planVisit: $('#plan-visit').height(),
            planVisitList: $('#planVisit').height(),
            planVisitLink: $('ul.big-calls-to-action', '#plan-visit').height(),
            planVisitIntro: ($('h2', '#plan-visit').height() + $('p', '#plan-visit').height()),
            exploreLink: $('ul.big-calls-to-action', '#explore').height(),
            hotOffers: $('#hotOffers').height(),
            hotOffersLink: $('ul.big-calls-to-action', '#hotOffers').height(),
            hotOffersIntro: ($('h2', '#hotOffers').height() + $('p', '#hotOffers').height()),
            linkDifference: 0,
            introDifference: 0,
            paraPadding: parseInt($('p', '#plan-visit').css("paddingBottom"), 10)
        };
        
        if(heights.planVisitLink > heights.hotOffersLink) {
            heights.linkDifference = (heights.planVisitLink - heights.hotOffersLink);
        }
        
        if(heights.planVisitIntro > heights.hotOffersIntro) {
            heights.introDifference = ((heights.planVisitIntro - heights.hotOffersIntro) + (heights.paraPadding -1));
            $('p', '#hotOffers').css('paddingBottom', heights.introDifference +'px');
        }
        
        $('#verticalTicker').height(heights.planVisitList + heights.linkDifference);        
        $('.content', '#explore').height((heights.planVisit - heights.exploreLink) - heights.contentPadding);

    }
};

$.ti.seeAndDo = $.prototype = {
    
    controls: {
        lock: false,
        clicked: false,
        activeItem: 1,
        itemCount: 0
    },            
    
    imageCache: [],
    
    options: {
        fadeTime: 2000,
        tagFadeTime: 2000, // same as normal fade time but gets zeroed for IE as it can't handle the gradients
        pauseTime: 8000, // N.B. this includes fadeTime i.e. 2000 + 6000 = 8000
        buttonWidth: 15
    },
    
    init: function() {                
        this.preloadImages();        
        this.createNav();
        if($.browser.msie) {
            $.ti.seeAndDo.options.tagFadeTime = 0;
            if($.ti.ie6 === true) {
                this.swapTag();
            }
        }
    },
    
    // Swap in filter version of tag for IE6
    swapTag: function() {
        var tag, newTag;
        tag = $('img.tag', '#seeAndDo');
        newTag = $('<div class="tag" style="width:67px; height:109px; filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src=' + $.ti.seeAndDo.json.promotions[1].tagPath + ', sizingMethod="crop")"></div>');
        $(tag).remove();
        $('#seeAndDo').append(newTag);
    },
    
    preloadImages: function() {
        for(var promotion in $.ti.seeAndDo.json.promotions){
            if($.ti.seeAndDo.json.promotions.hasOwnProperty(promotion)) {                
                var image = document.createElement('img');
                image.src = $.ti.seeAndDo.json.promotions[promotion].imagePath;
                this.imageCache.push(image);
                $.ti.seeAndDo.controls.itemCount++;
            }            
        }
    },
    
     createNav: function() {
        var navList, listItem;
        navList = $('#seeAndDoNav');
        for(var promotion in $.ti.seeAndDo.json.promotions){
            if($.ti.seeAndDo.json.promotions.hasOwnProperty(promotion)) {
                if($.ti.ie6 === true) {
                    listItem = $('<li><img src="/shared/resource/images/brandify/buttons/promo-radios-8b.png" width="24" height="11" alt="' + promotion + '" /></li>');
                } else {
                    listItem = $('<li><img src="/shared/resource/images/brandify/buttons/promo-radios.png" width="24" height="11" alt="' + promotion + '" /></li>');
                }                
                if(promotion != this.controls.activeItem) {
                    $('img', listItem).bind('click.change', function(event){
                        if($.ti.seeAndDo.controls.lock == false){
                            $.ti.seeAndDo.tellFlash('quit');
                            $.ti.seeAndDo.controls.clicked = true;
                            $.ti.seeAndDo.replaceContent($(this).attr('alt'), true);

                        }
                    }); 
                } else {
                    $(listItem).addClass('active');
                }                
                $(navList).width(promotion*this.options.buttonWidth + 'px').append(listItem);
            }
        }        
    },
    
    replaceContent: function(target, skipFade) {
	$.ti.seeAndDo.controls.lock = true;
        var markup = {
            cssObjectOld: {
                'z-index'   : '100'
            },
            cssObjectNew: {
                'z-index'   : '100',
                'display'    : 'none'
            },
            heading:    $('<h2>' + $.ti.seeAndDo.json.promotions[target].heading + '</h2>'),
            link:       $('<ul class="calls-to-action"><li><a href="' + $.ti.seeAndDo.json.promotions[target].url + '" title="">' + $.ti.seeAndDo.json.promotions[target].urlText + '</a></li></ul>'),
            image:      $('<img src="' + $.ti.seeAndDo.json.promotions[target].imagePath +'" alt="" width="240" height="105" />'),
            text:       $('<p>' + $.ti.seeAndDo.json.promotions[target].text + '</p>')
        };
        
        if($.ti.seeAndDo.json.promotions[target].external) {
            markup.link = markup.link.click(function(e) { e.preventDefault(); window.open($.ti.seeAndDo.json.promotions[target].url);});
        }
        
        // Get each swappable within a .wrapper
        $('.wrapper', '#seeAndDo').each(function(){
	    var child, functionHolder;
            child = $(this).find(":first");            
            child.css(markup.cssObjectOld);
	    skipFade ? functionHolder = swapInOut:functionHolder = fadeInOut;
            switch(child[0].tagName.toLowerCase()) {
                case 'h2':  functionHolder(markup.heading, child[0], this);
                            break;
                case 'ul':  functionHolder(markup.link, child[0], this);
                            break;
                case 'p':   functionHolder(markup.text, child[0], this);                            
                            break;
                case 'img': functionHolder(markup.image, child[0], this);                            
                            break;
            }
            $.ti.seeAndDo.setActiveItem(target);
        });
        
        // Swap tag
        var oldTag = $('.tag', '#seeAndDo');
        if($.ti.seeAndDo.json.promotions[target].tagPath) {
            if($.ti.ie6) {
                var newTag = $('<div class="tag" style="width:67px; height:109px; filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src=' + $.ti.seeAndDo.json.promotions[target].tagPath + ', sizingMethod="crop")"></div>');
            } else {
                var newTag = $('<img class="tag" alt="' + $.ti.seeAndDo.json.promotions[target].tagAlt + '" width="67" height="109" src="' + $.ti.seeAndDo.json.promotions[target].tagPath + '" style="z-index:490; display:none;" />');               
            }            
            $('#seeAndDo').append(newTag);
            newTag.fadeIn($.ti.seeAndDo.options.tagFadeTime, function() {
                $(this).css('z-index', '500');
            });            
        }
        if(oldTag.length) {
            oldTag.fadeOut($.ti.seeAndDo.options.tagFadeTime, function() {             
                $(this).remove();                 
            });   
        } else {            
            setTimeout('jQuery.ti.seeAndDo.controls.lock = false', $.ti.seeAndDo.options.fadeTime);
        }
        
        function fadeInOut(newObject, oldObject, parent) {            
            $(newObject).css(markup.cssObjectNew);
            $(parent).append(newObject);
            $(newObject).fadeIn($.ti.seeAndDo.options.fadeTime);
            $(oldObject).fadeOut($.ti.seeAndDo.options.fadeTime, function() {                    
                $(this).remove();
                $.ti.seeAndDo.controls.lock = false;	
            });                 
        }
	
	function swapInOut(newObject, oldObject, parent) {            
            $(newObject).css(markup.cssObjectNew);
            $(parent).append(newObject);
            $(newObject).css('display', 'block');
            $(oldObject).remove();
            $.ti.seeAndDo.controls.lock = false;	               
        }
    },
    
    setActiveItem: function(index) {        
        var buttons = $('li', '#seeAndDoNav');
        $(buttons[$.ti.seeAndDo.controls.activeItem-1]).removeClass('active');
        $('img', buttons[$.ti.seeAndDo.controls.activeItem-1]).bind('click.change', function(){
            if($.ti.seeAndDo.controls.lock == false){
                $.ti.seeAndDo.controls.lock = true;
                $.ti.seeAndDo.tellFlash('quit');
                $.ti.seeAndDo.controls.clicked = true;		
                $.ti.seeAndDo.replaceContent($(this).attr('alt'), true);                            
            }   
        });        
        $.ti.seeAndDo.controls.activeItem = index;
        $(buttons[index-1]).addClass('active');
        $('img', buttons[index-1]).unbind('click.change');
    },
    
    // Pass instruction to Flash movie
    tellFlash: function(instruction) {    
        if (swfobject.getFlashPlayerVersion().major > 0){       
       		document.getElementById('flashHeader').passToFlash(instruction);
		}           
    },
    
    // Performs two itterations of the panel then restarts the Flash movie.
    automate: function(last) {
        if(!$.ti.seeAndDo.controls.clicked) {
            var controls = {
                target: null,
                pause: null
            };
            
            $.ti.seeAndDo.controls.activeItem < $.ti.seeAndDo.controls.itemCount ? controls.target = ($.ti.seeAndDo.controls.activeItem + 1) : controls.target = 1;
	    $.ti.seeAndDo.replaceContent(controls.target, false);
            if(!last) {                
                controls.pause = setTimeout('jQuery.ti.seeAndDo.automate(true)', jQuery.ti.seeAndDo.options.pauseTime);
            } else {
                controls.pause = setTimeout('jQuery.ti.seeAndDo.tellFlash("continue")', jQuery.ti.seeAndDo.options.fadeTime);                
            }
        }
    }
};

$.ti.chooseLocale = $.prototype = {
    
    settings: {        
        countries: {},
        locale: 'int',
        location: {
            name: '',
            position: 0
        },           
        flagHeight: 11,
        languages: {},
        language: {
            name: '',
            position: 0
        },
        languageDropDown: null
    },                
    
    init: function() {
        this.getLocale();
        this.getOptions('#location option', $.ti.chooseLocale.settings.countries, $.ti.chooseLocale.settings.location);        
        if($('#language').length > 0) {            
            this.getOptions('#language option', $.ti.chooseLocale.settings.languages, $.ti.chooseLocale.settings.language);
            this.createLanguage();         
        }
        this.createList();
    },
    
    getOptions: function(target, listStorage, settingStorage) {
        $(target).each(function(index){
            listStorage[$(this).text()] = $(this).val();
            if($(this).attr('selected')) {
                settingStorage.position = index;
                settingStorage.name = $(this).text();
            }
        });
    },
    
    // ToDo: duplicates functionality in panel.js - move to utils.js when consolidatiing?
    getLocale: function() {
        var locale =  document.location.pathname.split('/');
        this.settings.locale = locale[1];        
    },
    
    createLanguage: function() {
        var html = {
            div: $('<div id="selectLanguage"><a class="select-language" title="" href="#">' + this.settings.language.name + '</a></div>'),
            ul: $('<ul class="language-drop-down" id="languageDropDown"></ul>'),
            link: $(),
            ulWrapper: $('<div class="drop-down-wrapper"><span class="drop-down-pointer"></span><div class="shadow"></div></div>')            
        };
        
        $.each(this.settings.languages, function(language, url){            
            html.li = $('<li><a href="' + url + '" title="">' + language +'</a></li>');
            html.ul.append(html.li);
            $('.shadow', html.ulWrapper).append(html.ul);
        });
        
        // Set focus or click events
        $('a.select-language', html.div).focus(function() {
            $(html.div).append(html.ulWrapper);            
        }).click(function(event) {
            event.preventDefault();
            event.stopPropagation();
            if($('#countryDropDown').length > 0) {
                $('.drop-down-wrapper','#selectLocale').remove();
                $('body').unbind('click.closeDropDown');
            }
            $(html.div).append(html.ulWrapper);
            $('body').bind('click.closeDropDown', function(){
                                                        html.ulWrapper.remove();
                                                        $('body').unbind('click.closeDropDown');
                                                    });
        });
        
        $('a').focus(function(event){            
            html.ulWrapper.remove();                
        });
        
        this.settings.languageDropDown = html.div;
    },
    
    createList: function() {
        var html = {
            div: $('<div id="selectLocale"></div>'),
            link: $('<a class="select-locale" title="" href="#"><span class="flag" style="background-position:0px -' + this.settings.location.position * this.settings.flagHeight + 'px;"></span>' + this.settings.location.name + '</a>'),
            ulWrapper: $('<div class="drop-down-wrapper"><span class="drop-down-pointer"></span><div class="shadow"></div></div>'),
            ul: $('<ul class="country-drop-down" id="countryDropDown"></ul>'),            
            flagCount: 0,
            position: 0
        };
        
       $.each(this.settings.countries, function(country, newUrl){
            html.position = ($.ti.chooseLocale.settings.flagHeight * html.flagCount);            
            html.li = $('<li><a href="' + newUrl + '" title=""><span class="flag" style="background-position:0px -' + html.position + 'px;"></span>' + country + '</a></li>');                    
            html.ul.append(html.li);
            $('.shadow', html.ulWrapper).append(html.ul);
            html.flagCount++;
        });
        
        html.div.append(html.link);
        
        // Set focus or click events
        $('a.select-locale', html.div).focus(function() {
            $(html.div).append(html.ulWrapper);            
        }).click(function(event) {
            event.preventDefault();
            event.stopPropagation();
            if($('#languageDropDown').length > 0) {
                $('.drop-down-wrapper','#selectLanguage').remove();
                $('body').unbind('click.closeDropDown');
            }
            $(html.div).append(html.ulWrapper);
            $('body').bind('click.closeDropDown', function(){
                                                        html.ulWrapper.remove();
                                                        $('body').unbind('click.closeDropDown');
                                                    });
        });
        
        
        // If link outside drop down gets focus from the keyboard remove
        $('a').focus(function(event){            
                html.ulWrapper.remove();
                if($('#languageDropDown').length > 0) {
                     $('.drop-down-wrapper','#selectLanguage').remove();
                }
        });
        
       
        $('#selectLocale').remove();
        if(this.settings.languageDropDown != null) {
            $('#topLinks').append(this.settings.languageDropDown);
        }
        $('#topLinks').append(html.div);
    }
};

$.fn.tiTicker = function(options) {
	var defaults = {
		speed: 500, /* Original default is 1500 - speeded up for testing */
		pause: 5000, /* Original default is 5000 - speeded up for testing */
		mousePause: true
	};

	options = $.extend(defaults, options);
	
	moveUp = function(container, stopPoint){
		if(options.mousePause) {
			height = container.children('ul').children('li:first').height();
			first = container.children('ul').children('li:first').clone(true);
			container.children('ul')
			.animate({top: '-=' + height + 'px'}, options.speed, function() {
				$(this).children('li:first').remove();
				$(this).css('top', stopPoint);
			});
			first.appendTo(container.children('ul'));
		}
	};
	
	return this.each(function() {
		container = $(this);
		list = $(container).children('ul');
		listItems = $(list).children('li');
		
		// Pause the scroller if mouse hovered...
		if(options.mousePause) {
				container.hover(
					function() {
						options.mousePause = false;
					},
					function() {
						options.mousePause = true;
					}
				);
			}

		// Get padding and margins from list items - assuming they are all the same here so we don't have to check each one inside the each() below.
		// Getting values individually to play nice with all browsers.
		liPadTop = $(listItems[0]).css('padding-top');
		liPadRight = $(listItems[0]).css('padding-right');
		liPadBot = $(listItems[0]).css('padding-bottom');			
		liPadLeft = $(listItems[0]).css('padding-left');
		liMargTop = $(listItems[0]).css('margin-top');
		liMargRight = $(listItems[0]).css('margin-right');
		liMargBot = $(listItems[0]).css('margin-bottom');
		liMargLeft = $(listItems[0]).css('margin-left');
		liFloat = $(listItems[0]).css('float');

		// Zero margins and paddings on the list items then replicate those + the float for a div inserted inside - thus preserving layout
		$(listItems).each(function() {
			var liDiv = $('<div style="float:' + liFloat + '; padding:' + liPadTop + ' ' + liPadRight + ' ' + liPadBot + ' ' + liPadLeft + '; margin:' + liMargTop + ' ' + liMargRight + ' ' + liMargBot + ' ' + liMargLeft + ';" </div>');
			$(this).css({margin: 0, padding: 0});
			$(this).children().wrapAll(liDiv);
		});
		
		// Set up container and list styles
		container.css({overflow: 'hidden', position: 'relative'});
		list.css({position: 'absolute', margin: 0, padding: 0});
		
		// Does the container have top padding? If so use that as the "stop point"
		stopPoint = container.css('padding-top');
			
    	interval = setInterval('moveUp(container, stopPoint)', options.pause);
	});
};

$.ti.validate = {
        
        // Check required fields, cannot be empty, cannot be default value
        required: function(formElement, rule) {
            var value = $('#' + formElement).val();
            if(value === '' || value === document.getElementById(formElement).defaultValue) {                
                this.insertMessage(formElement, rule);    
            }
        },
        
        // Check is valid email address
        email: function(formElement, rule) {
            var value = $('#' + formElement).val();            
            if(!value.match(/^[a-zA-Z0-9_\-\.]+\@(([\[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/)) {
                this.insertMessage(formElement, rule);                
            }
        },
        
        // Check length of input value
        minLength: function(formElement, rule) {
            if($('#' + formElement).val().length < rule[0]) {
                this.insertMessage(formElement, rule[1]);               
            }  
        },
        
        // Check that the value matches that of another for element i.e. compare two email or password fields
        matchVal: function(formElement, rule) {
            if($('#' + formElement).val() !== $(rule[0]).val()) {
                this.insertMessage(formElement, rule[1]);
            }
        },
        
        // Ensure that a particular exact value is not matched
        cannotBe: function(formElement, rule) {         
            if($('#' + formElement).val() === rule[0]) {
                this.insertMessage(formElement, rule[1]);                
            }
        },
        
        // Ensure that a checkbox is ticked
        checked: function(formElement, rule) {          
            if($('#' + formElement).attr('checked') == false) {
                this.insertMessage(formElement, rule[1]);                
            }
        },
        
        // Ensure that something has been entered - fails on white space or numbers only
        hasText: function(formElement, rule) {
            var value = $('#' + formElement).val();            
            if(!value.match(/[^\d\s]/)) {
                this.insertMessage(formElement, rule);                
            }  
        },
        
        // Append error message
        insertMessage: function(formElement, message) {
            var errorLabel = $('<label for="' + formElement +'" class="error">' + message + '</label>').hide();
            
            // Set form as not valid
            this.checks.valid = false;
            
            // Set has already thrown an error for this form element
            this.options.rules[formElement].hasError = true;
                
            if(!this.options.errorTarget){
                $('#' + formElement).before(errorLabel);   
            } else {
                if(this.checks.shown === 0) {
                    $(this.options.errorTarget).append(errorLabel);
                    if(!this.options.showAll) {
                        this.checks.shown = 1;    
                    }                    
                }
            }  
            errorLabel.fadeIn(500);
        },
        
        options: {
            errorTarget: false, // If false inserted before input
            showAll: true,  // If set to false only the first error message encountered will display
            success: false,
            failure: false
        },
        
        checks: {
            valid: true,
            shown: 0
        },
        
        check: function(form, settings) { 
            // Reset checks
            this.checks.valid = true;
            this.checks.shown = 0;
            
            // update options with settings
            $.extend(this.options, settings);
            // Clear any existing errors
            $('label.error', form).remove();
            
            // Get each form element that has a rule
            for(var formElement in this.options.rules){
                if(this.options.rules.hasOwnProperty(formElement)) {
                     // Get each rule for the form element
                    for(var rule in this.options.rules[formElement]) {
                        if(this.options.rules[formElement].hasOwnProperty(rule)) {
                            //$.ti.console.log(rule);
                            // Check that a rule has not already been broken before checking that element again
                            if(!this.options.rules[formElement].hasError) {
                                // Run the required check on that element.
                                //$.ti.console.log(this.options.rules[formElement][rule]);
                                //debugger;
                                $.ti.validate[rule](formElement, this.options.rules[formElement][rule]);
                            }
                        }
                    }
                }
            }
         
            // If no errors get thrown run success callback   
            if(this.checks.valid) {            
              this.options.success($(form));   
            } else {
                // or failure callback if one exists
                if(this.options.failure) {
                    this.options.failure($(form)); 
                }
            } 
        }
    };

$.ti.popup = {
	
	options: {
        width: '600px',          // Pixel value width
        zIndex: 9100,            // Overlay z-index - pop up is over this
        opacity: '0.7',          // Overlay opacity
        bgColour: '#5c5c5c',     // Overlay background colour
        vPos: 100,           // Vertical position of popup from top of viewport- Pixel value
        hPos: 'center',          // Horizontal position - pixel value can replace 'center'
        closeButton: ['#close'],   // Array - element(s) to attach close function to
        callback: false,		 // function to call once loaded
		content: false,			 // string: html inside the popup
		insertPoint: '#swapable'  // point at which to insert content
    },
	
	html:   $([ '<div class="popup" id="popUp">',					
                    '<div class="content clearfix">',
						'<span id="close"><img src="/shared/resource/images/itinerary_planner/buttons/popup-close.png" width="33" height="35" alt="close window" /></span>',
						'<div id="swapable">',
						'</div>',
					'</div>',
                '</div>'
            ].join('')),	
	
	overlay: function() {
		var html, docHeight;
		
		html = $('<div id="overlay"></div>');
		docHeight = $(document).height();
		
		// Apply overlay css
		$(html).css({
            'height': docHeight,
            'width': '100%',            
            'z-index': this.options.zIndex,
            'position': 'absolute',
            'top': '0',
            'left': '0',
            'background-color': this.options.bgColour
        });
		
		// Do opacity seperatly to accomodate IE's method
        $(html).fadeTo(0, this.options.opacity);
		
		// Append Overlay
        $(document.body).prepend(html);
	},
	
	init:	function(settings) {				
		this.options.hPos = 'center';
        this.options.vPos = 100;
		
		if (settings) {
			$.extend(this.options, settings);
		}
        
        // Get center position
        if(this.options.hPos === 'center') {            
            this.options.hPos = this.getCenter(this.options.width);            
        }
		
		this.options.vPos = this.getTop(this.options.vPos);		
        
		// Apply popup CSS
		$(this.html).css({
            'z-index': (this.options.zIndex + 10),
            'position': 'absolute',
            'width': this.options.width,
            'top': this.options.vPos,
            'left': this.options.hPos
        });
		
		this.overlay();
		
		$('#overlay').after(this.html);
		
		// Append popup content
		if(this.options.insertPoint) {
			$(this.options.insertPoint, this.html).append(this.options.content);	
		}
	
        $(this.html).tiClearInputs();
		
		this.closeEvents();
				
		if(this.options.callback) {
			this.options.callback();	
		}        

	},
	
    // Returns a distance in pixels from the left to center the popup
	getCenter: function(popUpWidth) {
		return Math.round(($(document).width() - parseInt(popUpWidth, 10)) /2);
	},
    
    // Returns the scroll position of the viewport + the height set in options
    getTop: function(top) {
        return ($(window).scrollTop() + top);        
    },
	
	// Attach close event to all close buttons
	closeEvents: function() {
		var count, length;
		
		length = this.options.closeButton.length;
		
		for(count = 0; count < length; count += 1) {
			
			$(this.options.closeButton[count]).unbind('click.close');
			$(this.options.closeButton[count]).bind('click.close', function(){				
				$.ti.popup.close();
			});
		}
	},
    
	swapContent: function(content, newWidth, callback) {
		var leftPos = $.ti.popup.getCenter(newWidth);		
		$('#swapable').height($('#swapable').height());
		$('#popUp').animate({
			"width": newWidth,
			"left": leftPos
		}, 500); 
        
        
		$('#swapable').fadeTo(500, 0, function(){
		    $(this).empty()
			       .append(content);
		    callback();
		    $(this).animate({
			     "height": $('#swapableContent').height()											 
		     }, 500, function(){
				     $('#swapable').fadeTo(500, 1, function(){
												     $('#swapable').css({height: 'auto'
												     });
											     });
				     }
		     );
		    }
		);
		$(content).tiClearInputs();       
	},
	

	close: function() {		
		$('#popUp').fadeOut('500', function(){
			$('#swapable').css({
				height: 'auto'				
			}).empty();			
			$('#popUp').remove().fadeIn();			
		});              
        $('#overlay').fadeOut('500', function(){$('#overlay').remove().show();});
	}
};

$.ti.console = $.prototype = {
    log: function(message){
            if(window.console) {
                console.log(message);
            }            
    }
};

$(document).ready(function(){
    $.ti.initCommon();    
});

})(jQuery);
