/**
* myhood Namespace
* This anonymous function acts as a namespace wrapper for the rest
* of the methods. Methods are then assigned to the window object
* using: window['myhood']['methodName'] = methodReference;
* @alias myhood
*/
(function(){

  /**
  * The primary namespace object
  * @type {Object}
  * @alias myhood
  */
  if(!window['myhood']) {
    window['myhood'] = {};
  } // end if

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

  /* Alias for prototypes Event.observe */
  function addEvent(elm,event,func){
    Event.observe(elm,event,func);
  } // end addEvent function
  window['myhood']['addEvent'] = addEvent;

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

  /* Gets variable from url */
  function getUrl(name){
    var regexS = "[\\?&]"+name+"=([^&#]*)";
    var regex = new RegExp( regexS );
    var tmpURL = window.location.href;
    var results = regex.exec( tmpURL );
    if( results == null )
    return "";
    else
    return results[1];
  } // end getUrl function
  window['myhood']['getUrl'] = getUrl;

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

  /* effects on location bar search box place / remove text */
  function check_search(el){
    if(el.value == ""){
      el.style.color = '#c1c1c1';
      el.value = 'Enter neighbourhood, intersection, university, subway or GO station';
      return false;
    } // end if
    if(el.value == "Enter neighbourhood, intersection, university, subway or GO station"){
      el.style.color = '';
      el.value = '';
      return false;
    } // end if
  } // end check_search function
  window['myhood']['checksearch'] = check_search;

  /* setup effects on location search bar */
  function initLocationSearch(el){
    if(el){
      check_search(el);
      addEvent(el,'focus',function(){check_search(el);});
      addEvent(el,'blur',function(){check_search(el);});
    } // end if
  } // end initLocationSearch function
  window['myhood']['initLocationSearch'] = initLocationSearch;

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

  function update_search_link( el,page ){
    if(el){
      var link = el;
      var linkzoom = map.getZoom();
      var linkcenter = map.getCenter();
      var session = getUrl('session');
      
      var hrefvalue = page + '?lat=' + linkcenter.y + '&lng=' + linkcenter.x + '&zoom=' + linkzoom + '&type=switch&house_type=apa';
      if(session != ""){
        hrefvalue += '&session=' + session;
      }
      link.href = hrefvalue;
    } // end if
  } // end if
  window['myhood']['update_search_link'] = update_search_link;

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

  function addLoading(){
    if($('hideload')){
      var box = $('hideload');
      box.style.display = 'block';
    }
  } // end addLoading function
  window['myhood']['addLoading'] = addLoading;

  function removeLoading(){
    if($('hideload')){
      var box = $('hideload');
      box.style.display = 'none';
    }
  } // end removeLoading function
  window['myhood']['removeLoading'] = removeLoading;

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

})();

/* change the arrows on map sidebar based on accordian */
function changeArrow(el){
  var panel_title_1 = $('panel1').getElementsByTagName('h5');
  panel_title_1 = panel_title_1[0];
  var panel_title_2 = $('panel2').getElementsByTagName('h5');
  panel_title_2 = panel_title_2[0];
  if(panel_title_2.firstChild.className == ''){
    panel_title_2.firstChild.className = 'up';
  }else{ // end if
    panel_title_2.firstChild.className = '';
  } // end else
  if(panel_title_1.firstChild.className == ''){
    panel_title_1.firstChild.className = 'up';
  }else{ // end if
    panel_title_1.firstChild.className = '';
  } // end else
} // end changeArrow function

/* The accordian on the map pages uses scriptaculous  */
function accordion(el) {
  if (Element.hasClassName(el.parentNode.id+'-body','visible')){
    //do not need to perform an actions
    return;
  } // end if
  var eldown = el.parentNode.id+'-body';
  var apanels = document.getElementsByClassName('panel_body',el.parentNode.parentNode);
  for (var i=0;i<apanels.length;i++){
    if (Element.hasClassName(apanels[i].parentNode.id+'-body','visible')){
      var elup = apanels[i].parentNode.id+'-body';
      changeArrow(el);
    } // end if
  } // end for
  new Effect.Parallel([ new Effect.SlideUp(elup), new Effect.SlideDown(eldown) ], {duration: 0.5});
  Element.removeClassName(elup,'visible');
  Element.addClassName(eldown,'visible');
} // end accordion function

//pass in ID of container element that has all instances of apanels
function accordion_init(id) {
  var apanels = document.getElementsByClassName('panel_body',id);
  for (var i=0;i<apanels.length;i++){
    apanels[i].style.display = 'none';
  } // end for
  var velems = document.getElementsByClassName('visible');
  for (var i=0;i<velems.length;i++){
    $(velems[i]).style.display = 'block';
  } // end for
} // end accordian_init function

