(function($)

{  

    $.darkScreen = function() 

    {     

        var div = $('<div></div>');



        div

            .css('position','absolute')

            .css('top','0px')

            .css('left','0px')

            .css('filter','alpha(opacity=70)')

            .css('opacity','0.7')

            .css('width', Math.max(window.document.documentElement.offsetWidth, window.document.body.offsetWidth) + "px")

            .css('height',Math.max(window.document.documentElement.offsetHeight,window.document.body.offsetHeight) + "px")

            .css('background','black')

            .css('zIndex',100);



        $.darkScreen.div = div;



        $('body').append(div);

        

        return this;    

    };



    $.darkScreenOff = function()

    {

        $.darkScreen.div.remove();

    }



    $.bigView = function()

    {

        var div = $('<div id="imgHolder"><img src="" id="listingImage" /></div>');



        div

            .css('display',   'none')

            .css('position',  'absolute')

            .css('top',       0)

            .css('left',      0)

            .css('padding',   '5px')

            .css('border',    '1px solid #F36F21')

            .css('background','white')



        $('img.view')

            .mouseover(function(ev)

            {

                var e = window.event || ev;



                var scrollTop = Math.max(window.document.documentElement.scrollTop,window.document.body.scrollTop);



                if($(this).attr('full').length > 2)

                {

                    $('#listingImage').attr('src', $(this).attr('full'));

                    

                    div

                        //.css('display','block')

                        .css('left', e.clientX+10+'px')

                        .css('top',  e.clientY+scrollTop+10+'px')



                    div.show(300);

                }

            })

            .mouseout(function()

            {

                //div.css('display','none');

                div.hide(300);

                $('#listingImage').attr('src', '');

            })

            .mousemove(function(ev)

            {

                var e = window.event || ev;



                var scrollTop = Math.max(window.document.documentElement.scrollTop,window.document.body.scrollTop);



                div

                    .css('display','block')

                    .css('left',e.clientX+10+'px')

                    .css('top',e.clientY+scrollTop+10+'px')            

            })



        $('body').append(div);

    }



})(jQuery); 





function checkEmail(email)

{

    var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;

    return filter.test(email);

}



function checkPhone(str) 

{

//	var phone2 = /^(\+\d)*\s*(\(\d{3}\)\s*)*\d{3}(-{0,1}|\s{0,1})\d{2}(-{0,1}|\s{0,1})\d{2}$/; 

//	if (str.match(phone2)) {

//   		return true;

// 	} else {

// 		return false;

// 	}



	return (str.length >= 7 );

}





var listOfsetDelta = 7;

var interval;



function clInterval()

{

    clearInterval(interval);

}



