viewportWidth = 0;
viewportHeight = 0;
$(document).ready(function() {
    if ($('body').hasClass("resize")) {
        resizeMap();
    }
    titleReplace();

    $('textarea').each(function() {
        if($(this).html() == " ") {
            $(this).html("");
        }
    });

    $('#searchForm input[name="searchStr"]').bind("focus", function() {
        if (($(this).val() == "") || ($(this).val() == "Enter place or postcode" )) {
            $(this).val("");
        }
    });

    $('#searchForm input[name="searchStr"]').bind("blur", function() {
        if ($(this).val() == "") {
            $(this).val("Enter place or postcode");
        }
    });
    if ($('#airportParkingForm').length == 1) {
        initializeDatePickers();
    }
});
function initializeDatePickers() {
    // arrival
        $('#outDatePick')
            .datePicker(
                // associate the link with a date picker
                {
                    createButton:false
                }
            ).bind(
                // when the link is clicked display the date picker
                'click',
                function()
                {
                    updateOutSelects($(this).dpGetSelected()[0]);
                    $(this).dpDisplay();
                    return false;
                }
            ).bind(
                // when a date is selected update the SELECTs
                'dateSelected',
                function(e, selectedDate, $td, state)
                {
                    updateOutSelects(selectedDate);
                }
            ).bind(
                'dpClosed',
                function(e, selected)
                {
                    updateOutSelects(selected[0]);
                }
            );
            
        var updateOutSelects = function (selectedDate)
        {
            selectedDate = new Date(selectedDate);
            var d = selectedDate.getDate();
            var m = selectedDate.getMonth();
            var y = selectedDate.getFullYear();
            ($('#arrivalDay')[0]).selectedIndex = d - 1;
            ($('#arrivalMonth')[0]).selectedIndex = m;
            $('#arrivalYear').val(y);
            $('#arrivalDow').html(selectedDate.getDayName());
            $('#arrivalDowShort').html(selectedDate.getDayName(true));
        }
        // listen for when the selects are changed and update the picker
        $('#arrivalDay, #arrivalMonth, #arrivalYear')
            .bind(
                'change',
                function()
                {
                    var d = new Date(
                                $('#arrivalYear').val(),
                                $('#arrivalMonth').val()-1,
                                $('#arrivalDay').val()
                            );
                    $('#arrivalDow').html(d.getDayName());
                    $('#arrivalDowShort').html(d.getDayName(true));
                    $('#outDatePick').dpSetSelected(d.asString());
                }
            );
    //departure
        $('#retDatePick')
            .datePicker(
                // associate the link with a date picker
                {
                    createButton:false
                }
            ).bind(
                // when the link is clicked display the date picker
                'click',
                function()
                {
                    updateRetSelects($(this).dpGetSelected()[0]);
                    $(this).dpDisplay();
                    return false;
                }
            ).bind(
                // when a date is selected update the SELECTs
                'dateSelected',
                function(e, selectedDate, $td, state)
                {
                    updateRetSelects(selectedDate);
                }
            ).bind(
                'dpClosed',
                function(e, selected)
                {
                    updateRetSelects(selected[0]);
                }
            );
        
        var updateRetSelects = function (selectedDate)
        {
            selectedDate = new Date(selectedDate);
            var d = selectedDate.getDate();
            var m = selectedDate.getMonth();
            var y = selectedDate.getFullYear();
            ($('#departDay')[0]).selectedIndex = d - 1;
            ($('#departMonth')[0]).selectedIndex = m;
            $('#departYear').val(y);
            $('#departDow').html(selectedDate.getDayName());
            $('#departDowShort').html(selectedDate.getDayName(true));
        }
        // listen for when the selects are changed and update the picker
        $('#departDay, #departMonth, #departYear')
            .bind(
                'change',
                function()
                {
                    var d = new Date(
                                $('#departYear').val(),
                                $('#departMonth').val()-1,
                                $('#departDay').val()
                            );
                    $('#departDow').html(d.getDayName());
                    $('#departDowShort').html(d.getDayName(true));
                    $('#retDatePick').dpSetSelected(d.asString());
                }
            );
    
    // default the position of the selects to today

    $('#arrivalDay').trigger('change');
    $('#departDay').trigger('change');
}

