$(function(){ // On document-ready
    $('form.ajaxform').ajaxSubmit(); // Ajaxify forms
    $("div.formMessage").html($("div.formMessage").html() + "<div class=\"close\"><a href=\"javascript:void(0);\" onclick=\"$('div.formMessage').fadeOut('normal');\">X</a></div>");
    
    // home page slider
    if ($('#home-banner').length != 0) {
        $('#home-banner').cycle({
            'timeout' : 3500,
            'pause'   : 1
        });
    }
    
    if ($("select.input[name='areaid']").length) {
        $("select.input[name='areaid']").multiSelect({
            selectAll: true,
            selectNone: true,
            noneSelected: 'Select Location',
            oneOrMoreSelected: '% Location(s)'
        });
    }
    
    if ($("select.input[name!='areaid']").length) {
        $("select.input[name!='areaid']").selectBox();
    }
    
    if ($("input.input[ref!='']").length) {
        $("input.input[ref!='']").blur(function(){
            if ($(this).val() == "") {
                $(this).val($(this).attr('ref'));
            }
        });
    }
    
    if ($("input.input[ref!='']").length) {
        $("input.input[ref!='']").focus(function(){
            if ($(this).val() == $(this).attr('ref')) {
                $(this).val('');
            }
        });
    }
    
    if ($('form[name="property_search"]')) {
        $('form[name="property_search"]').submit(function(){
            $("input.input[ref!='']").each(function(){
                if ($(this).val() == $(this).attr('ref')) {
                    $(this).val("");
                }
            });
        });
    }
    
    if ($('a[rel="gallery"]').length) {
        $('a[rel="gallery"]').colorbox();
    }
    if ($('a.slideshow').length) {
        $('a[rel="galleryslide"]').colorbox({slideshow: 'true'});
        $('a.slideshow').click(function(ev) {
            ev.preventDefault();
            $('#slideshow-gallery a.first').click();
        });
    }
    
    if ($('#floorplan-gallery').length) {
        $('a[rel="fpoverlay"]').colorbox();
        $('#floorplan-gallery').click(function(ev) {
            ev.preventDefault();
            $('#floorplan-gallery-images a.first').click();
        });
    }
    
    if ($('#google-map').length){
        // we have a google map
        loadScript();
    }
    
    if ($('#overlay-toggle').length) {
        $('#overlay-toggle').click(function() {
            $(this).parent().toggleClass('show');
            $(this).html($(this).parent().hasClass('show') ? 'hide filters' : 'view filters');
        });
    }
    
    /*
     * Gallery slider
     */
    if ($('ul.thumbs li').length > 3) {
    $('.slideshow-thumbs').prepend('<div class="nav-left" />');
    $('.slideshow-thumbs').prepend('<div class="nav-right active" />');
    
    sliderPos = 0;
        function slideTo(pos) {
            if (pos >= 0 && pos <= $('ul.thumbs li').length-3) {
                sliderPos = pos;
                $('ul.thumbs').animate({
                    left: (pos * $('ul.thumbs li').width())*-1
                },200);
            }
        }
        $('.nav-right').live('click',function(){
            slideTo(sliderPos+1);
            /*$('ul.thumbs').animate({
                left: '-=' + $('ul.thumbs li').width()
            }, 200, function() {
                $('.nav-left').addClass('active');
                if ((parseInt($(this).css('left'))*-1) >= ($(this).width() - ($('ul.thumbs li').width()*3))){
                    $('.nav-right').removeClass('active');
                }
            });*/
        });
        $('.nav-left').live('click',function(){
            slideTo(sliderPos-1);
            /*$('ul.thumbs').animate({
                left: '+=' + $('ul.thumbs li').width()
            }, 200, function() {
                $('.nav-right').addClass('active');
                if (parseInt($(this).css('left')) >= 0){
                    $('.nav-left').removeClass('active');
                    
                }
            });*/
        });
    }
    
    if ($('ul.thumbs')) {
        $('ul.thumbs').width($('ul.thumbs li').length * $('ul.thumbs li').width());
    }
});
function loadScript() {
    var script = document.createElement("script");
    script.type = "text/javascript";
    script.src = "http://maps.google.com/maps/api/js?sensor=false&callback=initializeGMap";
    document.body.appendChild(script);
}

var map       = null;
var locations = [];