//addEvent(window, "load", function(){accordion_init('panels');});



function gup(el){
  return myhood.getUrl(el);
}

function clear_error_text(){
  if($('errorWrapper')){
    $('errorWrapper').style.display = 'none';
  }
}

function error_text(text){
  if(text != ""){
    if($('clientContent')){
      if(!$('errorWrapper')){
        var errorWrapper = document.createElement('div');
        errorWrapper.innerHTML = text;
        errorWrapper.id = 'errorWrapper';
        $('clientContent').appendChild(errorWrapper);
      }else{
        $('errorWrapper').innerHTML = text;
        $('errorWrapper').style.display = 'block';
      }
    }
  }
}

function keypressHandler (event,page){

  var key = event.which || event.keyCode;

  if(key == Event.KEY_RETURN){
    //find_location($('search').value, $('city_id').value,page);
    GLog.write('test');
  }
}

function listenforenter(el,page){
  addEvent(el,'keypress',function(event){keypressHandler(event,page)});
}

function endlistenforenter(el,page){
  Event.stopObserving(el,'keydown',function(event){keypressHandler(event,page)})
}



function setup_search_form(page){

  if(page == ""){
    page = 'rent';
  }

  var el = $('search');
  //addEvent(el,'focus',function(){listenforenter(el,page);});
  //addEvent(el,'blur',function(){endlistenforenter(el,page);});

  if($('searchbutton')){
    $('searchbutton').onclick = function(){
      // search location provided
      if($('search')){
        if($('search').value != ""){
          find_location($('search').value, $('city_id').value,page);
        } // end if
      } // end if
    };
  } // end if

} // end function setup_search_form

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

function float_search(page,room){
  if($('right_pane')){
    var params = '&page=' + page;
    function handlerFunc(t){
      var post = t.responseText;
      //JSLog.write(post);
      var floatDiv = document.createElement('div');
      floatDiv.id = 'floatSearchBox';
      floatDiv.innerHTML = post;
      $('right_pane').appendChild(floatDiv);
      
      if(room){
      var searchtypes = $('floatsearchform').getInputs('radio', 'search_type');
      
      for(var i=0; i<searchtypes.length; i++){
        searchtypes[i].checked = false;
        if(searchtypes[i].value == gup('house_type')){
          searchtypes[i].checked = true;
        } // end if
      } // end for
      }
      
      var floatDivCloseLink = document.createElement('a');
      floatDivCloseLink.style.position = 'absolute';
      floatDivCloseLink.style.top = '2px';
      floatDivCloseLink.style.right = '2px';
      floatDivCloseLink.style.cursor = 'pointer';
      floatDivCloseLink.style.fontWeight = 'bold';
      floatDivCloseLink.innerHTML = 'X';
      floatDivCloseLink.id = 'closebutton';
      floatDivCloseLink.onclick = function(){
        $('right_pane').removeChild($('floatSearchBox'));
      }
      floatDiv.appendChild(floatDivCloseLink);

      if($('floatsearchbutton')){
        $('floatsearchbutton').onclick = function(){
          if($('type_search')){
            if($('options_form') && $('floatsearchform')){
              var changeto;
              var checks = $('floatsearchform').getInputs('radio', 'search_type');
              if(checks.length != 0){
                for(var i=0; i<checks.length; i++){
                  if(checks[i].checked == true){
                    changeto = checks[i].value;
                  }
                }
              }

              var types = $('options_form').getInputs('radio', 'house_type');
              if(types.length != 0){
                for(var i=0; i<types.length; i++){
                  types[i].checked = false;
                  var typecheck;
                  switch(changeto){
                    case "roommates":
                    case "roo":
                    typecheck = 'roo';
                    break;
                    case "sublet":
                    case "sub":
                    typecheck = 'sub';
                    break;
                    case "rent":
                    case "apa":
                    default:
                    typecheck = 'apa';
                    break;
                  }
                  if(types[i].value == typecheck){
                    types[i].checked = true;
                  }
                }
              }
            }

          }
          // search location provided
          if($('floatsearch')){
            if($('floatsearch').value != ""){
               $('search').style.color = '';
               $('search').value = $('floatsearch').value;
               
               //myhood.checksearch($('search'));
              find_location($('floatsearch').value, $('float_city_id').value);
            } // end if
          } // end if
          
          
          //$('right_pane').removeChild($('floatSearchBox'));
        } // end if
      }

    } // end handlerFunc
    function errFunc(){}
    new Ajax.Request('/scripts/finder/float.php', {method:'post', postBody:params, onSuccess:handlerFunc, onFailure:errFunc});

  } // end if
} // end function


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

