/**
 * mred-tools.js
 *
 * This code handles the error checking and validation of the search widget 
 * This code also calls the jsearch php code to perform the search
 * Returned results are injected into the #searchresults div
 * Returned results include a map with all properties indicated.
 * 
 * 
 */ 

function pageselectCallback(page_index, jq){
    var new_content = jQuery('#hiddenresults div.listing:eq('+page_index+')').clone();
    jQuery('#Searchresult').empty().append(new_content);
    return false;
}
     
/** 
 * Callback function for the AJAX content loader.
 */
function initPagination() {
    var num_entries = jQuery('#hiddenresults div.listing').length;
    // Create pagination element
    jQuery("#listings-pagination").pagination(num_entries, {
        num_edge_entries: 1,
        num_display_entries: 10,
        items_per_page: 8,
        callback: pageselectCallback
    });
 }

jQuery(document).ready(function(){
	jQuery('#loading').fadeOut();
	jQuery('label#ziperror').fadeOut();
    var zip = jQuery('#zip').val();
    if(zip == '') {
      jQuery('#area-search').show();
    } else {
	 jQuery('#area-search').hide();
	}
	WidgetSearch();  
	mt_map_display();
  // This is where I'd put the jquery lightbox plugin hook...
});

/**
*
* Display a map of markers representing listing data
* This function reads a previously created xml file of latitude and longitude coordinates
* and places a Google map image with the markers displaying the coordinates
* predominantly for use with <domain>/zip/nnnnn pages
*
*
*/
function mt_map_display() {
if (jQuery('#searchresults_contents').length != 0) {
	jQuery('#searchresults_contents').ready(function() {
			//fadeAllDivs();
			jQuery('#searchresults_contents').fadeIn();
			var myLatlng = new google.maps.LatLng(41.760632,-88.143778);
			var myOptions = {
			  zoom: 12,
			  center: myLatlng,
			  mapTypeId: google.maps.MapTypeId.ROADMAP
			};            
			var infoWindow = new google.maps.InfoWindow;
			var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
	// find a way of limiting the data gather to maximum listings.
	// process data points / listings to add the map popups
			jQuery.get('/wp-content/uploads/maps.xml', function(data) {            
			  jQuery(data).find('marker').each(function() {              
				var listing_id = jQuery(this).attr('id');
				var area_name = jQuery(this).attr('area_name');
				var address = jQuery(this).attr('address');              
				var zip = jQuery(this).attr('zip');
				var lat = jQuery(this).attr('lat');
				var lng = jQuery(this).attr('lng');
				var point = new google.maps.LatLng( lat, lng);                
				var pic_url = jQuery(this).attr('mainpic');
				var price = jQuery(this).attr('price');
				var description = jQuery(this).attr('description');
				var infotext = '<div class=listing_map_popup><h3>' +
				address+'</h3>'+
				'<p>MLS ID <a href=/listing/'+listing_id+'>'+listing_id+'</a></p>' +
				'<img src='+pic_url+' height=262 width=350 />' +                
				 '<p>Priced at $'+price+'</p>' +
				'<p>'+description+'</p></div>';                
				var marker = new google.maps.Marker({
					  map: map,
					  position: point,                  
					  title: address
					});                    
				bindInfoWindow(marker, map, infoWindow, infotext);                
				map.setCenter(point);
			  });
			}, "xml");
			// activate the data table   
			mt_data_tables();         
			mt_listing_highlight();            
			mt_picture_highlight();            
			jQuery('#loading').fadeOut();
		});
	}
}
function HinPagination() {
  jQuery("a.next").click(function() {
    alert('Click');
    });
  }  

/**
 * this function initiates the datatable javascript to paginate the listings results table
 * 
 */
function mt_data_tables() {
  oTable = jQuery("#mls_listings").dataTable(
  {  
    "bPaginate": true,    
    "iDisplayLength": 5,    
    "bLengthChange": false,    
    "bStateSave": true,    
    "iCookieDuration": 600,
    "sDom": '<"top"ip>rt<"bottom"fl<"clear">',    
    "bAutoWidth": false,
		"aoColumns": [ 
			{"sWidth" : "70px"},
			{"sWidth" : "90px"},
			{"sWidth" : "70px"},
			{"sWidth" : "40px"},
			{"sWidth" : "40px"},
			{"sWidth" : "350px"}

		]
  });
}