function airportForm () {
    $('#restOfTheForm').slideDown();
    // move the go button
    $('#airportParkingForm .go[type="button"]').remove();
}
function resizeMap() {
    refreshViewport();
    var magic = 260;

    $('#main').css("width", ($('#content').width() - magic)+"px" );
    var newHeight = (viewportHeight - 150);
    if ($('body').hasClass("admin")) {
        newHeight = viewportHeight - 55;        
    }
    if (newHeight < 500) {
        newHeight = 500;
    }
    $('#map').height(newHeight);
    $('#searchResults').height(newHeight - 60); 
    $('#searchResults .scroller').height(newHeight - 60);    
    $( window ).resize( resizeMap ); 
}

function titleReplace() {
    $('.helper[title!=""]').each(function() {
        var title = this.title;
        var obj = $(this);
        $(this).bind("click", function() {
            showHelperToolTip(obj, ''+title);
        });
        this.title = "";
    });
}

function removeHelpers(context) {
    $('.helper', context).remove();
}

function showHelperToolTip(obj, string) {
    var marginTop = parseInt(obj.css("margin-top"));

    var top = (obj.position().top-(obj.height()/2))+marginTop+34;
    var left = obj.position().left+obj.width()-230;

    $("#wrapper").append('<div id="helperToolTip" style="left:'+left+'px; top: '+top+'px"><img class="helperArrow" src="./img/up-arrow-trans.png" alt="" />'+string+'</div>');
    if (obj.attr("id") == "leftSearchHelper") {
        $('input[name="searchStr"]').focus();
    }
    
    $().one("mousedown", function() {
        hideHelperToolTip();
    });
}

function hideHelperToolTip() {

    $('#helperToolTip').fadeOut(function() {
        $('#helperToolTip').remove();
    });
}

function emailCheck(str) {
	var at="@"
	var dot="."
	var lat=str.indexOf(at)
	var lstr=str.length
	var ldot=str.indexOf(dot)

	if (str.indexOf(at)==-1){
	  return false;
	}
	if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr){
	  return false;
	}
	if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr){
	  return false;
	}
	if (str.indexOf(at,(lat+1))!=-1){
	  return false;
	}
	if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){
	  return false;
	}
	if (str.indexOf(dot,(lat+2))==-1){
	  return false;
	}
	if (str.indexOf(" ")!=-1){
	  return false;
	}
	return true;
}

function processErrors(errorObj) {
    for (var i in errorObj) {
        $('#'+errorObj[i].id).addClass('error');
        $('label[for="'+errorObj[i].id+'"]').addClass('error');
        $('#'+errorObj[i].id).after('<img class="helper" title="'+errorObj[i].msg+'" alt="What is this?" src="./img/helper.gif"/>');
        titleReplace();
    }
}

/*
Popup stuff
*/

function showBlackout() {   //show the blackout only if it isn't already there
    if (!$('#blackout').length) {
        updateBrowserDimensions();
        $('body').append('<div id="blackout"></div>');
        $('#blackout').css("height", windowHeight);
        $('#blackout').css("width", windowWidth);
    }
}
function removeBlackout() {   //remove the blackout
    $('div#blackout').fadeOut(function() {
        $('div#blackout').remove();
    });
}

function msgBox(type, title, text, buttons) {
    //show the overlay full screen
    showBlackout();
    var msgBox = '<div id="msgBox">';
    switch(type) {
        case 'attention':
            msgBox += '<img class="right" src="./img/icons/attention.gif" alt="" />';
            break;
        case 'notify':
            msgBox += '<img class="right" src="./img/icons/notify.gif" alt="" />';
            break;
        case 'ok':
            msgBox += '<img class="right" src="./img/icons/ok.gif" alt="" />';
            break;
        case 'info':
            msgBox += '<img class="right" src="./img/icons/ok.gif" alt="" />';
            break;
    }
    msgBox += '<h2 class="left">'+title+'</h2>';
    msgBox += '<p class="clear">'+text+'</p>';
    msgBox += '<div class="buttons">';
    
    $.each(buttons, function(btnName, onClick) { //the a name is the return value of that button
        msgBox += '<button type="button" onclick="javascript:'+onClick+'">'+                                    
                      '<div class="leftSide"></div>'+   
                      '<div class="rightSide">'+btnName+'</div>'+   
                  '</button>';
    });
    
    msgBox += '<div class="clear"></div>';
    msgBox += '</div>';
    msgBox += '</div>';
    $('body').append(msgBox);
    
    //now show the msgBox in the middle of the screen
    centerDiv('#msgBox');
}

