/** 
 * Main dombehaviour
 *
 * @author Dodi Raditya
 * @version 1.0
 *
 * Note: This code works only in combination with Mootools 1.2
 */






/***
 * Main Application
 */
var App = {
  
  
  init: function() {
    if(App.browserBounce())
      return false;
    App.setupExternalLinks();
    App.setupShadows();
    App.setupFillet();
    App.setupFonts();
  },
  
   
  /** 
   * Bounce IE-users
   */
	browserBounce: function() {
	  if(Browser.Engine.trident && !document.location.toString().contains('/fail/browser')) {
	    document.location.href = '/fail/browser/';
	    return true;
	  }
	  return false;
	},
  
   
  /** 
   * Setup external links to other sites
   */
	setupExternalLinks: function() {
	  var ext = $$('a[rel="external"]');
	  ext.each(function(a) {
	    a.addEvent('click', function(e) {
	      window.open(this.href, '', '');
	      new Event(e).stop();
	    });
	  });
	},
  
   
  /** 
   * Setup shadow effects
   */
	setupShadows: function() {
	  var lomos = $$('.lomo');
	  lomos.each(function(lomo) {
	    lomo.appendChild(new Element('div', {'class': 'shadow shadow-tl', 'html':' '}));
	    lomo.appendChild(new Element('div', {'class': 'shadow shadow-t', 'html':' '}));
	    lomo.appendChild(new Element('div', {'class': 'shadow shadow-tr', 'html':' '}));
	    lomo.appendChild(new Element('div', {'class': 'shadow shadow-r', 'html':' '}));
	    lomo.appendChild(new Element('div', {'class': 'shadow shadow-br', 'html':' '}));
	    lomo.appendChild(new Element('div', {'class': 'shadow shadow-b', 'html':' '}));
	    lomo.appendChild(new Element('div', {'class': 'shadow shadow-bl', 'html':' '}));
	    lomo.appendChild(new Element('div', {'class': 'shadow shadow-l', 'html':' '}));
	  });
	},
  
   
  /** 
   * Setup fillet effects
   */
	setupFillet: function() {
	  var fillets = $$('.fillet');
	  fillets.each(function(fillet) {
	    fillet.appendChild(new Element('div', {'class': 'corner corner-tl', 'html':' '}));
	    fillet.appendChild(new Element('div', {'class': 'corner corner-tr', 'html':' '}));
	    fillet.appendChild(new Element('div', {'class': 'corner corner-br', 'html':' '}));
	    fillet.appendChild(new Element('div', {'class': 'corner corner-bl', 'html':' '}));
	  });
	},
  
   
  /** 
   * Resize body
   */
	resizeBody: function() {
	  var containerSize = $('container').getSize();
	  var viewportSize = App.getScreenSize();
	  if(containerSize.y < viewportSize.height)
	    $('container').style.height = viewportSize.height + 'px';
	},
	
  
  /** 
   * Get screen size
   */
  getScreenSize: function() {
	  var size = {
	    width: 1024,
	    height: 600
	  };
	  
	  if(typeof(window.innerWidth) == 'number') {
	    //Non-IE
	    size.width = window.innerWidth;
	    size.height = window.innerHeight;
	  }
	  else if(document.documentElement && (document.documentElement.clientWidth || document.documentElement.clientHeight)) {
	    //IE 6+ in 'standards compliant mode'
	    size.width = document.documentElement.clientWidth;
	    size.height = document.documentElement.clientHeight;
	  }
	  else if(document.body && (document.body.clientWidth || document.body.clientHeight)) {
	    //IE 4 compatible
	    size.width = document.body.clientWidth;
	    size.height = document.body.clientHeight;
	  }
	  return size;  
  },
  
   
  /** 
   * Setup custom fonts
   */
	setupFonts: function() {
	  if(!App.checkFontfaceSupport())
	    return false;

    $(document.body).addClass('custom-fonts');
	},
  
   
  /** 
   * Check fontface supported browsers
   */
	checkFontfaceSupport: function() {
    browsersInfo = [{
      name: 'Firefox',
      needle: 'Firefox',
      minVersion: 3.1
    },
    {
      name: 'Safari',
      needle: 'Version',
      minVersion: 3
    }];
    
    var uA = navigator.userAgent;
    
    for(var i=0, len = browsersInfo.length; i < len; i++) {
      var needle = browsersInfo[i].needle;
      var uAVersion = parseFloat(uA.substring(uA.indexOf(needle) + needle.length+1));
      if(uA.indexOf(name) > -1 && uAVersion >= browsersInfo[i].minVersion)
        return true;
    }
    return false;
	}
};