function mt_listing_highlight() {
/** 
* this each function creates a hover over image showing map location of each property based on the contents of the div and table
*
*/
  jQuery('#mls_listings td a[href].show').each(function(){
	  var temp_mls_id = jQuery(this).attr("title");
	  var mls_id = temp_mls_id.substring(13,21); // get just Property and MLS ID.  
	  var three_digits = mls_id.substring(5,9); // get last three digits to complete url  
	  var s = jQuery(this).attr("src");  
	  var c = jQuery(this).attr("map");
	  var mapUrl = "http://maps.google.com/maps/api/staticmap?zoom=14&size=350x262&markers=";
	  var mapUrl = mapUrl + c;  
	  var mapUrl = mapUrl + "&sensor=false";
	  content ='<div class="property-tip"><img src="'+mapUrl+'" /><p>'+temp_mls_id+'</p></div>';
	  jQuery(this).qtip({
		  content: content,      
		  style: { 
				border: {
				   width: 3,
				   radius: 8,
				   color: '#003366'
				},
				width: 365,            
				height: 300,
			  }, 
		  position: {
			   corner: {
				   target: 'topRight',
				   tooltip: 'leftMiddle'
				}
			 }
	   });   
  });// each 
}

/**
*
* this each function creates a hover over image of the property photograph at it's original size
* requires the MLS number to be in the title attribute of the img tag
*
*/
function mt_picture_highlight() {
  jQuery('#mls_listings td img.main').each(function(){
	  var temp_mls_id = jQuery(this).attr("title");
//	  var re = new RegExp(temp_mls_id);
//	  var banana = re.exec('([0-9]{8})');
//	  alert (re + banana.index);
	  var mls_id = temp_mls_id.substring(13,21); // get just Property and MLS ID.  
	  var three_digits = mls_id.substring(5,9); // get last three digits to complete url  
	  var s = jQuery(this).attr("src"); // I inject url into the markup for tip
	  content ='<div class="property-tip"><img src="'+s+'" /><p>'+temp_mls_id+'</p></div>';
	  jQuery(this).qtip({
		  content: content,      
		  style: { 
				border: {
				   width: 2,
				   radius: 6,
				   color: '#003366'
				},
				width: 512,            
				height: 430,
			  }, 
		  position: {
			   corner: {
				   target: 'topMiddle',
				   tooltip: 'leftBottom'
				}
			 }
	   });   
  });// each 
}

