var map;
var geocoder = null;
var IMAGES = ["home", "heighth_home" ];
var ICONS = [];
var mgr = null;
var is_pagination = false;
var nMax = 100;
var fnc=new Array();
var defaultZoom = 15;
var mark = new Array();
var data = new Array();
//var getFavoritesUrl = "";
var getListingByIdUrl = "";
var getPropertyDetailsUrl = "";
var type="";

function initialize(point) {
    if (GBrowserIsCompatible()) {
        map = new GMap2(document.getElementById("map_view"));
        if (!point)
            point = new GLatLng(33.448263, -112.073821);
        map.setCenter(point, defaultZoom);
        //map.addControl(new GMapTypeControl());
       map.addControl(new GLargeMapControl());
    var mapControl = new GMapTypeControl();
    map.addControl(mapControl);
		
		
    /*
            var bounds = map.getBounds();
            var southWest = bounds.getSouthWest();
            var northEast = bounds.getNorthEast();
            var lngSpan = northEast.lng() - southWest.lng();
            var latSpan = northEast.lat() - southWest.lat();
            for (var i = 0; i < 5; i++) {
                var point = new GLatLng(southWest.lat() + latSpan * Math.random(),
                southWest.lng() + lngSpan * Math.random());
                map.addOverlay(createMarker(point, i + 1));
            }*/
    }
}

function myinit(point){
    initialize(point);
}

function mapaddOverlay(marker) {
    map.addOverlay(marker);
}

jQuery(document).ready(function() {
    /*
    $("#price_slider").slider({
        range: true,
        min: 0,
        max: 2000000,
        values: [0, 2000000],
        slide: function(event, ui) {
            $("#minprice").val(ui.values[0]);
            $("#maxprice").val(ui.values[1]);
        }
    });

    $("#beds_slider").slider({
        range: "min",
        value: 0,
        min: 0,
        max: 5,
        slide: function(event, ui){
            $("#beds").val(ui.value);
        }
    });
    var minbed = $("#beds_slider").slider('option', 'min');
    var maxbed = $("#beds_slider").slider('option', 'max');
    $("#beds").blur(function(){
        var slider1Value = $("#beds").attr("value");
        if(slider1Value >= minbed && slider1Value <= maxbed){
            $('#beds_slider').slider('option', 'value',slider1Value );
        }else{
            alert('Please enter a value between ' +minbed+ ' and '+maxbed);
            return false;
        }
    });
    $("#beds_slider").slider('option', 'value', $("#beds").val());

    $("#baths_slider").slider({
        range: "min",
        value: 0,
        min: 0,
        max: 5,
        slide: function(event, ui) {
            $("#baths").val(ui.value);
        }
    });
    var minbath = $("#baths_slider").slider('option', 'min');
    var maxbath = $("#baths_slider").slider('option', 'max');
    $("#baths").blur(function(){
        var slider2Value = $("#baths").attr("value");
        if(slider2Value >= minbed && slider2Value <= maxbed){
            $('#baths_slider').slider('option', 'value',slider2Value );
        }else{
            alert('Please enter a value between ' + minbath + ' and '+ maxbath);
            return false;
        }
    });
    $("#baths_slider").slider('option', 'value', $("#baths").val());

    $("#slider-range-sq").slider({
        range: true,
        min: 0,
        max: 5000,
        values: [0, 5000],
        slide: function(event, ui) {
            $("#minsq").val( ui.values[0]);
            $("#maxsq").val(ui.values[1]);
        }
    });

    $("#minsq").blur(function(){
        var vl = $("#minsq").attr("value");
        alert("Gia tri min Square feet: "+ vl);
        var vl1 = 199;

        alert("Gia tri min Square feet: "+ vl1);

        $("#slider-range-sq").slider('option', 'values', [19,199]);

    });


    $("#slider-range-ls").slider({
        range: true,
        min: 0,
        max: 20000,
        values: [0, 20000],
        slide: function(event, ui) {
            $("#minls").val( ui.values[0]);
            $("#maxls").val(ui.values[1]);
        }
    });


    $("#slider-range-right").slider({
        range: "min",
        value: 0,
        min: 0,
        max: 20,
        slide: function(event, ui) {
            $("#baths").val(ui.value);
        }
    });
*/
    $("#tabs_panel").tabs();
    $("#right_panel").tabs({
        select: function(event, ui) {
            if (ui.index == 1) {
                
        }
        }
    });    
    $("#areaID div#right_panel").tabs({
        select: function(event, ui) {
            if (ui.index == 1) {
                
        }
        }
    });
    jQuery("#extrainfor").click(function () {
      jQuery("#inforextra").toggle();
	  var extra = $("#extrainfor").html();

	  if (extra=='MORE SEARCH OPTIONS')
		var textinfor="FEWER SEARCH OPTIONS";
		else textinfor="MORE SEARCH OPTIONS";
	  jQuery("#extrainfor").html(textinfor);
    });

    jQuery("#extrainfor1").click(function () {
      jQuery("#inforextra1").toggle();
    });
        
    var options = {
        dataType:       'json',
        //target:        '',   // target element(s) to be updated with server response
        beforeSubmit:  showRequest,  // pre-submit callback
        success:       showResponse  // post-submit callback

    // other available options:
    //url:       url         // override for form's 'action' attribute
    //type:      type        // 'get' or 'post', override for form's 'method' attribute
    //dataType:  null        // 'xml', 'script', or 'json' (expected server response type)
    //clearForm: true        // clear all form fields after successful submit
    //resetForm: true        // reset the form after successful submit

    // $.ajax options can be used here too, for example:
    //timeout:   3000
    };
    // bind form using 'ajaxForm'
    $('#form1').ajaxForm(options);
    
    geocoder = new GClientGeocoder();
    var address = "Kansas city";
    geocoder.getLatLng(address,
        function(point) {
            if (!point) {
                alert(address + " not found");
                myinit();
            } else {
                myinit(point);
            }
            
            
        });
});

