/*jslint white: true, laxbreak: true, indent: 2 */
// This is only missing in IE 6 and 7
// P.S. I hate myself - love ~ Anders
var iframesfix = false;
var ua = window.navigator.userAgent;
if (ua.indexOf('Opera') > -1) {
  iframesfix = true;
}

var staticPages = false;
if (ua.indexOf('MSIE 6') > -1 || ua.indexOf('MSIE 7') > -1) {
  staticPages = true;
}

function show_tab(tab) {
  if (tab == 'map') {
    $J("body").addClass("map").removeClass("listings");
    $J('#content_pages, #content_pages_footer').remove();
    $J('#search_column').css("visibility", "visible");
    $J('#search_footer_disclaimer').css({'visibility': 'visible', 'position' : 'relative'});
    $J('#content_map').removeClass('hidden').css('position', 'relative');
  } else {
    $J("body").removeClass("map").addClass("listings");
    if ($J('#content_pages, #content_pages_footer').length > 0) {
      $J("#content_pages, #content_pages_footer").remove();
    }
    $J('#search_column').css("visibility", "hidden");
    $J('#search_footer_disclaimer').css({'visibility': 'hidden', 'position' : 'absolute'});
    $J('#content_map').addClass('hidden').css('position', 'absolute');
    //$J('#content_pages').removeClass('hidden');
  }
}

var lastUpdate = null;

function doPageUpdate(hash) {
  if (lastUpdate) {
    lastUpdate.abort();
  }

  if (hash.charAt(0) != '/') {
    hash = '/' + hash;
  }

  if (hash == '/map' || isLocationPath(hash)) {
    show_tab('map');
    _Estately.pubsub.trigger("/page/changed", ["map"]);
  } else {
    show_tab('content_pages');
  
    //without ?ajax=true to differentiate it some browsers get confused between these and the permalinkable version and break 
    //the back button
    lastUpdate = $J.ajax({ url: hash
                         , type: "GET"
                         , dataType: "html"
                         , complete: function () {
                             delete lastUpdate;
                           }
                         , success: function (content, textStatus, xhr) {
                             if (xhr.status == "200") {
                               $J("#content_column").append(content);
                               _Estately.pubsub.trigger("/page/changed", ["listings"
                                                                         , $J("#listing-full-details").attr("data-property-id")
                                                                         , $J("#listing-full-details").attr("data-with-request-showing")
                                                                         , $J("#listing-full-details").attr("data-title-tag")
                                                                         ]);
                             } else {
                               // if we are getting back anything but a 200 then something has gone wrong
                               // so kick them over to a page that works.
                               window.location = "/map";
                             }
                           }
                         , error: function (xhr, stat, err) {
                             // aborted requests have a status of 0 and aren't errors
                             if (xhr.status) {
                               window.location = "/map";
                             }
                           }
                         });
    try {
      pageTracker._trackPageview(hash);
      bounceTracker._trackPageview(hash);
      EstatelyLog('Tracked pageview: "' + hash + '"');
    } catch (e) {}

    return hash;
  }
}

function update_hash(hash) {
  if (iframesfix) {
    document.getElementById('ajaxnav').setAttribute('src', '/map/mock_page/?hash=' + hash);
  } else if (staticPages) {
    window.location.pathname = hash;
  } else {
    window.location.hash = hash;
  }
}

/* PAGELOCATOR */
function PageLocator(propertyToUse, dividingCharacter) {
  this.propertyToUse = propertyToUse;
  var t = window.location.pathname;
  if (t.charAt(0) == '/') {
    t = t.slice(1);
  }
  this.defaultQS = t;
  this.dividingCharacter = dividingCharacter;
}

PageLocator.prototype.getLocation = function () {
  var loc = this.propertyToUse() || "";
  return loc;
  //return eval(this.propertyToUse);
};

PageLocator.prototype.getHash = function () {
  var url = this.getLocation();
  if (url.indexOf(this.dividingCharacter) > -1) {
    var url_elements = url.split(this.dividingCharacter);
    return url_elements[url_elements.length - 1];
  } else {
    return this.defaultQS;
  }
};

PageLocator.prototype.getHref = function () {
  var url = this.getLocation();
  var url_elements = url.split(this.dividingCharacter);
  return url_elements[0];
};

