var popUpsAreGo = false;

search_input_form = {
	toggleRooms : function(caller, label, divClass, direction) {
		search_input_form.callingDiv = $(caller).parents('div.' + divClass );

		search_input_form.desiredNumberOfRooms = $(caller).attr('value');
		search_input_form.actualNumberOfRooms = $(search_input_form.callingDiv).find('table.bookingPassengers tr.room').size();
		if(search_input_form.desiredNumberOfRooms > search_input_form.actualNumberOfRooms) {
			while ( search_input_form.desiredNumberOfRooms > search_input_form.actualNumberOfRooms ) {
                // Want to ADD a room
                search_input_form.addRoomRow(search_input_form.actualNumberOfRooms, label, direction);
            }
        } else {
			// Want to REMOVE a room
			$(search_input_form.callingDiv).find('table.bookingPassengers:first tr:gt('+search_input_form.desiredNumberOfRooms+')').remove();
		}
	},
	addRoomRow : function(roomNumber, label, direction){
		if(search_input_form.desiredNumberOfRooms > search_input_form.actualNumberOfRooms) {
			// increment nb of rooms since we will add one here
            search_input_form.actualNumberOfRooms = roomNumber + 1;
            // grab the HTML for the added line of the form (synchronously so that we dont get the 4th line before the 3rd one)
            jQuery.ajax({
                 url:    '/add_room_row.action?roomNumber='+ roomNumber + '&direction=' + direction,
                 success: function(newRoomMarkup){
                                // Set the room values
                                $(search_input_form.callingDiv).find('table.bookingPassengers tr.room:last').after(newRoomMarkup);
			              },
                 async:   false
            });
		}
	}
}

billing_information_form = {
	toggleCreditCards : function(caller, label, divClass) {
		billing_information_form.callingDiv = $(caller).parents('div.' + divClass );

		billing_information_form.desiredNumberOfCreditCard = $(caller).attr('value');
		billing_information_form.actualNumberOfCreditCard = $(billing_information_form.callingDiv).find('table.creditCards tr.creditCard').size();

		if(billing_information_form.desiredNumberOfCreditCard > billing_information_form.actualNumberOfCreditCard) {
            while( billing_information_form.desiredNumberOfCreditCard > billing_information_form.actualNumberOfCreditCard ) {
                // Want to ADD a CreditCard form
                billing_information_form.addCreditCardRow(billing_information_form.actualNumberOfCreditCard, label);
            }
        } else {
			// Want to REMOVE a CreditCard form
			$(billing_information_form.callingDiv).find('table.creditCards tr.creditCard:gt('+( billing_information_form.desiredNumberOfCreditCard - 1 )+')').remove();
		}
	},
	addCreditCardRow : function(creditCardNumber, label){
        if(billing_information_form.desiredNumberOfCreditCard > billing_information_form.actualNumberOfCreditCard) {
			// increment nb of credit cards since we will add one here
            billing_information_form.actualNumberOfCreditCard = creditCardNumber + 1;
            // grab the HTML for the added line of the form (synchronously so that we dont get the 4th line before the 3rd one)
            jQuery.ajax({
                 url:    '/add_credit_card_row.action?creditCardNumber=' + creditCardNumber,
                 success: function(newCreditCardMarkup) {
                                // Set the credit card values
                                $(billing_information_form.callingDiv).find('table.creditCards tr.creditCard:last').after(newCreditCardMarkup);
			              },
                 async:   false
            });
		}
	}
}