function check_for_home_search(page){
  //GLog.write('home page: ' + page);
  if(page == ""){
    page = 'rent';
  }
  clear_error_text();
  var street = gup('street');
  var city_id = gup('city_id');
  var type = gup('type');

  if(type == 'single' && !clearsingle){
    var lat = gup('lat');
    var lng = gup('lng');
    var zoom = gup('zoom');
    
    var point = new GLatLng(lat,lng);
    map.setCenter(point,Number(zoom));
    
    display_markers();
    return false;
  }
  
  
  if(type == 'switch'){

    var lat = gup('lat');
    var lng = gup('lng');
    var zoom = gup('zoom');
    var type = gup('house_type');
    
    if(lat == '43.6667540515383' && lng == '-79.3979358673096' && zoom == '13' && type == 'roo'){
      var housetypes = $('options_form').getInputs('radio', 'house_type');
            for(var i=0; i<housetypes.length; i++){
              housetypes[i].checked = false;
              if(housetypes[i].value == gup('house_type')){
                housetypes[i].checked = true;
              } // end if
            } // end for
            
      float_search(page,true);
      
      return false;
    } // end if
    
    

    switch(page){
      case "review":
      
            var price_min = gup('price_min');
            var bedrooms = gup('bedrooms');
            var recommend = gup('recommend');
            var rating = gup('rating');
            var num_reviews = gup('num_reviews');
            var search = gup('search');
            
            switch(price_min){
              case '0':
                price_min = '0';
                break;
              case '1':
                price_min = '< $600';
                break;
              case '2':
                price_min = '$600 - $800';
                break;
              case '3':
                price_min = '$800 - $1000';
                break;
              case '4':
                price_min = '$1000 - $1200';
                break;
              case '5':
                price_min = '$1200 - $1400';
                break;
              case '6':
                price_min = '$1400 - $1600';
                break;
              case '7':
                price_min = '$1600 - $1800';
                break;
              case '8':
                price_min = '$1800 - $2000';
                break;
              case '9':
                price_min = '$2000 - $2200';
                break;
              case '10':
                price_min = '$2200 - $2400';
                break;
              case '11':
                price_min = '> $2400';
                break;
                default:
                price_min = '0';
                break;
            } // end switch
            
            $('bedrooms').value = bedrooms;
            $('rating').value = rating;
            $('recommend').value = recommend;
            if($('price_min')) $('price_min').value = price_min;
      
        break;
      case "rent":
      
            $('price_min').value = gup('price_min');
            $('price_max').value = gup('price_max');
            $('bedrooms').value = gup('bedrooms');
            $('bathrooms').value = gup('bathrooms');
            $('bathrooms').value = gup('bathrooms');
            //$('house_type').value = gup('house_type');
            $('search_filter').value = gup('search_filter');
            
            var housetypes = $('options_form').getInputs('radio', 'house_type');
            for(var i=0; i<housetypes.length; i++){
              housetypes[i].checked = false;
              if(housetypes[i].value == gup('house_type')){
                housetypes[i].checked = true;
              } // end if
            } // end for
            
            var checks = $('options_form').getInputs('checkbox');
            for(var i=0; i<checks.length; i++){
              checks[i].checked = false;
              if(gup(checks[i].name) == 't'){
                checks[i].checked = true;
              } // end if
            } // end for
            
        break;
    } // end switch



    var point = new GLatLng(lat,lng);
    map.setCenter(point,Number(zoom));
    display_markers();
    return false;
  }

  if(street == "" && city_id == "" && type == ""){
    
    if(page){
      float_search(page);
    }
  }else{

    if(type){
      if($('options_form')){
        var types = $('options_form').getInputs('radio', 'house_type');
        if(types.length != 0){
          for(var i=0; i<types.length; i++){
            types[i].checked = false;
            var typecheck;
            switch(type){
              case "roommates":
              case "roo":
              typecheck = 'roo';
              break;
              case "sublet":
              case "sub":
              typecheck = 'sub';
              break;
              case "rent":
              case "apa":
              default:
              typecheck = 'apa';
              break;
            }
            if(types[i].value == typecheck){
              types[i].checked = true;
            }
          }
        }
      }
    }

    var getVars = '&search=' + street + '&city_id=' + city_id + '&page=' + page + '&zoom=' + map.getZoom();

    var params = 'action=get_points';
    params += getVars;

    var handlerFunc = function(t){
      //GLog.writeHtml(t.responseText);

      var data = t.responseText;
      var error = false;
      if(data == '800' || data == '801'){
        error_text('That location could not be found!');
        error = true;
        //display_markers();
      } // end if

      //
      if(!error){
        var pointreturn;
        eval(data);
        if(pointreturn.length == 1 && pointreturn.htype != 'didyou'){
          for(id in pointreturn){
            if(id != 'length' && id != 'htype'){
              if(pointreturn[id].go == 1){
                var point = new GLatLng(pointreturn[id].lat,pointreturn[id].lng);
                //JSLog.write(pointreturn[id].zoom);
                map.setCenter(point,Number(pointreturn[id].zoom));
                $('didyoumean').style.display = 'none';
              } // end if
            } // end if
          } // end for
        } // end if

        if(pointreturn.length > 1 || pointreturn.htype == 'didyou'){
          // build did you mean list
          var errorDiv = $('didyoumean');
          errorDiv.style.display = 'block';
          var header = document.createElement('h3');
          header.innerHTML = 'Did you mean:';
          errorDiv.appendChild(header);
          var list = document.createElement('ul');
          
          for(id in pointreturn){
            if(id != 'length' && id != 'htype'){
              var listItem = document.createElement('li');
              var listItemLink = document.createElement('a');
              listItemLink.href = '#';

              createlink(listItemLink,pointreturn[id]);

              listItemLink.innerHTML = pointreturn[id].returntext;
              listItem.appendChild(listItemLink);
              list.appendChild(listItem);
            } // end if
          } // end for
          $('didyoumean').innerHTML = '';
        errorDiv.appendChild(header);
        $('didyoumean').appendChild(list);
          
          var panel_title_2 = $('panel2').getElementsByTagName('h5');
          var title = panel_title_2[0];
          accordion(title);
          
        } // end if

        if(pointreturn.length == 0){
          error_text('That location could not be found!');
        } // end if

      } // end if

      if(error){
        $('didyoumean').style.display = 'none';
      }

    }; // end handlerFunc

    var errFunc = function(){

    }; // end errFunc
    new Ajax.Request('/scripts/finder/function.php', {method:'post', postBody:params, onSuccess:handlerFunc, onFailure:errFunc});
  }
} // end function