$(document).ready(function()

{    



    $.bigView();



    if($.fn.lightBox)  $('#trueContainer a').lightBox();



    if($.fn.jcarousel) $('#carousel').jcarousel({

            size:5, 

            scroll:1

    });

    



    $('#scrolldown_condos').mousedown(function()

    {        

        var max = $('#list_condos').height() - $('.scrollbox').height();

        interval = setInterval(function()

        {

            var ofs = parseInt($('#list_condos').attr('ofs'));

            ofs -= listOfsetDelta;



            if(max + ofs < 0)

            {

                clearInterval(interval);

                return;

            }



            $('#list_condos').css('margin-top',ofs + 'px');

            $('#list_condos').attr('ofs',ofs);        

        },1);

    });



    $('#scrollup_condos').mousedown(function()

    {        

        interval = setInterval(function()

        {

            var ofs = parseInt($('#list_condos').attr('ofs'));

            if(ofs > 0) return;

            ofs += listOfsetDelta;



            if(ofs > 0)

            {

               clearInterval(interval);

               return;

            }



            $('#list_condos').css('margin-top',ofs + 'px');

            $('#list_condos').attr('ofs',ofs);        

        },1);

    });



    $('#scrolldown_homes').mousedown(function()

    {        

        var max = $('#list_homes').height() - $('.scrollbox').height();

        interval = setInterval(function()

        {

            var ofs = parseInt($('#list_homes').attr('ofs'));

            ofs -= listOfsetDelta;



            if(max + ofs < 0)

            {

                clearInterval(interval);

                return;

            } 



            $('#list_homes').css('margin-top',ofs + 'px');

            $('#list_homes').attr('ofs',ofs);        

        },1);

    });



    $('#scrollup_homes').mousedown(function()

    {        

        interval = setInterval(function()

        {

            var ofs = parseInt($('#list_homes').attr('ofs'));

            if(ofs > 0) return;            

            ofs += listOfsetDelta;



            if(ofs > 0)

            {

               clearInterval(interval);

               return;

            }



            $('#list_homes').css('margin-top',ofs + 'px');

            $('#list_homes').attr('ofs',ofs);        

        },1);

    });



    $('#scrolldown_condos, #scrollup_condos, #scrolldown_homes, #scrollup_homes').mouseup(clInterval).mouseout(clInterval);



    communityFilter();

    $('#ptype').change(communityFilter);



    var city = $('#city').val();



    $('a[t=cT]').click(function()

    {

        var community = $(this).html();

        location.href = 'http://www.ebeyhomes.com/results.php?ptype=CT&city='+city+'&community='+community

        return false;

    });



    $('a[t=s]').click(function()

    {

        var community = $(this).html();

        location.href = 'http://www.ebeyhomes.com/results.php?ptype=S&city='+city+'&community='+community

        return false;

    });





    $('a#quickSearch').click(function()

    {

        $(this).addClass('active');

        $('a#rentals').removeClass('active');

        $('#centerContent').css('height', '536px');

        //$('#rightContent').css('height',  '710px');

        $('#searchform .rental').hide();

        $('#searchform .residential').show();

        

        $('#typeForm').val('quick');



        $('#minprice option[t=res]').show();

        $('#minprice option[t=rnt]').hide();



        $('#maxprice option[t=res]').show();

        $('#maxprice option[t=rnt]').hide();



        return false;

    });

    



    $('a#rentals').click(function()

    {        

        $(this).addClass('active');

        $('a#quickSearch').removeClass('active');

        $('#centerContent').css('height', 'auto');

        //$('#rightContent').css('height',  '980px');

        $('#searchform .rental').show();

        $('#searchform .residential').hide();

        $('#typeForm').val('rental');



        $('#minprice option[t=res]').hide();

        $('#minprice option[t=rnt]').show();



        $('#maxprice option[t=res]').hide();

        $('#maxprice option[t=rnt]').show();



        return false;

    });



    var formType = $('#typeForm').val();

    

    if(formType == 'rental') 

        $('a#rentals').click();

    else 

        $('a#quickSearch').click();



    $('.map').click(function()

    {

        $.darkScreen();

         

        var width     = Math.max(window.document.documentElement.offsetWidth,  window.document.body.offsetWidth);

        var height    = Math.max(window.document.documentElement.offsetHeight, window.document.body.offsetHeight);

        var scrollTop = Math.max(window.document.documentElement.scrollTop,    window.document.body.scrollTop);



        var formWidth  = 500;

        var formHeight = 300;



        $('#map')

            .css('left'   , ((width / 2 - formWidth / 2) + 'px'))

            .css('top'    , scrollTop + 60 + 'px' )

            .show()



        //$('#mapHolder').html($(this).attr('address'));

        load();

        return false;

    });



    $('#close').click(function()

    {

        $.darkScreenOff();

        $('#map').hide();

        return false;

    });



});





function communityFilter()

{

    var ptype = $('#ptype').val();

    var community= $('#communityName').val();

    

    if(ptype == 'A')

    {

        //disable all repeated options

        $('#community option').show();

        $('#community option[noUniq = 1]').hide();

    }

    else

    {

        //disable all not needed options

        $('#community option').show();

        $('#community option[subType != '+ptype+']').hide();

        $('#community option[any=1]').show();

    }

    

    $('#community option[value="'+community+'"]').attr('selected',true);

}



//-------------------------------------------------------

function emailToFrind(id)

{

    $.darkScreen();

    formatForm('<img id="clock" src="/images/clock.gif" />');

    $.get('/ajax/emailForm.php',{'id':id},function(data)

    {

        $('#clock').remove();

        formatForm(data);

        

        

        $('#send').click(function()

        {



            var ok = require([$('#emailto').val(), $('#name').val(), $('#subject').val()]);

            if(!ok)

            {

                alert('Please, fill all fields in form.');

                return;

            }														



            var params = 

            {

                emailto  : $('#emailto').val(),

                name     : $('#name').val(),

                subject  : $('#subject').val(),

                comments : $('#comments').val(),

                url      : 'http://ebeyhomes.com/details.php/?id='+id

            }



            $.get('/ajax/emailHandler.php',params,function(res)

            {

                if(res == 'ok') alert('Email was succesfully send to: '+params.emailto);

                else alert(res);

                clear(); 

            });





        });

    });

    

}