$(document).ready(
	function() {
		// For CSS sliding doors
		$('div.bigBox, div.smallBox').wrapInner('<div></div>');

        // For CSS buttons
		$('a.redButton, a.greyButton').addClass('button');

		// For CSS sliding doors buttons
		$('a.button').wrapInner('<span><span style="color: white;"></span></span>');

		// For slight overhang of table-header underline
		$('table.flightDetails > thead > tr > th:first-child, table.flightDetails > tbody > tr > td:first-child')
			.css('padding-left', '10px');


		$('table.flightDetails > thead > tr > th:last-child, table.flightDetails > tbody > tr > td:last-child')
			.css('padding-right', '10px');



		// Curved corners on 'div.stopover'
		curveSettings = {
			tl: { radius: 8 },
			tr: { radius: 8 },
			bl: { radius: 8 },
			br: { radius: 8 },
			antiAlias: true,
			autoPad: false
		}

       /* var cornersObj = new curvyCorners(curveSettings, "stopover");
		cornersObj.applyCornersToAll();

        cornersObj = new curvyCorners(curveSettings, "stopover outboundDiv");
		cornersObj.applyCornersToAll();

        cornersObj = new curvyCorners(curveSettings, "stopover inboundDiv");
		cornersObj.applyCornersToAll();*/

        cornersObj = new curvyCorners(curveSettings, "bigRounded");
        cornersObj.applyCornersToAll();

        $('div.bigRounded').wrapInner('<div></div>');


        // Initialize small image browsers
		smallImageBrowser.init();

        $('div.stopover').wrapInner('<div></div>');
        $('div.stopover').wrapInner('<div></div>');

        // 
        popUpsAreGo = true;

        // if there are any forms, set the input focus
        $(".firstInput:first").focus();

    }

);

////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////

function dimStage(showThisAfter) {
    if (popUpsAreGo) {
        backgroundDiv = document.createElement('div');
        $(backgroundDiv).addClass('overlay');
        $(backgroundDiv).css({'height':$(document).height()});
        $('body').append(backgroundDiv);
        $('div.overlay').css('opacity',0);
        $('div.overlay').show();

        // the following line ensures that the div to be displayed is a direct child of the BODY
        $('body').append($('#' + showThisAfter));

        var scrollTop = window.pageYOffset || document.documentElement.scrollTop || 0;
            $('#'+showThisAfter).css({
                'top' : (($(window).height() - $('#'+showThisAfter).height()) / 2) + scrollTop +'px',
                'opacity' : '0',
                'left' : ($(window).width() - $('#'+showThisAfter).width()) / 2 + 'px'
            });


        $('div.overlay').animate({opacity: 0.35}, 300, "", function() {
            $('#'+showThisAfter).css('display', 'block').animate({opacity: 1}, 300, "");
        });
    }
}

function relightStage(removeThisFirst) {
	$('#' + removeThisFirst).animate({opacity: 0}, 300, "", function() {
		$(this).css('display', 'none');
		$('div.overlay').animate({opacity: 0}, 300, "", function() {
			$(this).remove();
		});
	});
}

////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////

