/* 	AMP OBJECT:
	Note: Stores values that needs to be accessible
	globally.
================================================== */
var Amp = {


	cssIsOn: true,

	dimensions: {
		isSet: false
	},
	
	modal: {
		isAlreadyBuilt: false,
		isOpen: false
	},
	
	slideshow: {
		pause: false,
		pausedExternally: false
	}
	
	
	
	
}; /* END: AMP OBJECT */

/*	HELPER OBJECT
	Note: Holds helper function that doesn't 
	need a jQuery target.
================================================== */
var Helper = {



	/* GET PAGE DIMENSIONS
	================================================== */
	pageDimensions: function(){
	
		Amp.dimensions.documentWidth	= docWidth	= $(document).width();
		Amp.dimensions.documentHeight  	= docHeight = $(document).height();
		Amp.dimensions.windowWidth	    = winWidth	= $(window).width();
		Amp.dimensions.windowHeight		= winHeight = $(window).height();
		Amp.dimensions.bodyWidth	    = bodyWidth	= $("body").width();
		Amp.dimensions.bodyHeight      	= bodyHeight = $("body").height();
										// IE uses bodyWidth, everything else uses docWidth
		Amp.dimensions.overlayWidth		= ($.browser.msie && parseInt($.browser.version) < 7) ? bodyWidth : docWidth; 
		Amp.dimensions.overlayHeight	= (docHeight < winHeight) ? winHeight : docHeight;
		
	},	/* END: pageDimensions() */
	
	/*	OPEN MODAL WINDOW
	================================================== */
	modalOpen: function(modalData, modalWidth){
		this.modalData = modalData;
		this.modalWidth = modalWidth;
		
		// Pause any slideshow in progress
		if(Amp.slideshow.pause == false){
			Amp.slideshow.pause = true;
			Amp.slideshow.pausedExternally = true;
		}
		
		// Set page dimension measurements if none exists, or recalculates if the page was resized. 
		/* 	Note: Currently set to calculate when modalOpen is fired AND if Amp.dimensions.isSet 
			is set to 'false'.
			This is better than the alternative of re-calculating all dimensions 
			when the user resizes the page. The page resize is wonky and consumes
			processing cycles continously - a UI and performance problem.
		*/
		if(!Amp.dimensions.isSet){
			Helper.pageDimensions();
			Amp.dimensions.isSet = true;
		}
		
		// Clone dimensions object in Amp
		var dimensions = Amp.dimensions;
		
		// Check if the modal window was already built, if not build one.
		if(Amp.modal.isAlreadyBuilt){
			
			// Move modalOverlay (which is already created) back over the visible page
			var modalOverlay = $('#modalOverlay').css({
				display: 'block',
				top: '0',
				width: dimensions.overlayWidth,	
				height: dimensions.overlayHeight
			});
			
			// Show modalWindow (which is already created)
			var modalWindow = $('#modalWindow').css({
				display: 'block'
			});
			
			/* 	Add an assigned width if modalWidth title attr was present 
				in the anchor that triggers the modal. Else clear the width class and default 
				to #modalWindow's original width of 700px
			*/
			if(modalWidth !== 'none'){
				$('#modalWindow').removeAttr('class').addClass(modalWidth);
			} else if(Amp.modal.isOpen && (modalWidth == 'none')){
				// Do nothing
			} else {
				$('#modalWindow').removeAttr('class');
			}
			
			//Insert modalData into the modal
			$('.modalBody').html(modalData);
				
		} else {
		
			// Create Semi-Transparent Overlay
			var modalOverlay = $("<div id=\"modalOverlay\"></div>").css({
				width: dimensions.overlayWidth,	
				height: dimensions.overlayHeight
			}).bgiframe().appendTo("body");
			
			// Create Modal Window
			var modalWindow = $('<div id=\"modalWindow\"></div>').appendTo("body");
			
			// Insert data into modalWindow
			modalWindow.html('<div class=\"modalHeader\"></div> <div class=\"modalBody\">' +modalData+ '</div> <div class=\"modalFooter\"></div>')
			/*
			modalWindow.html('<div class=\"modalHeader\"><div class=\"wrapper\"></div></div> <div class=\"modalBody\">' +modalData+ '</div> <div class=\"modalFooter\"><div class=\"wrapper\"></div></div>')
			
			*/
			// Add an assigned width class if modalWidth title attr was present in the anchor that triggers the modal
			if(modalWidth !== 'none'){
				$('#modalWindow').addClass(modalWidth);
			}
			
			// Create Close Button
			var modalCloseButton = $('<a id=\"modalClose\">Close</a>').prependTo('#modalWindow .modalHeader');
			
			// Bind Close Modal function to Close Button
			modalCloseButton.bind('click', function(){
				Helper.modalClose();
				return false;
			});
			
			// Set modal already built to true for reuse.
			Amp.modal.isAlreadyBuilt = true;
		}
		
		
		// Calculate if the user has scrolled the window
		Amp.dimensions.scrollLeft	= $(document).scrollLeft();
		Amp.dimensions.scrollTop	= $(document).scrollTop();
		
		// Calculate the X Y coordinates in order to center the modal window
		var moveModalLeft = Math.round(dimensions.overlayWidth / 2) - Math.round(modalWindow.width() / 2) + Amp.dimensions.scrollLeft;
		
		if(modalWindow.height() > dimensions.windowHeight){
			var moveModalTop = 0;
		} else {
			var moveModalTop = Math.round(dimensions.windowHeight / 2) - Math.round(modalWindow.height() / 2) + Amp.dimensions.scrollTop;
		}
		
		// Move modal window into the visible area of the page
		modalWindow.css({
			left: moveModalLeft,
			top: moveModalTop
		});
		
		// Call rebind event function
		Helper.rebindModalEvents();

		Amp.modal.isOpen = true;
		
	},	/* END: modalOpen() */
	
	
	
	/*	MODAL CLOSE
	================================================== */
	modalClose: function(){
		
		// Move and Hide Modal Display
		$('#modalOverlay, #modalWindow').css({
			display: 'none',
			top: '-10000px'
		});
		
		Amp.modal.isOpen = false;
		Amp.modal.isAlreadyBuilt = true;
		
		// Restart Slideshow if it was paused when modal window was launched
		if(Amp.slideshow.pausedExternally == true){
			Amp.slideshow.pause = false;
			Amp.slideshow.pausedExternally = false;
		}
		
	},	/* END: modalClose() */
	
	
	/*	MODAL RESIZE
	================================================== */
	modalResize: function(){
		
		Helper.pageDimensions();
		
		var modalWindow = $('#modalWindow');
		
		// Calculate if the user has scrolled the window
		Amp.dimensions.scrollLeft	= $(document).scrollLeft();
		Amp.dimensions.scrollTop	= $(document).scrollTop();
		
		// Calculate the X Y coordinates in order to center the modal window
		var moveModalLeft = Math.round(Amp.dimensions.overlayWidth / 2) - Math.round(modalWindow.width() / 2) + Amp.dimensions.scrollLeft;
		
		if(modalWindow.height() > Amp.dimensions.windowHeight){
			var moveModalTop = 0;
		} else {
			var moveModalTop = Math.round(Amp.dimensions.windowHeight / 2) - Math.round(modalWindow.height() / 2) + Amp.dimensions.scrollTop;
		}
		
		// Move modal window into the visible area of the page
		modalWindow.css({
			left: moveModalLeft,
			top: moveModalTop
		});

	},	/* END: modalResize() */



	
	/*	REBIND EVENTS IN MODAL DATA
	================================================== */
	rebindModalEvents: function(){
		
		
		/*	MODAL WINDOW USING AJAX FORM SUBMIT
		================================================== */
		if($('#modalWindow form.modalForm').length > 0){	
			$('#modalWindow form.modalForm').each(function(){
				var target = $(this);
				target.submit(function(){
					target.modalForm();
					return false;
				});
			});	
		}
		
		/*	BIND MODAL WINDOW WITH CONTENT LOADED VIA AJAX
		================================================== */
		if($('#modalWindow a.modalAjax').length > 0){	
			$('#modalWindow a.modalAjax').live('click', function(){
				$(this).modalAjax();
				return false;
			});  
		}
		
		/*	TAB CONTENT
		================================================== */
		if($('#modalWindow .tabContent').length > 0){
			$('#modalWindow .tabContent').each(function(){
				$(this).tabContent();   
			})         
		}
		
		/*	ACCORDION CONTENT
		================================================== */
		if($('#modalWindow .accordionContent').length > 0){
			$('#modalWindow .accordionContent').each(function(){
				$(this).accordion({
					header: 'h6',
					autoHeight: false
				});   
			})         
		}
		
		/* POP UP WINDOW
		================================================== */
		if($('#modalWindow a.popUpWindow').length > 0){
			$('a.popUpWindow').each(function(){
				$(this).popUpWindow();
			})   
		}
		
		
		/*	BIND CONTACT SHOW/HIDE EVENT IN RATINGS FORM
		================================================== */
		if($('#modalWindow .rating_form').length > 0){	
			$('#modalWindow #yes').bind('click', function(){
				var contactInfo = $(this).parent('.approval_checkbox').siblings('.contact_information');
				
				if(contactInfo.hasClass('visible')){
					contactInfo.removeClass('visible');
				} else {
					contactInfo.addClass('visible');
				}
				
			});  
			
		}
		
		/*	ASSIGN MAPS MODAL SUB NAV
		================================================== */
		if($('#modalWindow .mapsModalSubNav').length > 0){	
			$('#modalWindow .mapsModalSubNav').unbind().mapsModalSubNav();
		}
		
		/*	ASSIGN ADDITIONAL CLOSE MODAL BUTTON
		================================================== */
		if($('#modalWindow .modalClose').length > 0){	
			$('#modalWindow .modalClose').click(function(){
				Helper.modalClose();
			});
		}
		
		
	} /* END: rebindModalEvents() */
}; /* END: HELPER OBJECT */