/**
*
* WidgetSearch - collect and validate search inputs 
*
*/
function WidgetSearch() {

// reset errors removing them from display as defined by .error class
  jQuery(".error").hide();


  // if a key is pressed in the zip input box then hide the area selector
  // to require that only one is used in the query
  jQuery('#zip').keyup(function() {
	jQuery('label#ziperror').fadeOut();
    var zip = jQuery('#zip').val();
    if(zip == '') {
      jQuery('#area-search').show();
    } else {   
      jQuery('#area-search').hide();
    }
  });  

  jQuery("#submit_button").click(function() {
  // validation for selections
  var searcherror = false;
  var price_to = jQuery("#priceto option:selected").val();
  var price_from = jQuery("#pricefrom option:selected").val();
  var zip = jQuery('#zip').val();
  var area = jQuery('#searcharea option:selected').val();
  var baths = jQuery("#baths option:selected").val();
  var beds = jQuery("#beds option:selected").val();

    if( ((area == '') || ( area == undefined )) && ( zip == '') ){
      jQuery('#searcharea option:selected').focus();
      searcherror = true;
	  alert('area is empty / undefined and zip is not empty');
	  return false;
    }
	if ((zip == '' ) && ((area == '') || ( area == undefined) )) {
		jQuery('label#ziperror').fadeIn();
		searcherror = true;
		alert('zip');
	  return false;
	}
    if((price_from == '') && (price_to == '')){
      jQuery('label#pricefromerror').fadeIn();
      jQuery('#pricefrom').focus();
      searcherror = true;
	  return false;
    }  
	if(zip != '') {
		area = '';
	}
//    if(price_to == '') {
//      jQuery('label#pricetoerror').fadeIn();
//      jQuery('#priceto').focus();
//      searcherror = true;
//    } 
    if (searcherror) { return false; }
    if ((price_to != '') && (price_from != '')) {
      if (parseInt(price_to) <= parseInt(price_from)) {
      alert("Oops : Price to: "+price_to+" Price from "+price_from);
        jQuery('label#pricetoerror').fadeOut();
        jQuery('label#pricefromerror').fadeOut();
        jQuery('label#pricetoerror').fadeIn();
        jQuery('label#pricefromerror').fadeIn();
        searcherror = true;
		return false;
      }
    }
    if (searcherror) { return false; }
    if(zip != '') {
      jQuery('#searcharea option:selected').val('');
    }
    jQuery('label#pricetoerror').fadeOut();
    jQuery('label#pricefromerror').fadeOut();      
      jQuery(document).ready(function() {
        jQuery('#searchresults').fadeIn();
        jQuery('#loading').fadeIn();
// maybe here get total number of results and then set the paging settings
        jQuery.get('/wp-content/plugins/mred-tools/jsearch.php',         
        { 
          price_from: price_from,
          price_to: price_to,
          area: area,      
		  zip: zip,
          beds: beds,      
          baths: baths,       
          get_count: 'true'
        }, function(data) {
            fadeAllDivs();
            jQuery('.results_heading').html(data).fadeIn();
        }); // end get listing count        
// now get the full listing data
        jQuery.get('/wp-content/plugins/mred-tools/jsearch.php', 
          { 
          price_from: price_from,
          price_to: price_to,
          area: area,      
		  zip: zip,
          beds: beds,      
          baths: baths,   
          layout: 'table'
          }, function(data) {             
            fadeAllDivs();
            jQuery('#searchresults_contents').html(data).fadeIn();
            var myLatlng = new google.maps.LatLng(41.760632,-88.143778);
            var myOptions = {
              zoom: 12,
              center: myLatlng,
              mapTypeId: google.maps.MapTypeId.ROADMAP
            };            
            var infoWindow = new google.maps.InfoWindow;
            var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
			var bounds = new google.maps.LatLngBounds(); // used to later center / fit the map with the markers
			// find a way of limiting the data gather to maximum listings.
// process data points / listings to add the map popups
            jQuery.get('/wp-content/uploads/maps.xml', function(data) {            
              jQuery(data).find('marker').each(function() {              
                var listing_id = jQuery(this).attr('id');
				var area_name = jQuery(this).attr('area_name');
                var address = jQuery(this).attr('address');              
                var zip = jQuery(this).attr('zip');
                var lat = jQuery(this).attr('lat');
                var lng = jQuery(this).attr('lng');
                var point = new google.maps.LatLng( lat, lng);                
                var pic_url = jQuery(this).attr('mainpic');
                var price = jQuery(this).attr('price');
                var description = jQuery(this).attr('description');
                var infotext = '<div class=listing_map_popup><h3>' +
                address+'</h3>'+
                '<p>MLS ID <a href=/listing/'+listing_id+'>'+listing_id+'</a></p>' +
                '<img src='+pic_url+' height=262 width=350 />' +                
                 '<p>Priced at $'+price+'</p>' +
                '<p>'+description+'</p></div>';                
                var marker = new google.maps.Marker({
                      map: map,
                      position: point,                  
                      title: address
                    });                   
				bounds.extend(point);
                bindInfoWindow(marker, map, infoWindow, infotext);                
                map.fitBounds(bounds);
              });
            }, "xml");
            // activate the data table   
            mt_data_tables();         
            mt_listing_highlight();            
            mt_picture_highlight();            
            jQuery('#loading').fadeOut();
			} // jsearch callback
        ); // jsearch
    });  
  return true;
  }); // submit click
} // widget search

function bindInfoWindow(marker, map, infoWindow, html) {
  google.maps.event.addListener(marker, 'click', function() {
    infoWindow.setContent(html); 
    infoWindow.setOptions({maxWidth: 400});   
    infoWindow.open(map, marker);
  });
}

function fadeAllDivs () {
  jQuery('#content').fadeOut();
  jQuery('#latest').fadeOut();
  jQuery('#featured').fadeOut();
  jQuery('#pricechanged').fadeOut();
}
