var IphoneView = Classe.cria();

IphoneView.prototype = {

	construtor: function(args){
	
		this.first = true;

		this.container = (args.container)?args.container:"iphone_body";
		this.loading = (args.loading)?args.loading:"iphone_loading_page";
			
		this.classGoForward = ((args.classGoForward)?args.classGoForward:"go_forward");
		this.classGoBackward = ((args.classGoBackward)?args.classGoBackward:"go_back");
		this.classGoVideo = ((args.classGoVideo)?args.classGoVideo:"go_video");
		this.goBack = false;
		
		// window.innerWidth nao performa bem, por isso "cacheamos" aqui.
		this.larguraTela;
		this.animating = false;
		
		addEventListener("load", this.onLoad.bind(this), false);
		addEventListener("click", this.onClick.bind(this), false);
	
	},
	
	loadPage: function(args){
		
		this.larguraTela = window.innerWidth;
		
		clearInterval(checkHash); // pause the history daemon during animation.

		if(args.target) args.target.className=(args.target.hasClass('no-selected'))?args.target.className:args.target.className+" selected"; 

		newpage = document.createElement("div");
		newpage.className = "iphone_page";
		newpage.style.display="block";

		$(this.container).className = "iphone_page";
		$(this.container).style.display="block";
		
		/* remove dominio da url */
		regexURL = /^(http:\/\/[^\/]*)?(.*)/;
		args.url = regexURL.exec(args.url)[2];

		this.goBack = (args.content)?History.clear():History.go(args.url);
		
		if(args.content){ //n�o faz ajax
			this.onLoadPage({responseText:args.content,disableHash:(args.disableHash)?args.disableHash:false,page:newpage})
		}
		else{
			var self = this;
			this.xml = new xmlObj( {
				url: args.url,
				obj: self,
				func: 'onLoadPage',
				args: {url:args.url,page:newpage,disableHash:(args.disableHash)?args.disableHash:false}
			});
		}
		
		
	},
	
	onLoadPage: function(args){
		this.animating = true;
		
		args.page.innerHTML = args.responseText;
		
		clearInterval(this.updateTimer);
		
		if(args.disableHash) // pagina inicial
			currentHash = "";
		else
			location.href = currentHash = "#"+args.url;
		
		/* 
		 * Track PageView:
		 *  	Predicta Atmosphere 
		 *  	Google Analytics		 
		 */ 
		if(args.url) TrackPageview.add(args.url);
		
		document.body.className = "__slide";
		
		$("glb-container").insertBefore(args.page,(this.goBack)?$(this.container):$(this.container).nextSibling);

		checkHash = setInterval(navigationChangeAgent, 300);			
		
		this.slidePage({
			page:args.page
		});
	},
	
	cancel: function(args){
		location.hash = "";
	},
	
	slidePage: function(args){
		_self = this;
		if(this.goBack){
			setTimeout(window.scrollTo, 5, args.page.offsetWidth, window.pageYOffset);
		}
		else{
			scrollTo(0,0);
		}
				
		setTimeout(function() {
			_self.slidePageTimeout( {
				page:args.page,
				s:0
			});
		}, 5);

	},
	
	ease:function(s, w, dir, step, mn) {
		s += Math.max((w - s) / step, mn || 4);
		return [s, (w + w * dir) / 2 - Math.min(s, w) * dir];
	},
	
	slidePageTimeout: function(args){
		var _self = this;
		var s = 0;
		var w = args.page.offsetWidth;
		var i = setInterval(function() {
			if (s <= w) {
				var z = _self.ease(s,w, ((_self.goBack)?+1:-1), 6, 2);
				s = z[0];window.scrollTo(z[1], 1);
				return;
			}
			clearInterval(i);
			
			$("glb-container").removeChild($(_self.container));
			
			var clone = args.page.cloneNode(true);
			$("glb-container").insertBefore(clone, args.page.nextSibling);
			
			setTimeout(function() {
				args.page.removeAttribute("style");
				args.page.removeAttribute("className");
				args.page.removeAttribute("class");
				args.page.id = _self.container;

				$("glb-container").removeChild(clone);
				
				document.body.className = "";
				
				//executa os scripts
				//execScript(args.page);

				if(backBtn = _self.$byClass("a","button-back"))
					backBtn[0].style.display = (_self.getHash())?"block":"none";
				
				_self.animating = false;

			}, 5);
			
			_self.goBack = false;

		}, 5);
	},
	
	$byClass: function(el,c){
		els = document.getElementsByTagName(el);
		ret = [];
		for(i=0;i<els.length;i++){
			if(els[i].hasClass(c))
				ret.push(els[i]);
		}
		if(ret.length > 0)
			return ret;
		else
			return false
	},
	
	getHash: function(){
		this.url = location.href.toString();
		var t = this.url.split("#");
		if(t.length>1 && t[1].length > 0)
			return t[1];
		else
			return false;
	},
	
	onLoad: function(){
		
		if(this.first) this.homePage = $(this.container).innerHTML;
		
		hash = this.getHash();
		if(hash)
			this.loadPage({url:hash,nextPage:true,disableHash:false});
		else if(!this.first)
				this.loadPage({content:this.homePage,disableHash:true});
		this.first = false;	
	},
	
	onClick: function(event){
		var a = this.findParent(event.target, "a");
		if (a && a.hasClass(this.classGoForward)) {
			this.loadPage({url:a.href,next:true,target:a});
			event.preventDefault();
			return false;
		} else if (a && a.hasClass(this.classGoBackward)) {
			history.back();
			event.preventDefault();
		}
	},
	
	findParent: function(node, localName) {
	    while (node && (node.nodeType != 1 || node.localName.toLowerCase() != localName))
	        node = node.parentNode;
	    return node;
	}
}

var iphoneView = new IphoneView({});

var currentHash = location.hash;
var currentWidth = 0;
var checkTimer = setInterval(checkOrientAndLocation, 300);
var checkHash = setInterval(navigationChangeAgent, 300);

function navigationChangeAgent() {
	if (currentHash != location.hash){
		iphoneView.onLoad();
	}
}

function checkOrientAndLocation(){
    if (window.innerWidth != currentWidth){   
        currentWidth = window.innerWidth;
        var orient = currentWidth == 320 ? "profile" : "landscape";
        document.body.setAttribute("orient", orient);
		setTimeout(scrollTo, 100, 0, 1);
    }
}

function ease(t, b, c, d){
	t /= d/2;
	if (t < 1)
		return c/2*t*t*t + b;
	t -= 2;
	return c/2*(t*t*t + 2) + b;
}

