﻿
// Check that the page has loaded
$(document).ready(function() {

    // LOGIN CHECKBOX IMAGE REPLACE

    // Handle click
    $('#loginRight .checkbox').click(function() {
        var input = $(this).find('INPUT')

        if (input.attr("checked")) {
            $(this).css({
                backgroundPosition: '0 0'
            }) // Move background image (active)
            input.attr("checked", "");
        }

        else {
            $(this).css({
                backgroundPosition: '0 -11px'
            }) // Move background image (inactive)
            input.attr("checked", "checked");
        }
        return false;
    });


    // COMMENT BOX EXPAND/COLLAPSE  

    $('#homepage #upDownArrow').toggle(function() {

        $('#homepage #commentBox').animate({
            height: "200px"
        }, 300);

        $('#homepage #upDownArrow').css({
            backgroundPosition: "0 -21px"
        });

        return false;
    }, function() {

        $('#homepage #commentBox').animate({
            height: "44px"
        }, 300);

        $('#homepage #upDownArrow').css({
            backgroundPosition: "0 0"
        });

        return false;
    });

    // DROPOUT MENU BOX EXPAND/COLLAPSE  

    $('#dropoutMenuArrow').toggle(function() {

        $('#dropoutMenu').animate({
            height: ($('#dropoutMenu ul').height() + 44) + "px"
        }, 300);

        $('#dropoutMenuArrow').css({
            backgroundPosition: "0 0"
        });

        return false;
    }, function() {

        $('#dropoutMenu').animate({
            height: "24px"
        }, 300);

        $('#dropoutMenuArrow').css({
            backgroundPosition: "0 -21px"
        });

        return false;
    });

    // CATEGORY LINKS ROLLOVER
    $('#homepage #categoryLinks .categoryLinkGroup').hover(    //mouseover
    function() {
        $(this).find('.title').addClass('over');
    },    // mouseout
    function() {
        $(this).find('.title').removeClass('over');
    });


    // TAB SELECT

    // Select first tab content
    $('#tabbedBody .searchContent').hide();
    $('#tabbedBody #housing').show();

    // Show correct tab on click
    $('#tabs A').click(function() {

        // Show correct search content
        $('#tabbedBody .searchContent').hide();

        var content = $(this).attr('href');

        $('#tabbedBody #' + content + '').show();

        // Show correct results colour
        $('#resultListing').removeClass();

        var style = $(this).attr('href');

        $('#resultListing').addClass(style);

        // Highlight correct tab
        $('#tabs .tab').removeClass('selected');

        $(this).parent('LI').addClass('selected');

        return false;
    });

    // If they have come from an tablink show correct tab 

    if (document.location.search.indexOf("tab=") > 0) {
        var content = document.location.search.substring(document.location.search.indexOf("tab=") + 4);
        // Get the tab in question and click it!
        $('#' + content + 'Tab a').click();
    }



    // GENERAL CHECKBOX IMAGE REPLACE
    // Set inital checked state
    $('.largeCheckbox').each(function() {
        if ($(this).find('INPUT').is(':checked')) {
            $(this).find('.checkboxReplacement').css({ backgroundPosition: '0 -26px' }) // Move background image (active)
        }
    });
    $('.smallCheckbox').each(function() {
        if ($(this).find('INPUT').is(':checked')) {
            $(this).find('.checkboxReplacement').css({ backgroundPosition: '0 -26px' }) // Move background image (active)
        }
    });

    // Handle click
    $('.largeCheckbox').click(function() {

        if ($(this).find('INPUT').is(':checked')) {
            $(this).find('.checkboxReplacement').css({ backgroundPosition: '0 0' }) // Move background image (active)
            $(this).find('INPUT').attr("checked", ""); // Click <input> to keep backend working
        }

        else {
            $(this).find('.checkboxReplacement').css({ backgroundPosition: '0 -26px' }) // Move background image (inactive)
            $(this).find('INPUT').attr("checked", "checked"); // Click <input> to keep backend working
        }
    });

    // Handle click
    $('.smallCheckbox').click(function() {

        if ($(this).find('INPUT').is(':checked')) {
            $(this).find('.checkboxReplacement').css({ backgroundPosition: '0 0' }) // Move background image (active)
            $(this).find('INPUT').click(); // Click <input> to keep backend working
        }

        else {
            $(this).find('.checkboxReplacement').css({ backgroundPosition: '0 -20px' }) // Move background image (inactive)
            $(this).find('INPUT').click(); // Click <input> to keep backend working
        }
    });


    // Bind print buttons 

    $('.printPage').click(function() {
        $('#logo a img').attr('src', '/i/logoWhite.jpg');
        window.print();
        $('#logo a img').attr('src', '/i/logo.gif');
        return false;
    });

    // Setup login boxes
    $('#txt_loginEmail').focus(function() {
        if ($(this).val() == "Email Address") {
            $(this).val("");
        }
    });

    $('#txt_loginEmail').blur(function() {
        if ($(this).val() == "") {
            $(this).val("Email Address");
        }
    });

    // Bind login button to ajax login function
    $('#login .submitButton input').click(function() {
        var JSONData = "{'email': '" + $('#txt_loginEmail').val() + "', 'password': '" + hex_md5($('#txt_loginPassword').val()) + "', 'remember': '" + $('#checkbox_remember').is(':checked') + "'}";
        $.ajax({
            type: "POST",
            url: 'methods/methods.aspx/logIn',
            data: JSONData,
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function(data) {
                result = JSON.parse(data.d);
                if (result.success) {
                    //                    $('#login').hide();
                    //                    $('#logout').show();
                    window.location = "/manager";
                }
                else {
                    if (result.errorMessage != "Server Error") {
                        $('#loginError').html("<span class=\"error\">" + result.errorMessage + "</span>");
                    }
                    else {
                        $('#loginError').html("<span class=\"error\">There was an error logging you in, please try again later</span>");
                    }
                }

            },
            failure: function(data) {
                $('#loginError').html("<span class=\"error\">There was an error logging you in, please try again later</span>");
            }
        });
        return false;

    });

    // Bind logout button
    $('#logout .submitButton a').click(function() {

        $.ajax({
            type: "POST",
            url: 'methods/methods.aspx/logOut',
            data: '{}',
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function(data) {
                result = JSON.parse(data.d);
                if (result.success) {
                    location.reload();
                }
                else {
                    if (result.errorMessage != "Server Error") {
                        $('#logoutError').html("<span class=\"error\">" + result.errorMessage + "</span>");
                    }
                    else {
                        $('#logoutError').html("<span class=\"error\">There was an error logging you in, please try again later</span>");
                    }
                }

            },
            failure: function(data) {
                $('#logoutError').html("<span class=\"error\">There was an error logging you in, please try again later</span>");
            }
        });

    });

    // Bind forgot password button
    $('#forgotPass').click(function() {
        if ($('#txt_loginEmail').val() == "") {
            $('#loginError').html("<span class=\"error\">Please enter your email address</span>");
        }
        else {
            $.ajax({
                type: "POST",
                url: 'methods/methods.aspx/passwordReminder',
                data: "{'email': '" + $('#txt_loginEmail').val() + "'}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function(data) {
                    result = JSON.parse(data.d);
                    if (result.success) {
                        $('#forgotPass').html("Successfully sent reminder");
                        $('#loginError').html('');
                    }
                    else {
                        if (result.errorMessage != "Server Error") {
                            $('#loginError').html("<span class=\"error\">" + result.errorMessage + "</span>");
                        }
                        else {
                            $('#loginError').html("<span class=\"error\">There was an error, please try again later</span>");
                        }
                    }
                }
            });
        }
        return false;
    });


    //Flag clicks 
    $('#languageFlags li:not(.text) ').hover(function() {
        if ($(this).is(".americanSelected")) {
            $('#languageFlags li.text').hide();
        }
        else {
            $('#languageFlags li.text').show();
        }
    },
        function() {
            $('#languageFlags li.text').hide();
        }
    );

    $('#languageFlags li a ').click(function() {

        return false;
    });

    $('#bookmark a').click(function() {
        if ((navigator.appName == "Microsoft Internet Explorer") && (parseInt(navigator.appVersion) >= 4)) {
            window.external.AddFavorite(window.location, "World Of Relocation");
        } else if (navigator.appName == "Netscape") {
            window.sidebar.addPanel("World Of Relocation", window.location, "");
        }
    });
    $('#headerBanners').innerfade({ speed: '3000', timeout: 6000, type: 'sequence' });

    // Setup homepage dropdown to forward to search page
    $('a.startSearch').click(function() {
        if ($('.dropCity').attr("selectedIndex") > 0) {
            window.location = "search.aspx?CityID=" + $('.dropCity').val();
        }
        else {
            $('.dropdown .small').animate({ marginLeft: "10px" }, 250).animate({ marginLeft: "0px" }, 250).animate({ marginLeft: "10px" }, 250).animate({ marginLeft: "0px" }, 250).animate({ marginLeft: "10px" }, 250).animate({ marginLeft: "0px" }, 250);
        }
        return false;
    });

    // DropoutList Item Bullet 
    $('#dropoutMenu li').prepend("<span style=\"color: #f33A06; font-weight: bold; font-size: 2em; margin-right: 8px;\"> &gt; </span>");
    
    // Load the google maps api
    $.getScript('http://maps.google.com/maps?file=api&v=2&async=2&key=ABQIAAAANPH9gcmVuAEzKV9w9r-z4xTOmqXu6UsUzKnBPGffYtYQpmHf0xT4czJYYF5uEYYOmL1UZpAZqlgBTQ', function() {
        });

    // Open the location selection map and bind the double click function for it
    $('.byMap a').click(function() {
        if (GBrowserIsCompatible()) {
            $('#mapPopup').show();
            var mapid = "map";
            var latitude = 0;
            var longitude = 0;
            var map = new GMap2(document.getElementById(mapid));
            map.setCenter(new GLatLng(latitude, longitude), 2);
            map.disableDoubleClickZoom();
            map.enableGoogleBar();
            map.enableScrollWheelZoom();
            map.addControl(new GSmallMapControl());
            map.addControl(new GScaleControl());
            map.addControl(new GMapTypeControl());
            var selectedLat = 0;
            var selectedLong = 0;
            GEvent.addListener(map, "dblclick", function(overlay, latlng) {
                if (latlng) {
                    map.clearOverlays();
                    var marker = new GMarker(latlng);
                    selectedLat = latlng.lat();
                    selectedLong = latlng.lng();
                    map.addOverlay(marker);                
                }
            });
            $('.btnMapSearchGo').click(function() {
            
              $.ajax({
                        type: "POST",
                        url: 'methods/methods.aspx/chooseCityFromLatLong',
                        data: "{'latitude': '" + selectedLat + "'," +
                              "'longitude': '" + selectedLong + "'}",
                        contentType: "application/json; charset=utf-8",
                        dataType: "json",
                        success: function(data) {
                            result = JSON.parse(data.d);
                            if (result.success) {
                                window.location = "search.aspx?CityID=" + result.cityID;
                            }
                            else {
                                if (result.errorMessage != "Server Error") {
                                    $('#loginError').html("<span class=\"error\">" + result.errorMessage + "</span>");
                                }
                                else {
                                    $('#loginError').html("<span class=\"error\">There was an error, please try again later</span>");
                                }
                            }
                        }
                    });
            });
    
        }
    });

    // Close the location selection map
    $('#mapPopup .closeWindow a').click(function() {
        $('#mapPopup').hide();
    });

});


function isValidEmail(email) {
    return TVI.Validation.email(email);
}