/*	JQUERY EXTENSIONS
================================================== */
jQuery.fn.extend({

    /*	CALLS OPEN MODAL WINDOW FUNCTION 
    AND LOAD CONTENT VIA AJAX
    ================================================== */
    modalAjax: function() {

        var target = $(this);
        var ajaxLink = $(this).attr('href');

        // get a width class assignment for the model if one exists.
        if (target.attr('title').length > 0) {
            var modalWidth = target.attr('title');
        } else {
            var modalWidth = 'none';
        }

        // Make an AJAX request, then passed the received data to Helper.modalOpen();
        $.ajax({
            type: "POST",
            url: ajaxLink,
            success: function(msg) {
                Helper.modalOpen(msg, modalWidth);
            },
            error: function(XMLHttpRequest, textStatus, errorThrown) {
                alert('The AJAX data requested from the server failed and gave the following messages. \n\nStatus:\n '
				+ textStatus + '\n\nError Message:\n' + errorThrown)
            }
        })

    }, /* END: tabContent() */



    /*	CALLS OPEN MODAL WINDOW FUNCTION 
    AND LOAD CONTENT VIA NESTED CONTENT
    ================================================== */
    modalInline: function() {

        var target = $(this);
        var inlineData = $(this).siblings('.modalInlineData').html();

        // get a width class assignment for the model if one exists.
        if (target.attr('title').length > 0) {
            var modalWidth = target.attr('title');
        } else {
            var modalWidth = 'none';
        }

        Helper.modalOpen(inlineData, modalWidth);

    }, /* END: modalInline() */



    /*	SUBMITS FORM DATA VIA AJAX AND 
    CALLS OPEN MODAL WINDOW FUNCTION
    ================================================== */
    modalForm: function() {

        var targetForm = $(this);

        var ajaxLink = targetForm.attr('action');

        var continueToSubmitForm = true;

        if (targetForm.hasClass('validationRequired')) {

            targetForm.find('input, select').each(function(i) {
                var targetInput = $(this);

                if (targetInput.is('input')) {
                    if (targetInput.attr('name') == 'email') {
                        if (targetInput.attr('value') == '') {
                            targetInput.closest('.inputWrapper').addClass('inputError');
                            continueToSubmitForm = false;
                        } else {
                            var emailPattern = /^[a-zA-Z0-9_\.\-]+\@([a-zA-Z0-9\-]+\.)+[A-Za-z0-9]*[A-Za-z][A-Za-z0-9]{1,3}$/;
                            var patternPassed = emailPattern.test(targetInput.attr('value'));
                            if (patternPassed) {
                                if (targetInput.closest('.inputWrapper').hasClass('inputError')) {
                                    targetInput.closest('.inputWrapper').removeClass('inputError');
                                };
                            } else {
                                targetInput.closest('.inputWrapper').addClass('inputError');
                                continueToSubmitForm = false;
                            }
                        }

                    } else if (targetInput.attr('value') == '') {
                        targetInput.closest('.inputWrapper').addClass('inputError');
                        continueToSubmitForm = false;
                    } else {
                        if (targetInput.closest('.inputWrapper').hasClass('inputError')) {
                            targetInput.closest('.inputWrapper').removeClass('inputError');
                        };
                    }
                } else if (targetInput.is('select')) {
                    if (targetInput.children('option:first').attr('selected')) {
                        targetInput.closest('.inputWrapper').addClass('inputError');
                        continueToSubmitForm = false;
                    } else {
                        if (targetInput.closest('.inputWrapper').hasClass('inputError')) {
                            targetInput.closest('.inputWrapper').removeClass('inputError');
                        };
                    }
                }
            })

            if (!continueToSubmitForm) {
                targetForm.siblings('p.generalError').show();
                Helper.modalResize();
            }

        }

        if (continueToSubmitForm) {

            var formData = targetForm.serialize();

            $.ajax({
                type: "POST",
                url: ajaxLink,
                data: formData,
                success: function(msg) {
                    Helper.modalOpen(msg);
                },
                error: function(XMLHttpRequest, textStatus, errorThrown) {
                    alert('Sorry, the AJAX data requested from the server failed and gave the following messages. \n\nStatus:\n '
					+ textStatus + '\n\nError Message:\n' + errorThrown);
                }
            })

        }

        return false;

    }, /* END: modalInline() */


    /*	SUBMITS FORM DATA VIA AJAX
    ================================================== */
    formAjax: function(formLocation) {

        this.formLocation = formLocation;

        var targetForm = $(this);

        var ajaxLink = targetForm.attr('action');

        var continueToSubmitForm = true;

        targetForm.find("input[type='text']").each(function() {

            var targetInput = $(this);

            if (targetInput.attr('name') == 'email') {
                if (targetInput.attr('value') == '' || targetInput.attr('value') == 'username@email.com') {
                    targetInput.closest('.inputWrapper').addClass('inputError');
                    continueToSubmitForm = false;
                } else {
                    var emailPattern = /^[a-zA-Z0-9_\.\-]+\@([a-zA-Z0-9\-]+\.)+[A-Za-z0-9]*[A-Za-z][A-Za-z0-9]{1,3}$/;
                    var patternPassed = emailPattern.test(targetInput.attr('value'));
                    if (patternPassed) {
                        if (targetInput.closest('.inputWrapper').hasClass('inputError')) {
                            targetInput.closest('.inputWrapper').removeClass('inputError');
                        };
                    } else {
                        targetInput.closest('.inputWrapper').addClass('inputError');
                        continueToSubmitForm = false;
                    }
                }

            } else if (targetInput.attr('value') == '') {
                targetInput.closest('.inputWrapper').addClass('inputError');
                continueToSubmitForm = false;
            } else if (targetInput.attr('value') == 'First Name') {
                targetInput.closest('.inputWrapper').addClass('inputError');
                continueToSubmitForm = false;
            } else if (targetInput.attr('value') == 'Last Name') {
                targetInput.closest('.inputWrapper').addClass('inputError');
                continueToSubmitForm = false;
            } else {
                if (targetInput.closest('.inputWrapper').hasClass('inputError')) {
                    targetInput.closest('.inputWrapper').removeClass('inputError');
                };
            }
        })


        if (!continueToSubmitForm) {

            targetForm.siblings('p.generalError').show();

        } else {

            targetForm.siblings('p.generalError').hide();

            var formData = targetForm.serialize();

            $.ajax({
                type: "POST",
                url: ajaxLink,
                data: formData,
                success: function(msg) {
                    $(formLocation).html(msg);
                },
                error: function(XMLHttpRequest, textStatus, errorThrown) {
                    alert('Sorry, the AJAX data requested from the server failed and gave the following messages. \n\nStatus:\n '
					+ textStatus + '\n\nError Message:\n' + errorThrown);
                }
            })

        }

        return false;

    }, /* END: formAjax() */



    /*	SLIDESHOW
    ================================================== */
    slideshow: function() {

        var target = $(this);

        var jumpAnchors = target.find('.box2 a');

        jumpAnchors.live('click', function(e) {

            e.preventDefault();

            var anchor = $(this);

            var anchorClass = 'wrapper ' + (anchor.attr('class'));

            if (anchor.parent().hasClass('box2') || anchor.parent().hasClass('box3')) {

                anchor.addClass('active').siblings('a').removeClass('active').closest('.box2').siblings('.box1').fadeOut(300, function() {
                    anchor.closest('.wrapper').attr('class', anchorClass);
                }).fadeIn(300);

                return false;
            }


        })

    }, 	/* END: slideShow() */

  


    /*	POP UP WINDOW
    ================================================== */
    popUpWindow: function() {
        var target = $(this);

        target.click(function(e) {

            e.preventDefault();

            var anchor = $(this);
            var anchorTarget = anchor.attr('href');

            // get a width class assignment for the model if one exists.
            if (anchor.attr('title').length > 0) {
                var popUpWidth = "width=" + (anchor.attr('title').match(/[\d\.]+/g)) + ",height=700,resizable=yes,scrollbars=yes,status=no,toolbar=no,menubar=no,location=no";
            } else {
                var popUpWidth = "width=980,height=700,resizable=yes,scrollbars=yes,status=no,toolbar=no,menubar=no,location=no";
            }

            window.open(anchorTarget, null, popUpWidth);

            return false;
        });

    } /* END: popUp() */



});                               	/* END: JQUERY EXTENSIONS */