function updateTips(t) {
    tips.text(t).effect("highlight",{},1500);
}

function checkLength(o,n,min,max) {

    if ( o.val().length > max || o.val().length < min ) {
        o.addClass('ui-state-error');
        updateTips("Length of " + n + " must be between "+min+" and "+max+".");
        return false;
    } else {
        return true;
    }

}
 function pageselectCallbackinfo(page_index, jq){

                    var items_per_page = 1;
                    var low = (page_index*items_per_page)-1;
                    var high = (page_index+1)*items_per_page;
                    var new_content;
                    if (low >= 0)
                        new_content = jQuery('#hiddenresultinfo div.iteminfo:lt('+high+'):gt('+low+')').clone();
                    else
                        new_content = jQuery('#hiddenresultinfo div.iteminfo:lt('+high+')').clone();
                  
                  // new_content += "<p><b>"+jQuery('#hiddenresultinfo div.iteminfo').length;+" found here </b></p>";
                    jQuery('#contentinfo').empty().append(new_content);
					$("#contentbound div#contentinfo div.iteminfo").click(function(event){		
								event.preventDefault();
								var url = getPropertyDetailsUrl + '/' + $(this).attr('mls_number'); 
								var callback=function(data){
									$("#property_details").html(data);
									window_loaded = true;
									$('#gallery').galleryView({
										panel_width: 341,
										panel_height: 256,
										frame_width: 75,
										frame_height: 50,
										transition_speed: 350,
										easing: 'easeInOutQuad',
										transition_interval: 0
									});
								}
								var type='text';
								jQuery.post(url, null, callback, type);
								$('#right_panel').tabs('select', 1);
								//Chuyen den tab hien thi chi tiet mot ket qua
								$('#areaID div#right_panel').tabs('select', 4);
								return false;
					});
					return false;

                    //var new_content = $('#hiddenresult div.info_video_play:eq('+page_index+')').clone();
                    //$('#video_list').empty().append(new_content);
                 
				 
                }

            /**
             * Callback function for the AJAX content loader.
             */
 function initPaginationinfo() {
                var num_entries = jQuery('#hiddenresultinfo div.iteminfo').length;
                // Create pagination element
                
                jQuery("#Paginationinfo").pagination(num_entries, {
                    num_edge_entries: 1,
                    num_display_entries: 2,
                    callback: pageselectCallbackinfo,
                    items_per_page:1
                });
				
             }