function find_location(search_string,city_id,page){
  
  if($('floatSearchBox')){
    $('right_pane').removeChild($('floatSearchBox'));
  }
  
  //GLog.write('find page: ' + page);
  if(page == ""){
    page = 'rent';
  }
  var getVars = '&search=' + search_string + '&city_id=' + city_id + '&page=' + page + '&zoom=' + map.getZoom();

  var params = 'action=get_points';
  params += getVars;
  //GLog.write(params);
  clear_error_text();
  var handlerFunc = function(t){
    //GLog.writeHtml(t.responseText);

    var data = t.responseText;
    var error = false;
    if(data == '800' || data == '801'){
      error_text('That location could not be found!');
      error = true;
    } // end if

    //
    if(!error){
      var pointreturn;
      eval(data);
      if(pointreturn.length == 1 && pointreturn.htype != 'didyou'){
        for(id in pointreturn){
          if(id != 'length' && id != 'htype'){
            if(pointreturn[id].go == 1){
              var point = new GLatLng(pointreturn[id].lat,pointreturn[id].lng);
              //GLog.write(pointreturn[id].zoom);
              map.setCenter(point,Number(pointreturn[id].zoom));
              display_markers();
              $('didyoumean').style.display = 'none';
            } // end if
          } // end if
        } // end for
      } // end if

      if(pointreturn.length > 1 || pointreturn.htype == 'didyou'){
        // build did you mean list
        var errorDiv = $('didyoumean');
        errorDiv.style.display = 'block';
        var header = document.createElement('h3');
        header.innerHTML = 'Did you mean:';

        var list = document.createElement('ul');

        for(id in pointreturn){
          if(id != 'length' && id != 'htype'){
            var listItem = document.createElement('li');
            var listItemLink = document.createElement('a');
            listItemLink.href = '#';

            createlink(listItemLink,pointreturn[id]);

            listItemLink.innerHTML = pointreturn[id].returntext;
            listItem.appendChild(listItemLink);
            list.appendChild(listItem);
          } // end if
        } // end for
        $('didyoumean').innerHTML = '';
        errorDiv.appendChild(header);
        $('didyoumean').appendChild(list);
        
        var panel_title_2 = $('panel2').getElementsByTagName('h5');
          var title = panel_title_2[0];
          accordion(title);
        
      } // end if

      if(pointreturn.length == 0){
        error_text('That location could not be found!');
      } // end if

    } // end if

    if(error){
      $('didyoumean').style.display = 'none';
    }

  }; // end handlerFunc

  var errFunc = function(){

  }; // end errFunc
  new Ajax.Request('/scripts/finder/function.php', {method:'post', postBody:params, onSuccess:handlerFunc, onFailure:errFunc});
} // end function find_location



