// 
//  iphone.js
//  okonet.ru
//  
//  Created by Andrey Okonetchnikov on 2010-07-28.
//  Copyright 2010 Andrey Okonetchnikov (andrej.okonetschnikow@gmail.com). All rights reserved.
// 

var iPhone = {
  
  initialize: function(){
    iPhone.updateOrientation();
    iPhone.hideURLBar();
    
		window.addEventListener("orientationchange", iPhone.updateOrientation, false);
		window.addEventListener("orientationchange", iPhone.hideURLBar, false);
		
		window.addEventListener('touchstart', iPhone.handleEvent, false);
  	window.addEventListener('touchmove', iPhone.handleEvent, false);
  	window.addEventListener('touchend', iPhone.handleEvent, false);
  },
  
  handleEvent: function (e) {
		switch (e.type) {
			case 'touchstart': iPhone.onTouchStart(e); break;
			case 'touchmove': iPhone.onTouchMove(e); break;
			case 'touchend': iPhone.onTouchEnd(e); break;
		}
	},
	
	onTouchStart: function(e){
    if (e.targetTouches.length != 1) return false;
    e.preventDefault();
    e.stopPropagation();
    this.moved = false;
  },

  onTouchMove: function(e){
    if (e.targetTouches.length != 1) return false;
    this.moved = true;
  },

  onTouchEnd: function(e){
    if (e.targetTouches.length > 0) return false;
    if (!this.moved) {
      var theEvent = document.createEvent('MouseEvents');
      theEvent.initMouseEvent("click", true, true, document.defaultView, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, null);
      e.changedTouches[0].target.dispatchEvent(theEvent);		
      return false;
    }
  },
  
  // Hide the annoying load bar
  hideURLBar: function() {
    setTimeout(function() { window.scrollTo(false, 0); }, 1);
  },
  
  // updateOrientation checks the current orientation, sets the body's class attribute to portrait,
  updateOrientation: function(){
    var orientation = window.orientation;
		switch (orientation) {			
			// If we're horizontal
			case 90:
			case -90:
			
			// Set orient to landscape
			document.body.setAttribute('orient', 'landscape');
      document.body.className = document.body.className.replace(new RegExp('(^|\\s)orient-portrait(?:\\s|$)'), '$1'); // Remove classname
      document.body.className = document.body.className + ' orient-landscape';
			break;	
			
			// If we're vertical
			case 0:
			case 180:
			
			// Set orient to portrait
			document.body.setAttribute('orient', 'portrait');
			document.body.className = document.body.className.replace(new RegExp('(^|\\s)orient-landscape(?:\\s|$)'), '$1'); // Remove classname
      document.body.className = document.body.className + ' orient-portrait';
			break;
			
			// Orientation doesn't supported, set nothing
			default:
			break;
		}
  }
};

// Fire on load
if(typeof(window.orientation) !== 'undefined'){
(function(){
  document.addEventListener('DOMContentLoaded', this.initialize, false);
}).call(iPhone);
}