function checkRegexp(o,regexp,n) {
    if ( !( regexp.test( o.val() ) ) ) {
        o.addClass('ui-state-error');
        updateTips(n);
        return false;
    } else {
        return true;
    }
}
function createMarker(point, location) {
    var marker = new GMarker(point);
  // var temp = new Array();
    var mls_number ;
    var price ;
    var address;
    var county ;
    var city;
    var zip;
    var status;
    var subproperty_type;
    var list_office_name ;
  
    GEvent.addListener(marker, "click", function(overlay, latlng) {
    
        
             var myHtml = "<div id='contentbound'><div id='contentinfo'></div><div id='hiddenresultinfo' style='display:none;'>";
             
             var properties_count = 0;
             for (var i = 0;i<data.length;i++)
              {
            //   alert(location.lat + " " + location.lng+" "+data[i].lat+" "+data[i].lng);
               if ((data[i].lat == location.lat)&&(data[i].lng == location.lng))
                 {
                 //   alert("Vao");
                    mark[i] = 1;
                    properties_count++;
                    temp = data[i];
                    mls_number = temp['mls number'];
                    price = temp['price'];
                    address = temp['street number']+' '+temp['street direction']+' '+temp['street']+' '+temp['street type'];

                    county = temp['county id'];
                    city = temp['city'];
                    zip = temp['zip'];
                    status = temp['status'];
                    subproperty_type = temp['subproperty type'];
                    list_office_name = temp['list office name'];
                    myHtml += "<div class='iteminfo' mls_number='"+mls_number+"' style='cursor:pointer'><div class='informarker'><div class='headmarker'>"+address+' '+ county+' '+ city+' '+ zip +"</div>"+
                    "<div class='pricemarker'>Price: <font class='fontmarker'>$"+price+"</font><br /></div>"+
                    "<div class='imgmarker'><img width='90px' height='90px' src='"+staticUrl+"Photo/"+mls_number+".0.jpg' alt='No image' /></div>"+
                    "<div class='contenmarker'>Status: "+status+" </div>"+
                    "<div class='contenmarker'>Type: "+subproperty_type+" </div>"+
					"<div class='contenmarker'>MLS Number: "+mls_number+" </div>"+
                    "<div class='contenmarker'>Listing provided by: "+list_office_name+"</div></div></div>";
                   
                 }
              }
             
                 myHtml +="</div><div id='Paginationinfo' class='pagination'> </div><div id='numlisting'><p><b>"+properties_count+" properties found here</b></p></div></div>";


                     //alert(myHtml);
                   var pos = new GLatLng(location.lat,location.lng);
                     map.openInfoWindowHtml(pos,myHtml, {
                        onOpenFn: function() {
                            //alert("Vao ham open roi");
                            initPaginationinfo();
                                }
                            }
                        );
             
        //}
         
        //myTimer=setTimeout('fnc[0]();', 300);
    });

   
    return marker;
}
function overinfor(ordernumber){
    var temp = data[ordernumber];
    var point = new GLatLng(temp.lat,temp.lng);
    var mls_number = temp['mls number'];
    var price = temp['price'];
    var address = temp['street number']+' '+temp['street direction']+' '+temp['street']+' '+temp['street type'];
    var county = temp['county id'];
    var city = temp['city'];
    var zip = temp['zip'];
    var status = temp['status'];
    var subproperty_type = temp['subproperty type'];
    var list_office_name = temp['list office name'];
    var myHtml = "<div id='clickinfor'><div class='informarker' style='border:1px solid #666666; cursor:pointer'><div class='headmarker'>"+address+' '+ county+' '+ city+' '+ zip +"</div>"+
                    "<div class='pricemarker' style='margin-top:10px;'>Price: <font class='fontmarker'>$"+price+"</font><br /></div>"+
                    "<div class='imgmarker'><img width='80px' height='70px' src='"+staticUrl+"Photo/"+mls_number+".0.jpg' alt='No image' /></div>"+
                    "<div class='contenmarker'>Status: "+status+" </div>"+
                    "<div class='contenmarker'>Type: "+subproperty_type+" </div>"+
					"<div class='contenmarker'>MLS Number: "+mls_number+" </div>"+
                    "<div class='contenmarker'>Listing provided by: "+list_office_name+"</div></div></div>";
     map.panTo(point);
     map.openInfoWindowHtml(point,myHtml);
	 //Click ling anh link den detail
    $("#clickinfor div.informarker").click(function(event){		
        event.preventDefault();
        var url = getPropertyDetailsUrl + '/' + mls_number;
        var callback=function(data){
            $("#property_details").html(data);
            window_loaded = true;
            $('#gallery').galleryView({
                panel_width: 341,
                panel_height: 256,
                frame_width: 75,
                frame_height: 50,
                transition_speed: 350,
                easing: 'easeInOutQuad',
                transition_interval: 0
            });
        }
        var type='text';
        jQuery.post(url, null, callback, type);
        $('#right_panel').tabs('select', 1);
        //Chuyen den tab hien thi chi tiet mot ket qua
        $('#areaID div#right_panel').tabs('select', 4);
        return false;
    });
	
}
function showRequest(formData, jqForm, options) {
       
    // formData is an array; here we use $.param to convert it to a string to display it
    // but the form plugin does this for you automatically when it submits the data
    //var queryString = $.param(formData);
    // jqForm is a jQuery object encapsulating the form element.  To access the
    // DOM element for the form do this:
    // var formElement = jqForm[0];

    //alert('About to submit: \n\n' + queryString);

    // here we could return false to prevent the form from being submitted;
    // returning anything other than false will allow the form submit to continue
    var bound = map.getBounds();
    var sw = bound.getSouthWest();
    var ne = bound.getNorthEast();
    var minLat = sw.lat();
    var maxLat = ne.lat();
    var minLng = sw.lng();
    var maxLng = ne.lng();
    var zoom = map.getZoom();

    $("#form1 input[name=minlat]").val(minLat);
    $("#form1 input[name=maxlat]").val(maxLat);
    $("#form1 input[name=minlng]").val(minLng);
    $("#form1 input[name=maxlng]").val(maxLng);
    $("#form1 input[name=zoom]").val(zoom);
    var tmpArr = jqForm.formToArray(options.semantic);
    for (var i = 0; i < tmpArr.length; i++) {
        formData[i] = tmpArr[i];
    }
    /*    formData[] = minLat;
    formData[] = maxLat;
    formData[] = minLng;
    formData[] = maxLng;
    formData[] = zoom;*/
    return true;
}