//-------------------------------------------------------



function formatForm(data)

{

    var form = $(data);

    $('body').append(form);

    

    var width     = Math.max(window.document.documentElement.offsetWidth,  window.document.body.offsetWidth);

    var height    = Math.max(window.document.documentElement.offsetHeight, window.document.body.offsetHeight);

    var scrollTop = Math.max(window.document.documentElement.scrollTop,    window.document.body.scrollTop);



    var formWidth  = form.width();

    var formHeight = form.height();



    form

        .css('left' , ((width / 2 - formWidth / 2) + 'px'))

        .css('top'  , scrollTop + 60 + 'px' )

        

    return form;

}





//-------------------------------------------------------



function scheduleShowing(id)

{

    $.darkScreen();

    formatForm('<img id="clock" src="/images/clock.gif" />'); 



    $.get('/ajax/scheduleForm.php',{'id':id},function(data)

    {

        $('#clock').remove();

        formatForm(data);



        $('#send').click(function()

        {

            var ok = require([$('#name').val(), $('#email').val(), $('#phone2').val(), $('#listingId').val()]);



            if(!ok)

            {

                alert('Please, fill all fields in form.');

                return;

            }

			

			var email = checkEmail($('#email').val());

			var phone = checkPhone($('#phone2').val());



			if(! (email || phone))

			{

				alert('Please, fill correct email or phone field ');

				return;

			}





            var params = 

            {

                name       : $('#name').val(),

                email      : $('#email').val(),

                phone      : $('#phone2').val(),

                listingId  : $('#listingId').val(),

                comments   : $('#comments').val(),

                preference : ( $('#preferencePhone').attr('checked') == true ) ? 'Phone' : 'Email'

            }



            $.get('/ajax/scheduleHandler.php',params,function(res)

            {

                if(res == 'ok') alert('Request was succesfully send');

                else alert(res);

                clear(); 

            });

        });

    });

        

}

//-------------------------------------------------------



function require(a)

{

    for(var k in a)

    {

        if(a[k] == '' || a[k] == null)

        {            

            return false;

        }

    }



    return true;

}





function requestMoreInfo(id)

{

    $.darkScreen();

    formatForm('<img id="clock" src="/images/clock.gif" />'); 

    $.get('/ajax/requestForm.php',{'id':id},function(data)

    {

        $('#clock').remove();

        formatForm(data);



        $('#send').click(function()

        {

            var ok = require([$('#name').val(), $('#email').val(), $('#phone2').val(), $('#listingId').val()]);



            if(!ok)

            {

                alert('Please, fill all fields in form.');

                return;

            }



			var email = checkEmail($('#email').val());

			var phone = checkPhone($('#phone2').val());



			if(! (email || phone))

			{

				alert('Please, fill correct email or phone field ');

				return;

			}





            var params = 

            {

                name       : $('#name').val(),

                email      : $('#email').val(),

                phone      : $('#phone2').val(),

                listingId  : $('#listingId').val(),

                comments   : $('#comments').val(),

                preference : ( $('#preferencePhone').attr('checked') == true ) ? 'Phone' : 'Email'

            }



            $.get('/ajax/requestHandler.php',params,function(res)

            {

                if(res == 'ok') alert('Request was succesfully sended');

                else alert(res);

                clear(); 

            });

        });

    });

    

}

//-------------------------------------------------------

function calculator(id)

{

    $.darkScreen();

    formatForm('<img id="clock" src="/images/clock.gif" />'); 

    $.get('/ajax/calcForm.php',{'id':id},function(data)

    {

        $('#clock').remove();    

        formatForm(data);



        $('#send').click(function()

        {

            alert(1);

            clear();

        });

    });

    

}



function clear()

{

    $.darkScreenOff();

    $('#topForm').remove();

}



function load()

{

    if (GBrowserIsCompatible()) 

    {

        var map = new GMap2(document.getElementById("mapHolder"));

        var geocoder = new GClientGeocoder();



        function showAddress(address) {

          geocoder.getLatLng(

            address,

            function(point) {

              if (!point) {

                //alert(address + " not found");

              } else {

                map.setCenter(point, 15);

                var marker = new GMarker(point);

                map.addOverlay(marker);

                //marker.openInfoWindowHtml(address);

              }

            }

          );

        }



		map.addControl(new GSmallMapControl());

        map.addControl(new GMapTypeControl());   

        

        showAddress($('.map').attr('address'));

    }



}