function ajaxMsgBox(type, title, load, buttons) {
    //show the overlay full screen
    showBlackout();
    $.get(load, function(text) {
        var msgBox = '<div id="msgBox">';
        switch(type) {
            case 'attention':
                msgBox += '<img class="right" src="./img/icons/attention.gif" alt="" />';
                break;
            case 'notify':
                msgBox += '<img class="right" src="./img/icons/notify.gif" alt="" />';
                break;
            case 'ok':
                msgBox += '<img class="right" src="./img/icons/ok.gif" alt="" />';
                break;
            case 'info':
                msgBox += '<img class="right" src="./img/icons/ok.gif" alt="" />';
                break;
        }
        msgBox += '<h2 class="left">'+title+'</h2>';

        msgBox += text;
        msgBox += '<div class="buttons">';
        
        $.each(buttons, function(btnName, onClick) { //the a name is the return value of that button
            msgBox += '<button type="button" onclick="javascript:'+onClick+'">'+                                    
                          '<div class="leftSide"></div>'+   
                          '<div class="rightSide">'+btnName+'</div>'+   
                      '</button>';
        });
        
        msgBox += '<div class="clear"></div>';
        msgBox += '</div>';
        msgBox += '</div>';
        $('body').append(msgBox);
        
        //now show the msgBox in the middle of the screen
        centerDiv('#msgBox');
    });     
}
function closeMsgBox() {
    //remove the msgBox and blackout
    $('#msgBox').remove();
    removeBlackout();
    return false;
}
function centerDiv(displayDiv) { //centers a div in the middle of the screen
    var divHeight = $(displayDiv).height();
    var divWidth = $(displayDiv).width();
    var hPos = (windowWidth/2) - (divWidth/2);
    var vPos = (windowHeight/2) - (divHeight/2);
    var browserScrollTop = document.documentElement.scrollTop;
    $(displayDiv).css('position', 'absolute');
    $(displayDiv).css('left', hPos);
    $(displayDiv).css('top', vPos+browserScrollTop);
}

function updateBrowserDimensions() {
    windowHeight = $(window).height();
    windowWidth = $(window).width();
}

function lightbox(img) {
    showLightboxLoader();
    var image = new Image();
    image.src = img;
    image.onload = function() {
        $('#lightboxLoader').remove();
        msgBox( "",
            "",
            '<img src="'+img+'" alt="" />',
            {"Close": "closeMsgBox()"});
    };
}

function showLightboxLoader() {
    showBlackout();
    $('body').append('<div id="lightboxLoader"><img src="./img/indicator.gif" alt="Loading..." /><br />Loading...</div>');
    centerDiv('#lightboxLoader');
}

function msgBoxFromContentDiv(title, fromDiv) {
    msgBox("info", title, $('#'+fromDiv).html(), {"Close": "closeMsgBox()"});
}

function showTnC() {
    $('.termsAndConditions').slideDown();
}

function refreshViewport() {
    if (typeof window.innerWidth != 'undefined') {
        viewportWidth = window.innerWidth;
        viewportHeight = window.innerHeight;
    } else if (typeof document.documentElement != 'undefined' && typeof document.documentElement.clientWidth != 'undefined' && document.documentElement.clientWidth != 0) {
        viewportWidth = document.documentElement.clientWidth;
        viewportHeight = document.documentElement.clientHeight;
    } else {
        viewportWidth = document.getElementsByTagName('body')[0].clientWidth;
        viewportHeight = document.getElementsByTagName('body')[0].clientHeight;
    }
}