// post-submit callback
function showResponse(result)  {
    // for normal html responses, the first argument to the success callback
    // is the XMLHttpRequest object's responseText property

    // if the ajaxForm method was passed an Options Object with the dataType
    // property set to 'xml' then the first argument to the success callback
    // is the XMLHttpRequest object's responseXML property

    // if the ajaxForm method was passed an Options Object with the dataType
    // property set to 'json' then the first argument to the success callback
    // is the json data object returned by the server

    //alert('status: ' + statusText + '\n\nThe output div should have already been updated with the responseText.');
	//alert("Vao show res");
    var count = result.count;   
    getPropertyDetailsUrl = result.link;
    //getFavoritesUrl = result.getFavoritesUrl;
    map.clearOverlays();
    type = result.type;
    if (count == 0) {
        $('#areaID div#right_panel').tabs('select', 2);
        $('#areaID div#allSearchResults').html(result.view);
        $("#noresult").show();
        $("#yesresult").hide();
    }
    else {
        $("#noresult").hide();
        $("#yesresult").show();
        if (count > nMax) {
            //alert(count);
            map.count = count;
            if (map.msgCtr) map.removeControl(map.msgCtr);
            map.msgCtr = new MessageControl(map);
            map.addControl(map.msgCtr);
        } else {		
		//	alert(type);
			if (type){	
			//	alert("Vao map");
				if (map.msgCtr) map.removeControl(map.msgCtr);
				data = result.data;
				if(type != '3') {
					var point = new GLatLng(data[0].lat,data[0].lng);
					map.panTo(point);
				}
				for (var i = 0;i<data.length;i++)
					 {
						mark[i] = 0;
					 }
				for (i=0; i<data.length; i++)
					if (!mark[i])
					{
					var temp=data[i];
					var lat = temp.lat;
					var lng = temp.lng;

					var latlng = new GLatLng(lat,lng);
				   
					var marker = createMarker(latlng, temp);

					mapaddOverlay(marker);
				}
			}
            $('#tabs_panel').tabs('select', 0);
            $('#right_panel').tabs('select', 0);
            $('#areaID div#right_panel').tabs('select', 2);
            $('#allSearchResults').html(result.view);
            initPagination();
        }
        
    }

}