var INITIALIZED = false;
imageBrowser = {
	init : function(width){
        imageBrowser.inAnimation = false;
        if (INITIALIZED)
            return;

        imageBrowser.currentItem2 = parseFloat(0);
		imageBrowser.currentItem = parseFloat(0);

        $('div.imageBrowser').each(function(){
            imageBrowser.itemsCount = $(this).find('ul li').size();

            // Set the counter
            $(this).find('span.counter').text('1/' + $(this).find('ul li').length);
            $('div.fullscreenText span.counter').text('1/' + $(this).find('ul li').length);

            if ( width != null )
                imageBrowser.galleryWidth = parseFloat(width);
            else
                imageBrowser.galleryWidth = parseFloat($(this).find('ul li img').width());



            // If there's only one picture, remove the previous/newxt links
            if($('ul li').length == 1){
                $(this).find('span.photoBrowser a.photoArrowLeft').remove();
                $(this).find('span.photoBrowser a.photoArrowRight').remove();
                $(this).find('span.photoBrowser span.fRight').css({'margin-left':5})
            }

            $(this).find('ul li:eq(0)').css({position: 'absolute', left: '0px'});

            $(this).find('ul li:gt(0)').each(function(){
                $(this).css({
                    position : 'absolute',
                    right : imageBrowser.galleryWidth
                });
            });
        });

        INITIALIZED = true;
    },
	previous : function(caller){
        if(!imageBrowser.inAnimation){
            tempItemsValue = $(caller).parent().parent().parent().find('span.counter').text();
			tempCurrentItem = tempItemsValue.substr(0,$(caller).parent().parent().parent().find('span.counter').text().indexOf('/'));
			imageBrowser.currentItem = parseFloat(tempCurrentItem - 1); // -1 is cause arrays always start at 0
			imageBrowser.itemsCount = parseFloat(tempItemsValue.substr($(caller).parent().parent().parent().find('span.counter').text().indexOf('/') + 1,$(caller).parent().parent().parent().find('span.counter').text().length));

            imageBrowser.inAnimation = true;

            $(caller).parent().parent().parent().find('ul li:eq('+imageBrowser.currentItem +')').animate({ 'left': imageBrowser.galleryWidth }, 500 );

            imageBrowser.currentItem = (imageBrowser.currentItem - 1) % imageBrowser.itemsCount;
            if(imageBrowser.currentItem < 0){ imageBrowser.currentItem = imageBrowser.itemsCount - 1; }

            $(caller).parent().parent().parent().find('ul li:eq('+imageBrowser.currentItem+')').css('left',-imageBrowser.galleryWidth);
			$(caller).parent().parent().parent().find('ul li:eq('+imageBrowser.currentItem+')').animate({ 'left': 0 }, 500, function(){ imageBrowser.inAnimation = false; } );

			$(caller).parent().parent().parent().find('span.counter').text(imageBrowser.currentItem + 1 + '/' + $(caller).parent().parent().parent().find('ul li').length);
			imageBrowser.currentItem2 = imageBrowser.currentItem;
			$('div.fullscreenText span.counter').text(imageBrowser.currentItem + 1 + '/' + $(caller).parent().parent().parent().find('ul li').length);

			$("#fullscreenPhoto").width(parseFloat($('#fullPhoto img').width()));

		}
	},
	next : function(caller){
        if(!imageBrowser.inAnimation){
            tempItemsValue = $(caller).parent().parent().parent().find('span.counter').text();
			tempCurrentItem = tempItemsValue.substr(0,$(caller).parent().parent().parent().find('span.counter').text().indexOf('/'));
			imageBrowser.currentItem = parseFloat(tempCurrentItem - 1); // -1 is cause arrays always start at 0
			imageBrowser.itemsCount = parseFloat(tempItemsValue.substr($(caller).parent().parent().parent().find('span.counter').text().indexOf('/') + 1,$(caller).parent().parent().parent().find('span.counter').text().length));

            imageBrowser.inAnimation = true;

			$(caller).parent().parent().parent().find('ul li:eq('+imageBrowser.currentItem +')').animate({ 'left': -imageBrowser.galleryWidth }, 500 );

            imageBrowser.currentItem = ++ imageBrowser.currentItem % imageBrowser.itemsCount;

            $(caller).parent().parent().parent().find('ul li:eq('+imageBrowser.currentItem+')').css('left',imageBrowser.galleryWidth);
			$(caller).parent().parent().parent().find('ul li:eq('+imageBrowser.currentItem+')').animate({ 'left': 0 }, 500, function(){ imageBrowser.inAnimation = false; } );

			$(caller).parent().parent().parent().find('span.counter').text(imageBrowser.currentItem + 1 + '/' + $(caller).parent().parent().parent().find('ul li').length);
			imageBrowser.currentItem2 = imageBrowser.currentItem;
			$('div.fullscreenText span.counter').text(imageBrowser.currentItem + 1 + '/' + $(caller).parent().parent().parent().find('ul li').length);

			$("#fullscreenPhoto").width(parseFloat($('#fullPhoto img').width()));
		}
	},
	nextFull : function(caller){
            imageBrowser.fullscreenCurrentItem = ++ imageBrowser.fullscreenCurrentItem % imageBrowser.itemsCount;

            browserDetailsLocation = $(caller).parent().parent().parent().find('li:eq('+imageBrowser.fullscreenCurrentItem+') div.liFullPhoto');

			$("#fullPhoto").fadeOut('fast',function(){
                $("#fullPhoto").html($(browserDetailsLocation).find('img').clone());

				// Put the title and content
				$('#fullscreenPhoto .fullscreenText p:eq(0)').html('<strong>' + $(browserDetailsLocation).find('span.title').text() + '</strong> ( photo '+ (parseFloat(imageBrowser.fullscreenCurrentItem) + 1) +' of '+ imageBrowser.itemsCount +' )');

                var txtP = $('#fullscreenPhoto .fullscreenText p:eq(1)');
				txtP.text($(browserDetailsLocation).find('span.content').text());

                if (txtP.height() < 30) txtP.height(30);

                $("#fullPhoto").fadeIn('fast');
			});

	},
	previousFull : function(caller){
			imageBrowser.fullscreenCurrentItem = (imageBrowser.fullscreenCurrentItem - 1) % imageBrowser.itemsCount;
			if(imageBrowser.fullscreenCurrentItem < 0){ imageBrowser.fullscreenCurrentItem = imageBrowser.itemsCount - 1; }

			browserDetailsLocation = $(caller).parent().parent().parent().find('li:eq('+imageBrowser.fullscreenCurrentItem+') div.liFullPhoto');

			$("#fullPhoto").fadeOut('fast',function(){
				$("#fullPhoto").html($(browserDetailsLocation).find('img').clone());

				// Put the title and content
				$('#fullscreenPhoto .fullscreenText p:eq(0)').html('<strong>' + $(browserDetailsLocation).find('span.title').text() + '</strong> ( photo '+ (parseFloat(imageBrowser.fullscreenCurrentItem) + 1) +' of '+ imageBrowser.itemsCount +' )');
				var txtP = $('#fullscreenPhoto .fullscreenText p:eq(1)');
				txtP.text($(browserDetailsLocation).find('span.content').text());
				if (txtP.height() < 30) txtP.height(30);

				$("#fullPhoto").fadeIn('fast');
			});
	},
	openPicture : function(caller){
		imageBrowser.createFullscreen(caller);

		imageBrowser.loadPicture(caller);
	},
    openCurrentPicture : function(caller){
        imageBrowser.itemsCount = $(caller).parent().find('ul li').size();

        // this should be replace by a count of all preceding-sibling of the li element
        if ( imageBrowser.itemsCount == 1 )
            imageBrowser.currentItem = 0;
        else {
            tempItemsValue = $(caller).parent().find('span.counter').text();
            tempCurrentItem = tempItemsValue.substr(0,$(caller).parent().find('span.counter').text().indexOf('/'));
            imageBrowser.currentItem = parseFloat(tempCurrentItem - 1); // -1 is cause arrays always start at 0
        }

        imageBrowser.createFullscreen($(caller).parent().find("ul li:eq("+imageBrowser.currentItem+") a"));

        imageBrowser.loadPicture($(caller).parent().find("ul li:eq("+imageBrowser.currentItem+") a"));
    },
loadPicture : function(caller){
		// Put the photo in the container
		$("#fullPhoto").html($(caller).next().find('img').clone());

        // Put the title and content
		$('#fullscreenPhoto .fullscreenText p:eq(0)').html('<strong>' + $(caller).next().find('span.title').text() + '</strong> ( photo '+ (parseFloat(imageBrowser.fullscreenCurrentItem) + 1) +' of '+ imageBrowser.itemsCount +' )');
		var txtP = $('#fullscreenPhoto .fullscreenText p:eq(1)');
		txtP.text($(caller).next().find('span.content').text());
		if (txtP.height() < 30) txtP.height(30);

		// Find the largest image, then set it as the default width
		imageBrowser.fullScreenWidth = 300;
		imageBrowser.fullScreenHeight = 300;

		$(caller).parent().parent().parent().find('li div.liFullPhoto img').each(function(){
			imageWidth = parseFloat($(this).css('width'));
			imageHeight = parseFloat($(this).css('height'));
			if(imageWidth >= imageBrowser.fullScreenWidth){ imageBrowser.fullScreenWidth = imageWidth; }
			if(imageHeight >= imageBrowser.fullScreenHeight){ imageBrowser.fullScreenHeight = imageHeight; }
		})

		var scrollTop = window.pageYOffset || document.documentElement.scrollTop || 0;

		// Set the image browser width to the image width
		$('#fullscreenPhoto').css({
			'width': parseFloat(imageBrowser.fullScreenWidth) + 12,
			'margin-top': -(imageBrowser.fullScreenHeight/2) + scrollTop - 30,
			'margin-left': -imageBrowser.fullScreenWidth/2
		});

		// Then fade it in
		if(jQuery.browser.msie && jQuery.browser.version < 7.0){ $('select').hide(); }
		$('div.overlay').css('opacity',0);
		$('div.overlay').show();
		$('div.overlay').animate({opacity: 0.35}, 300, function(){
			$('div#fullscreenPhoto').fadeIn();
		});
	},
	createFullscreen : function(caller){
        imageBrowser.itemsCount = $(caller).parent().parent().find('li').size();

        // this should be replace by a count of all preceding-sibling of the li element
        if ( imageBrowser.itemsCount == 1 )
            imageBrowser.currentItem = 0;
        else {
            tempItemsValue = $(caller).parent().parent().parent().find('span.counter').text();
			tempCurrentItem = tempItemsValue.substr(0,$(caller).parent().parent().parent().find('span.counter').text().indexOf('/'));
			imageBrowser.currentItem = parseFloat(tempCurrentItem - 1); // -1 is cause arrays always start at 0
        }


        imageBrowser.fullscreenCurrentItem = imageBrowser.currentItem;

		// Build the background overlay div
		backgroundDiv = document.createElement('div');
		$(backgroundDiv).addClass('overlay');
		$(backgroundDiv).css({ 'height':$('body').height() });
		$(backgroundDiv).bind('click',function(){
			imageBrowser.closeFullScreen();
		});

        // Containers
		fullScreenPhotoContainer = document.createElement("div");
		$(fullScreenPhotoContainer).attr({'id':'fullscreenPhoto','class':'clearfix'});

		fullScreenPhotoInside = document.createElement("div");
		$(fullScreenPhotoInside).attr('class','fullscreenPhotoInside');

		// Close link
		fullScreenPhotoClose = document.createElement("a");
		$(fullScreenPhotoClose).attr({
			'href':'#',
			'class':'closeWindow'
		});
            $(fullScreenPhotoClose).bind('click',function(){
                imageBrowser.closeFullScreen();
                return false;
            });
			fullScreenCloseImage = document.createElement('img');
			$(fullScreenCloseImage).attr({
				'src':'/media/images/common/web/buttons/btn_X.gif',
				'width':'13',
				'height':'13',
				'alt':'Close'
			});
		$(fullScreenPhotoClose).append(fullScreenCloseImage);

		// Image Container
		imageContainer = document.createElement('div');
		$(imageContainer).attr('id','fullPhoto');

		// Previous link
		previousLink = document.createElement('a');
		$(previousLink).attr({
			'href':'#',
			'class':'arrow fLeft'
		});
			$(previousLink).bind('click',function(){
				imageBrowser.previousFull($(caller));
				return false;
			});
			previousLinkImage = document.createElement('img');
			$(previousLinkImage).attr({
				'src':'../images/arrow_left_Fullscreen.jpg',
				'width':'29',
				'height':'29'
			});
		$(previousLink).append(previousLinkImage);

		// Next link
		nextLink = document.createElement('a');
		$(nextLink).attr({
			'href':'#',
			'class':'arrow fRight'
		});
			$(nextLink).bind('click',function(){
				imageBrowser.nextFull($(caller));
				return false;
			});
			nextLinkImage = document.createElement('img');
			$(nextLinkImage).attr({
				'src':'../images/arrow_right_fullscreen.gif',
				'width':'29',
				'height':'29'
			});
		$(nextLink).append(nextLinkImage);

		// Text Container
		textContainer = document.createElement('div');
		$(textContainer).attr('class','fullscreenText');
			titleContainer = document.createElement('p');
			photoCounter = document.createElement('span');
			$(photoCounter).append(titleContainer);

			contentContainer = document.createElement('p');

		$(textContainer).append(titleContainer);
		$(textContainer).append(contentContainer);
		$(fullScreenPhotoInside).append(imageContainer).append(fullScreenPhotoClose);

		// Append the links only if there's more then 1 picture
        if(imageBrowser.itemsCount > 1){
			$(fullScreenPhotoInside).append(nextLink).append(previousLink);
		}

		$(fullScreenPhotoInside).append(textContainer);
		$(fullScreenPhotoContainer).append(fullScreenPhotoInside);

        // Append the content
		$('body').append(backgroundDiv);
		$('body').append(fullScreenPhotoContainer);
	},
	closeFullScreen : function(){
		$('div#fullscreenPhoto').animate({opacity: 0}, 300, function(){
			$('div.overlay').animate({opacity: 0}, 300, function(){
				$('div#fullscreenPhoto').remove();
				$('div.overlay').remove();
				if(jQuery.browser.msie && jQuery.browser.version < 7.0){ $('select').show(); }
			});
		});
	}
}