/***
 * Map
 */
var Map = {
  src: null,
  places: [],
  markers: [],
  headerContainer: null,
  dataDisplay: null,
  
  
  init: function() {
    this.setupMap();
    this.loadSrc();
    this.render();
    //this.setupDataDisplay();
    //this.setupSearchengine();
  },
	
	
	
	setupDataDisplay: function() {  
    this.dataDisplay = $('companies-section');
    
    this.dataDisplay.addEvent('mouseenter', function(e){
      Map.show(Map.dataDisplay);
      e.stop();
    });
    this.dataDisplay.addEvent('mouseleave', function(e){
      Map.hide(Map.dataDisplay);
      e.stop();
    });
    this.hide(this.dataDisplay);
	},


  /** 
   * Show datadisplay
   */
	show: function(el) {
	  var heightLength = '120px';
	  if(el.getElement("div.section-content-container"))
	    heightLength = el.getElement("div.section-content-container").getSize().x + 'px';
    var fx = new Fx.Morph(
      el, {
        duration: 'short',
        transition: Fx.Transitions.Quint.easeOut
      }
    );
    fx.start({
      'top': 0
    });
	},


  /** 
   * Hide datadisplay
   */
	hide: function(el) {
	  var heightLength = '120px';
	  if(el.getElement("div.section-content-container"))
	    heightLength = el.getElement("div.section-content-container").getSize().y + 'px';
    var fx = new Fx.Morph(
      el, {
        duration: 'long',
        transition: Fx.Transitions.Quint.easeOut
      }
    );
    fx.start({
      'top': '-' + heightLength
    });
	},


  /** 
   * Setup map as a global entity
   */
	setupMap: function() {  
	  if (!GBrowserIsCompatible() || !$("map"))
	    return false;
	
	  this.renderMap();
	
	  window['map'] = new GMap2($("map"));
	  window['map'].addControl(new GLargeMapControl());
	  window['map'].enableScrollWheelZoom();
	  this.setMapCenter(51.921508, 4.472122);
	},


  /** 
   * Render map as fullscreen
   */
	renderMap: function() {  
	  var screenSize = App.getScreenSize();
	  $("map").style.height = screenSize.height + 'px';
	},


	/** 
	 * Focus map to given coordinates
	 *
	 * @param  lat      latitude coordinate
	 * @param  lng      longitute coordinate
	 */
	setMapCenter: function(lat, lng, pan) {
	  if(!window['map'])
	    return false;
	
	  window['map']['center'] = new GLatLng(lat, lng);
	  if(typeof pan == 'undefined')
	    window['map'].setCenter(window['map']['center'], 3);
	  else
	    window['map'].panTo(window['map']['center']);
	},
	
	
	geoLocate: function(address) {
	  
	},
	
	
	loadSrc: function() {
    var vcards = $$('div.vcard');
	  for(var i = 0, len = vcards.length; i < len; i++) {
	    Map.places.push(new Company(vcards[i]));
	  }
	},
		
	
	renderPlace: function(place) {
	  var point = new GLatLng(place.lat, place.lng);
	  var marker = new GMarker(point);
	  GEvent.addListener(marker, "click", function() {
	    var placehtml = "<div class=\"mapplace\">";
	    placehtml += "<h3><a href=\""+ place.url +"\">" + place.name + "</a></h3>";
	    placehtml += "<p>" + place.street + "</p>";
	    placehtml += "<p>" + place.city + ", " + place.country + "</p>";
	    placehtml += "</div>";
      marker.openInfoWindowHtml(placehtml);
    });

    window['map'].addOverlay(marker);
    this.markers.push(marker);
	},
	
	
	removeMarkers: function() {
	  this.places = [];
	  window['map'].clearOverlays();
	},
	
	
	render: function() {    
    for(var i=0, len=this.places.length; i < len; i++ ) {
      var place = this.places[i];
      this.renderPlace(place);
      
      this.places[i].companyEl.lat = place.lat;
      this.places[i].companyEl.lng = place.lng;
      
	    this.places[i].companyEl.addEvent('click', function(e) {
	      this.setMapCenter(this.lat, this.lng);
	      new Event(e).stop();
	    });
      
    }
	},
	
	
	setupSearchengine: function() {
	  var companiesFinder = $('companies-finder');
	  if(!companiesFinder)
	    return false;
	  
	  companiesFinder.addEvent('submit', function(e) {
  	  var myRequest = new Request({
  	    url: '/companies/find/' + escape($('q').value.toLowerCase()),
        onComplete: function(response) {
          $('searchresults').innerHTML = response;
          Map.removeMarkers();
          Map.loadSrc();
          Map.render();
        }
  	  }).send();
	    e.stop();
	  });
	  
	  var q = $('q');
	  if(!q)
	    return false;
	  
	  q.addEvent('focus', function(e) {
	    if(this.value == 'Company')
	      this.value = '';
	    e.stop();
	  });
	}
	

};