function pageselectCallback(page_index, jq){
    //var typepagination = jq.opts.typepagination;
    var items_per_page = 8;
    var low = (page_index*items_per_page)-1;
    var high = (page_index+1)*items_per_page;
    var new_content;
    if (low >= 0)
        new_content = $('#allSearchResults div.result:lt('+high+'):gt('+low+')').clone();
    else
        new_content = $('#allSearchResults div.result:lt('+high+')').clone();
        $('#viewSearchResults').empty().append(new_content);
        $("#viewSearchResults a.addFavorite").click(function(event){
        event.preventDefault();
        var url = $(this).attr('href');
        var callback=function(data){
            var currentPage = $("#pagination2 span.current:last").text();
            if (currentPage == 'Next')
                currentPage = '1';
            currentPage = parseInt(currentPage)-1;
            if (data=='success') 
                {
                    alert(" You have just added a property as your favorite successful!");
                    reloadFavorite();
                }
            else if (data=='not_authenticate') alert('Please login before using this feature!');
        }
        var type='text';
        jQuery.post(url, null, callback, type);
        return false;
    });
    $("#viewSearchResults div.item div.header").click(function(event){
        event.preventDefault();        
        var url = getPropertyDetailsUrl + '/' + $(this).parent().attr('mls_number');       
        var callback=function(data){
            $("#property_details").html(data);
            window_loaded = true;
            $('#gallery').galleryView({
                panel_width: 341,
                panel_height: 256,
                frame_width: 75,
                frame_height: 50,
                transition_speed: 350,
                easing: 'easeInOutQuad',
                transition_interval: 0
            });
        }
        var type='text';
        jQuery.post(url, null, callback, type);
        $('#right_panel').tabs('select', 1);
        //Chuyen den tab hien thi chi tiet mot ket qua
        $('#areaID div#right_panel').tabs('select', 4);
        return false;
    });
    
    //Click ling anh link den detail
    $("#viewSearchResults div.item div.image").click(function(event){
        event.preventDefault();
        var url = getPropertyDetailsUrl + '/' + $(this).parent().attr('mls_number');
        var callback=function(data){
            $("#property_details").html(data);
            window_loaded = true;
            $('#gallery').galleryView({
                panel_width: 341,
                panel_height: 256,
                frame_width: 75,
                frame_height: 50,
                transition_speed: 350,
                easing: 'easeInOutQuad',
                transition_interval: 0
            });
        }
        var type='text';
        jQuery.post(url, null, callback, type);
        $('#right_panel').tabs('select', 1);
        //Chuyen den tab hien thi chi tiet mot ket qua
        $('#areaID div#right_panel').tabs('select', 4);
        return false;
    });
    return false;
}
function initPagination() {
    var num_entries = $('#allSearchResults div.result').length;
    // Create pagination element
    $("#pagination1").pagination(num_entries, {
        num_edge_entries: 2,
        num_display_entries: 2,        
        callback: pageselectCallback,
        items_per_page:8
    });
}
function reloadFavorite(pageNum) {   
    var url = getFavoritesUrl;
   // alert(url);
    var callback=function(data){
        $('#allfavorites').html(data.view);
        initFavoritePagination(pageNum);
    }
    var type='json';
    jQuery.post(url, null, callback, type);
    return false;
}