PageLocator.prototype.makeNewLocation = function (new_qs) {
  return this.getHref() + this.dividingCharacter + new_qs;
};
/* END PAGELOCATOR */


/* AjaxIframesFixer */
function AjaxIframesFixer(iframeid) {
  this.iframeid = iframeid;
  if (document.getElementById(this.iframeid)) {
    this.locator = new PageLocator(function () {
      // I worry that frames[0] might not always be our frame
      var loc = document.frames[0].location.href;
      return loc;
    }, "?hash=");

    this.windowlocator = new PageLocator(function () {
      return window.location.href;
    }, "#");
    this.delayInit(); // required or IE doesn't fire
  }
}

AjaxIframesFixer.prototype.delayInit = function () {
  var that = this;
  setTimeout(function () {
    that.checkBookmark();
  }, 100);
};
AjaxIframesFixer.prototype.checkBookmark = function () {
  window.location = this.windowlocator.makeNewLocation(this.locator.getHash());
  this.checkWhetherChanged(this.locator.defaultQS);
};

AjaxIframesFixer.prototype.checkWhetherChanged = function (location) {
  newLocation = this.locator.getHash();
  if (newLocation != location) {
    doPageUpdate(newLocation);
    window.location = this.windowlocator.makeNewLocation(newLocation);
  }
  var that = this;
  setTimeout(function () {
    that.checkWhetherChanged(newLocation);
  }, 200);
};
/* END AjaxIframesFixer */


/* AjaxUrlFixer */
function AjaxUrlFixer() {			
  this.locator = new PageLocator(function () {
    return window.location.href;
  }, "#");
  this.checkWhetherChanged(this.locator.defaultQS);
}

AjaxUrlFixer.prototype.checkWhetherChanged = function (location) {
  var tab_name;
  var newLocation = this.locator.getHash();
  if (newLocation != location) {
    doPageUpdate(newLocation);
  }
  var that = this;
  setTimeout(function () {
    that.checkWhetherChanged(newLocation);
  }, 200);
};
/* END AjaxUrlFixer */
var isState = function (test) {
  var start = test.slice(0,2);

  var states = ['AL', 'AK', 'AZ', 'AR', 'CA', 'CO', 'CT', 'DE', 'DC', 'FL', 'GA', 'HI', 'ID', 'IL', 
                'IN', 'IA', 'KS', 'KY', 'LA', 'ME', 'MD', 'MA', 'MI', 'MN', 'MS', 'MO', 'MT', 'NE',
                'NV', 'NH', 'NJ', 'NC', 'ND', 'OH', 'OK', 'OR', 'PA', 'RI', 'SC', 'SD', 'TN', 'TX',
                'UT', 'VT', 'VA',  'NY', 'WA', 'WV', 'WI', 'WY', 'BC'];
  for (var i = 0; i < states.length; i++) {
    if (start == states[i]) {
      return true;
    }
  }
  return false;
};

var isLocationPath = function (path) {
  if (path.charAt(0) == '/') {
    path = path.slice(1);
  }
  return path && isState(path) || path.match(/^-?\d+\.\d{1,4}/)
};

var fix;

function FixBackAndBookmarking() {
  if (window.location.hash == '' || window.location.hash == '#') {
    var t = window.location.pathname;
    //it's a lat/long or a statey thing
    if (isLocationPath(t)) {
      t = 'map';
    }
    update_hash(t);
  }
  if (iframesfix) {
    fix = new AjaxIframesFixer('ajaxnav');
  } else {
    fix = new AjaxUrlFixer();
  }
}

var tabbedSelector = function (event) {
  if (event.which == 2 || event.metaKey || event.ctrlKey) {
    event.stopPropagation();
    return true;
  }

  var link = $J(event.target);
  var href = link.attr("href");
  if (!href) {
    href = $J(link).parents('a').attr("href");
  }
  if (href.slice(0, 4) == "http") {
    update_hash(href.split('/').slice(3).join('/'));
  } else {
    update_hash(href);
  }
  return false;
};

if (!staticPages) {
  $J('a[href*=listings/info]').not('a[target=_blank]').live('click', tabbedSelector);
  $J('a[href*=listings/request_showing]').live('click', tabbedSelector);
  $J('a[href=/map]').live('click', tabbedSelector);
  $J(FixBackAndBookmarking);
}