/*	JQUERY'S VERSION OF WINDOW.ONLOAD AND DOM READY
================================================== */
$(document).ready(function() {


    $('div.pngImg').ifixpng();

    $.preloadCssImages();


    /*	Set CSS off properity to 'true' if CSS is turned off
    ================================================== */
    if ($('.accessibilityJumpLinks').css('position') != 'absolute') {
        Amp.cssIsOn = false;
    };



    /*	Check if CSS is on, if so run.
    ================================================== */
    if (Amp.cssIsOn) {


        /*	BIND REGULAR, NON-MODAL FORM AJAX FUNCTION
        ================================================== */
        if ($('form.formAjax').length > 0) {

            var targetForm = $('form.formAjax');

            var formLocation = targetForm.closest('.wrapper');

            // Bind Focus and Blur Functions
            targetForm.find("input[type='text']").each(function() {
                var target = $(this);

                var labelValue = target.closest('.inputChrome').siblings('label').text();

                target.bind('focus', function() {

                    if (target.attr('value') == labelValue) {
                        target.attr('value', '');
                    }
                });

                /*
                target.bind('blur', function(){
					
					if(target.attr('value') == ''){
                target.attr('value', labelValue);	
                }
					
				});
				*/
            });

            targetForm.submit(function(e) {
                e.preventDefault()
                $(this).formAjax(formLocation);
                return false;
            });
        }




        /*	MODAL WINDOW WITH CONTENT LOADED VIA AJAX
        ================================================== */
        if ($('a.modalAjax').length > 0) {
            $('a.modalAjax').live('click', function() {
                $(this).modalAjax();
                return false;
            });
        }



        /*	MODAL WINDOW WITH CONTENT LOADED VIA INLINE DATA
        ================================================== */
        if ($('a.modalInline').length > 0) {
            $('a.modalInline').live('click', function() {
                $(this).modalInline();
                return false;
            });
        }



        /*	MODAL WINDOW USING AJAX FORM SUBMIT
        ================================================== */
        if ($('form.modalForm').length > 0) {
            $('form.modalForm').each(function() {
                var target = $(this);
                target.submit(function() {
                    target.modalForm();
                    return false;
                });
            });
        }



        /* SLIDESHOW
        ================================================== */
        if ($('#slideshow').length > 0) {
            $('#slideshow').slideshow();
        }

        /*
        ========================================================================*/
//                Helper.loadTotalFlightSearches();
//                Helper.loadMostSearchArrivals();
//                Helper.loadMostSearchDepartures();
//                Helper.loadFlightSearchData();


        /* DATA DASHBOARD
        
        ================================================== */
if ($('#dataDashboard').length > 0) {
        $('#dataDashboard').dataDashboard();
        $('#dataDashboard').totalSearchPanel();
        $('#dataDashboard').mostSearchedArrDepPanel("Arr");
        $('#dataDashboard').mostSearchedArrDepPanel("Dep");
}


        /* POP UP WINDOW
        ================================================== */
        if ($('a.popUpWindow').length > 0) {
            $('a.popUpWindow').each(function() {
                $(this).popUpWindow();
            })
        }


        /* PAGE RESIZE DETECTION
        ================================================== */
        $(window).resize(function() {
            /* 	Change 'isSet' property to false so that the 
            modal will recalculate page dimensions the next 
            time a modal loads. */
            Amp.dimensions.isSet = false;
        });

    } /* END: CSS On Before Running functions check */


});      	/* END: DOM READY */