function create_cat_marker(point,icon,width,height){

  var newIcon = new GIcon();
  newIcon.image = "/user_files/images/Image/icons/" + icon;
  newIcon.iconSize = new GSize(Number(width), Number(height));
  newIcon.iconAnchor = new GPoint(6, 20);
  newIcon.infoWindowAnchor = new GPoint(6, 1);

  var marker = new GMarker(point,newIcon);
  return marker;
} // end create_cat_marker

function create_marker(point, type){
  var marker;
  if(type=='c') {
    //marker = new GMarker(point,clusterIcon);
    marker = new GMarker(point,clusterIcon);
  } else {
    marker = new GMarker(point,defaultIcon);
  }
  return marker;
}

function createlink(link,data){
  link.onclick = function(){
    map.setCenter(new GLatLng(data.lat,data.lng),15);
    if($('didyoumean')){
      //JSLog.write('test');
      $('didyoumean').style.display = 'none';
    }
  };
}

// array-like enumeration
if (!Array.forEach) { // mozilla already supports this
  Array.forEach = function(object, block, context) {
    for (var i = 0; i < object.length; i++) {
      block.call(context, object[i], i, object);
    }
  };
}

// generic enumeration
Function.prototype.forEach = function(object, block, context) {
  for (var key in object) {
    if (typeof this.prototype[key] == "undefined") {
      block.call(context, object[key], key, object);
    }
  }
};

// globally resolve forEach enumeration
var forEach = function(object, block, context) {
  if (object) {
    var resolve = Object; // default
    if (object instanceof Function) {
      // functions have a "length" property
      resolve = Function;
    } else if (object.forEach instanceof Function) {
      // the object implements a custom forEach method so use that
      object.forEach(block, context);
      return;
    } else if (typeof object.length == "number") {
      // the object is array-like
      resolve = Array;
    }
    resolve.forEach(object, block, context);
  }
};




//Create the ToolTip overlay object
function ToolTip(marker,html,width) {
	this.html_ = html;
	this.width_ = (width ? width + 'px' : 'auto');
	this.marker_ = marker;
}
ToolTip.prototype = new GOverlay();
ToolTip.prototype.initialize = function(map) {
	var div = document.createElement("div");
	div.style.display='none';
	map.getPane(G_MAP_FLOAT_PANE).appendChild(div);
	this.map_ = map;
	this.container_ = div;
}
ToolTip.prototype.remove = function() {
	this.container_.parentNode.removeChild(this.container_);
}
ToolTip.prototype.copy = function() {
	return new ToolTip(this.html_);
}
ToolTip.prototype.redraw = function(force) {
	if (!force) return;
	var pixelLocation = this.map_.fromLatLngToDivPixel(this.marker_.getPoint());
	this.container_.innerHTML = this.html_;
	this.container_.style.position='absolute';
	this.container_.style.left = pixelLocation.x + "px";
	this.container_.style.top = pixelLocation.y + "px";
	this.container_.style.width = this.width_;
	this.container_.style.font = 'bold 10px/10px verdana, arial, sans';
	this.container_.style.border = '1px solid black';
	this.container_.style.background = '#F3F3E9';
	this.container_.style.padding = '4px';

	//one line to desired width
	this.container_.style.whiteSpace = 'nowrap';
	if(this.width_ != 'auto') this.container_.style.overflow = 'hidden';

	this.container_.style.display = 'block';
}

GMarker.prototype.ToolTipInstance = null;
GMarker.prototype.openToolTip = function(content) {
	//don't show the tooltip if there is a custom info window
	if(this.ToolTipInstance == null && this.LittleInfoWindowInstance == null) {
		this.ToolTipInstance = new ToolTip(this,content)
		map.addOverlay(this.ToolTipInstance);
	}
}
GMarker.prototype.closeToolTip = function() {
	if(this.ToolTipInstance != null) {
		map.removeOverlay(this.ToolTipInstance);
		this.ToolTipInstance = null;
	}
}














// Global variables for maps
var map;
var centerLatitude = 43.6667540515383;
var centerLongitude = -79.3979358673096;
var startZoom = 13;
var clearsingle = false;