function initializeGMap() {
    geocoder = new google.maps.Geocoder();
    
    geocoder.geocode( {'address': $('#google-map').attr('ref') }, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            var myLatlng = new google.maps.LatLng(results[0].geometry.location.lat(),results[0].geometry.location.lng());
            var myOptions = {
                zoom: 16,
                center: myLatlng,
                mapTypeId: google.maps.MapTypeId.ROADMAP
            };
            map = new google.maps.Map(document.getElementById("google-map"), myOptions);
            marker = new google.maps.Marker({
                map: map,
                position: myLatlng,
                icon: '/asset/img/splash_new/map_icons/lugtons.png'
            });
            $('#google-map').show();
            
            google.maps.event.addListener(map, 'idle', function() {
                updateFilters();
            });
        }
    });
    
    if ($('.map-type-filters').length) {
        $('.map-type-filters').change(function(event) {
            updateFilters();
        });
    }
}
function updateFilters() {
    var types = [];
    $('.map-type-filters:checked').each(function() {
        types.push($(this).val());
    });
    var bounds = {
        ne: {lat: map.getBounds().getNorthEast().lat(), lng: map.getBounds().getNorthEast().lng()},
        sw: {lat: map.getBounds().getSouthWest().lat(), lng: map.getBounds().getSouthWest().lng()}
    };
    
    var url = '/location.php';
    var data = {
        bounds: bounds,
        types: types
    };
    var success = function(data) { showLocations(data); };
    var error   = function(data) { alert('An error occured while filtering locations'); };
    
    $.ajax({
        url:      url,
        data:     data,
        type:     'POST',
        dataType: 'json',
        async:    true,
        success:  success,
        error:    error
    });
}
var addMarker = function(point, text, map, html, icon) {
    var options = {
        position: point,
        title:    text,
        map:      map
    };
    
    if (html.length) options.html = html;
    if (icon.length) options.icon = '/asset/img/splash_new/map_icons/' + icon;
    
    var marker = new google.maps.Marker(options);
    
    return marker;
};
function showLocations(data) {
    var newlocations = [];
    var point = null;
    
    var name, latitude, longitude, type, icon, description, html;
    
    for (var index in data) {
        name        = data[index].name != undefined        ? data[index].name        : '';
        latitude    = data[index].latitude != undefined    ? data[index].latitude    : '';
        longitude   = data[index].longitude != undefined   ? data[index].longitude   : '';
        type        = data[index].type != undefined        ? data[index].type        : '';
        icon        = data[index].icon != undefined        ? data[index].icon        : '';
        description = data[index].description != undefined ? data[index].description : '';
        html        = '<p><strong>' + name + '</strong><br />' + description;
        
        if (name.length && latitude.length && longitude.length) {
            point = new google.maps.LatLng(latitude, longitude);
            
            found = false;
            for (var marker in locations) {
                if (locations[marker].getTitle() == name && locations[marker].getPosition().lat() == point.lat() && locations[marker].getPosition().lng() == point.lng()) {
                    //newlocations.push(locations[marker]);
                    found = true;
                }
            }
            
            if (!found) {
                marker = addMarker(
                    point,
                    name,
                    map,
                    html,
                    icon
                );
                var infowindow = new google.maps.InfoWindow({});
                google.maps.event.addListener(marker, 'click', function() {
                    infowindow.setContent(this.html);
                    infowindow.open(map, this);
                });
                //newlocations.push(marker);
                locations.push(marker);
            }
        }
    }
    
    /*
    for (var a in locations) {
        found = false;
        for (var b in newlocations) {
            if (locations[a].getTitle() == newlocations[b].getTitle() && locations[a].getPosition().lat() == newlocations[b].getPosition().lat() && locations[a].getPosition().lng() == newlocations[b].getPosition().lng()) {
                found = true;
            }
        }
        if (!found) {
            locations[a].setMap(null);
        }
    }
    
    locations = newlocations;
    */
}
function popUp(URL) {
    day = new Date();
    id = day.getTime();
    eval("page" + id + " = window.open(URL, '" + id + "', 'toolbar=0,scrollbars=1,location=0,statusbar=1,menubar=1,resizable=1,width=700,height=500,left = 320,top = 272');");
}

function newWindow(mypage,w,h){
    var winl = (screen.width-w)/2;
    var wint = (screen.height-h)/2;
    var settings ='height='+h+',';
    settings +='width='+w+',';
    settings +='top='+wint+',';
    settings +='left='+winl+',';
    settings +='toolbar=0,scrollbars=1,location=0,statusbar=1,menubar=1,resizable=1';
    day = new Date();
    id = day.getTime();
    win=window.open(mypage,id,settings);
    if(parseInt(navigator.appVersion) >= 4){win.window.focus();}
}

function changepic(imgFile) {
    document.image_main.src = imgFile;
}

$.fn.ajaxSubmit = function(e) {     
    /* Change a form's submission type to ajax */
    this.submit(function(){
                         
    var params = {};
    $(this)
    .find("input[@checked], input[@type='text'], input[@type='hidden'], input[@type='password'], input[@type='submit'], option[@selected], textarea")
    .filter(":enabled")
    .each(function() {
      params[ this.name || this.id || this.parentNode.name || this.parentNode.id ] = this.value;
    });
    $("body").addClass("curWait");
    
        $.post(this.getAttribute("action") + "&call=ajax", params, function(xml){
            $("body").removeClass("curWait");
            strError = "Unable to submit form. Please try again later.";
            oFocus = null;
            $("AjaxResponse", xml).each(function() {
                //strRedirect = this.getAttribute("redirecturl");
                strError = this.getAttribute("error");
                strMessage = this.getAttribute("message");
                oFocus = this.getAttribute("focus");
            });
            
            if (strError.length == 0) {
                $("div.formErrors").hide();
                $("div.formMessage").html("<h5>Success!<\/h5><div class=\"close\"><a href=\"javascript:void(0);\" onclick=\"$('div.formMessage').fadeOut('normal');\">X</a></div><p>" + strMessage + "<\/p>").filter(":hidden").fadeIn("normal");
            } else {
                $("div.formMessage").hide();
                $("div.formErrors").html("<h5>Error<\/h5><div class=\"close\"><a href=\"javascript:void(0);\" onclick=\"$('div.formErrors').fadeOut('normal');\">X</a></div><ul>" + strError.replace(/(\t)(.+)/g, "<li>$2<\/li>") + "<\/ul>").filter(":hidden").fadeIn("normal");
                if (oFocus) $("#" + oFocus).get(0).focus();
            }
        });
        return false;
    }); 
    return this;
}

function startSearch(new_order) {
    if( $('#quick_search').length > 0 ){
        $("#order_by").attr("value",new_order); 
        $("#quick_search").submit();
    }
}

function setRef(ref_no) {
    if( $('#quick_search').length > 0 ){
        $("#propertyref").attr("value",ref_no);
    }
}
    
function orderRental(new_order) {
    window.location = "rental_hamilton.php?order_by="+new_order;    
}