smallImageBrowser = {
	init : function(){
		smallImageBrowser.inAnimation = false;
		smallImageBrowser.currentItem = parseFloat(0);

		$('div.smallImageBrowser').each(function(){
			smallImageBrowser.itemsCount = $(this).find('ul li').size();
			$(this).find('span.counter').text('1/' + $(this).find('ul li').length);

			$(this).find('ul li:eq(0)').css({position: 'absolute', left: '0px'});

			// Set the counter
			//smallImageBrowser.galleryWidth = parseFloat($(this).find('ul li img').width());
            smallImageBrowser.galleryWidth = 190; // statically set to 190 to account for un-initializable cases

            $(this).find('ul li:gt(0)').each(function(){
				$(this).css({
					position : 'absolute',
					right : smallImageBrowser.galleryWidth
				});
			});
		});


	},

	previous : function(caller){
		if(!smallImageBrowser.inAnimation){
			tempItemsValue = $(caller).parent().parent().parent().find('span.counter').text();
			tempCurrentItem = tempItemsValue.substr(0,$(caller).parent().parent().parent().find('span.counter').text().indexOf('/'));
			smallImageBrowser.currentItem = parseFloat(tempCurrentItem - 1); // -1 is cause arrays always start at 0
			smallImageBrowser.itemsCount = parseFloat(tempItemsValue.substr($(caller).parent().parent().parent().find('span.counter').text().indexOf('/') + 1,$(caller).parent().parent().parent().find('span.counter').text().length));

			smallImageBrowser.inAnimation = true;

			$(caller).parent().parent().parent().find('ul li:eq('+smallImageBrowser.currentItem +')').animate({ 'left': smallImageBrowser.galleryWidth }, 500 );

			smallImageBrowser.currentItem = (smallImageBrowser.currentItem - 1) % smallImageBrowser.itemsCount;
			if(smallImageBrowser.currentItem < 0){ smallImageBrowser.currentItem = smallImageBrowser.itemsCount - 1; }

			$(caller).parent().parent().parent().find('ul li:eq('+smallImageBrowser.currentItem +')').css('left',-smallImageBrowser.galleryWidth);
			$(caller).parent().parent().parent().find('ul li:eq('+smallImageBrowser.currentItem +')').animate({ 'left': 0 }, 500, function(){ smallImageBrowser.inAnimation = false; } );

			$(caller).parent().parent().parent().find('span.counter').text(smallImageBrowser.currentItem + 1 + '/' + $(caller).parent().parent().parent().find('ul li').length);
		}
	},
	next : function(caller){
		if(!smallImageBrowser.inAnimation){
			tempItemsValue = $(caller).parent().parent().parent().find('span.counter').text();
			tempCurrentItem = tempItemsValue.substr(0,$(caller).parent().parent().parent().find('span.counter').text().indexOf('/'));
			smallImageBrowser.currentItem = parseFloat(tempCurrentItem - 1); // -1 is cause arrays always start at 0
			smallImageBrowser.itemsCount = parseFloat(tempItemsValue.substr($(caller).parent().parent().parent().find('span.counter').text().indexOf('/') + 1,$(caller).parent().parent().parent().find('span.counter').text().length));

			smallImageBrowser.inAnimation = true;

			$(caller).parent().parent().parent().find('ul li:eq('+smallImageBrowser.currentItem +')').animate({ 'left': -smallImageBrowser.galleryWidth }, 500 );

			smallImageBrowser.currentItem = ++ smallImageBrowser.currentItem % smallImageBrowser.itemsCount;

			$(caller).parent().parent().parent().find('ul li:eq('+smallImageBrowser.currentItem+')').css('left',smallImageBrowser.galleryWidth);
			$(caller).parent().parent().parent().find('ul li:eq('+smallImageBrowser.currentItem+')').animate({ 'left': 0 }, 500, function(){ smallImageBrowser.inAnimation = false; } );

			$(caller).parent().parent().parent().find('span.counter').text(smallImageBrowser.currentItem + 1 + '/' + $(caller).parent().parent().parent().find('ul li').length);
		}
	}
}