/***
 *  CLASS: Company
 */
function Company(companyEl) {
  this.companyEl = companyEl;
  this.load();
}
Company.prototype = {
  load: function() {
    if(!this.companyEl)
      return false;
    
    this.name = this.stripValue('a.org');
    this.url = this.companyEl.getElement('a.org').href;
    this.street = this.stripValue('div.street-address');
    this.city = this.stripValue('span.locality');
    this.country = this.stripValue('span.country-name');
    this.lat = this.stripValue('div.lat');
    this.lng = this.stripValue('div.lng');
    this.description = this.stripValue('p.description');
  },
  
  stripValue: function(selector) {
    if(this.companyEl.getElement(selector).firstChild)
      return this.companyEl.getElement(selector).firstChild.nodeValue;
    return '';
  }
};







/***
 * ElementsOverview
 */
var ElementsOverview = {


  init: function() {},
  

  /** 
	 * Setup elementslists
	 */
	setupElementslist: function() {
	  var i = 0;
	  var elementsTitles = $$('div.elements-container dt');
	  elementsTitles.each(function (title) {
	    title.id = 'element-title-' + i;
	    title.addEvent('click', function(e) {
	      var descId = 'element-desc-' + this.id.substring(14);
	      $(descId).hasClass('el-desc-show') ? 
	        $(descId).removeClass('el-desc-show') : 
	        $(descId).addClass('el-desc-show');
	      new Event(e).stop();
	    });
	    i++;
	  });
	  
	  var j = 0;
	  var elementsDescriptions = $$('div.elements-container dd');
	  elementsDescriptions.each(function (desc) {
	    desc.id = 'element-desc-' + j++;
	  });
	}
};







/***
 * CompanySearch
 */
function CompanySearch() {
  this.form = null;
  this.container = null;
}

CompanySearch.prototype = {
  init: function() {
    if(!this.loadComponents())
      return false;
    
    this.setup();
  },
  
  loadComponents: function() {
    this.form = $('company-search');
    this.container = $('companies-container');
    if(!this.form || !this.container)
      return false;
    
    return true;
  },
  
  setup: function() {
    var that = this;
    var searchform = that.form;
    var container = that.container;
    var formfields = searchform.getElements("input");
    formfields.each(function(field) {
      if(field.getAttribute('type') == 'checkbox') {
        field.addEvent('change', function(e) {
          that.update();
          e.stop();
        });
      }
      if(field.getAttribute('type') == 'text') {
        field.addEvent('keyup', function(e) {
          that.update();
          e.stop();
        });
      }
    });
    
    $('q').addEvent('focus', function() {
      if(this.value == 'type city')
        this.value = '';
    });
    $('q').addEvent('blur', function() {
      if(this.value == '')
        this.value = 'type city';
    });
    that.update();
  },
  
  update: function() {
    var that = this;
    var container = this.container;
    var searchform = this.form;
    var req = new Request.HTML({
      url:'/companies/find/',
      onSuccess: function(responseTree, responseElements, responseHTML) {
        container.set('html', responseHTML);
        that.setupEvents();
      }
    }).post(searchform);  
  },
  
  setupEvents: function() {
    var ext = this.container.getElements('a[rel="external"]');
	  ext.each(function(a) {
	    a.addEvent('click', function(e) {
	      window.open(this.href, '', '');
	      new Event(e).stop();
	    });
	  });
  }
};









/** 
 * Setup @ DOMloaded event
 */
function onLoaded(func) {
  window.addEvent('load', func);
}



/** 
 * Initialize startup functions
 */
onLoaded(App.init);
onLoaded(function() {
  var cSearch = new CompanySearch();
  cSearch.init();

  if($(document.body).hasClass('companies')) {
    Map.init();
  }
});
window.addEvent('resize', function() {
  if($(document.body).hasClass('companies')) {
    Map.renderMap();
  }
});

onLoaded(ElementsOverview.setupElementslist);
onLoaded(function() {
  $(document.body).addClass('js-enhanced');
});