function pageselectCallback2(page_index, jq){
    //var items_per_page = jq.opts.items_per_page;
    var items_per_page = 8;
    var low = (page_index*items_per_page)-1;
    var high = (page_index+1)*items_per_page;
    var new_content;
    if (low >= 0)
        new_content = $('#allfavorites div.result:lt('+high+'):gt('+low+')').clone();
    else
        new_content = $('#allfavorites div.result:lt('+high+')').clone();
    $('#viewfavorite').empty().append(new_content);
    $("#viewfavorite a.removeFavorite").click(function(event){
        event.preventDefault();
        var url = $(this).attr('href');
        var callback=function(data){            
            if (data=='succees') {
                alert(" You have just removed a property as your favorite successful!");
                reloadFavorite(page_index);
            }
        }
        var type='text';
        jQuery.post(url, null, callback, type);
        return false;
    });
    return false;
}
function initFavoritePagination(pageNum) {
    if (pageNum == null) pageNum = 0;
    var num_entries = $('#allfavorites div.result').length;
    var maxPage = Math.ceil(num_entries/8)-1;
    if (pageNum > maxPage) pageNum = maxPage;
    // Create pagination element
    $("#pagination2").pagination(num_entries, {
        current_page: pageNum,
        num_edge_entries: 2,
        num_display_entries: 2,
        callback: pageselectCallback2,
        items_per_page:8
    });
}

// A TextualZoomControl is a GControl that displays textual "Zoom In"
// and "Zoom Out" buttons (as opposed to the iconic buttons used in
// Google Maps).

// We define the function first
function MessageControl() {
}

// To "subclass" the GControl, we set the prototype object to
// an instance of the GControl object
MessageControl.prototype = new GControl();

// Creates a one DIV for each of the buttons and places them in a container
// DIV which is returned as our control element. We add the control to
// to the map container and return the element for the map class to
// position properly.
MessageControl.prototype.initialize = function(map) {
    var count = map.count;
    var container = document.createElement("div");

    var zoomInDiv = document.createElement("div");
    this.setButtonStyle_(zoomInDiv);
    container.appendChild(zoomInDiv);
    //alert(count);
    zoomInDiv.innerHTML = count + '<br/>' + 'Properties Found';


    var zoomOutDiv = document.createElement("div");
    this.setButtonStyle_(zoomOutDiv);
    container.appendChild(zoomOutDiv);
    zoomOutDiv.innerHTML = 'More than 100 properties found. Please Zoom In or narrow Search Criteria to view Search Results.';
    map.getContainer().appendChild(container);
    return container;
}

// By default, the control will appear in the top left corner of the
// map with 7 pixels of padding.
MessageControl.prototype.getDefaultPosition = function() {
    return new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(7, 30));
}

// Sets the proper CSS for the given button element.
MessageControl.prototype.setButtonStyle_ = function(button) {
    //button.style.textDecoration = "underline";
    button.style.color = "#0000cc";
    button.style.backgroundColor = "rgb(255, 207, 49)";
    button.style.font = "small Arial";
    button.style.border = "1px solid black";
    button.style.padding = "2px";
    button.style.marginBottom = "3px";
    button.style.textAlign = "center";
    button.style.width = "12em";
    button.style.cursor = "pointer";
}



