﻿var versionString = 'Mobile Web Apps version 1.0.1223.0000';

var HistoryManager = new Class({

	Implements: [Events],

	initialize: function() {
		this._currentLocation = this._getHash();
		
		var historyManager = this;			
		
		if (window.ie) {
			this.addState = this._addStateIE;
			this._iframe = new Element('iframe', {
				src: "javascript:'<html></html>'",
				styles: {
					'position': 'absolute',
					'top': '-1000px'
				}
			}).inject(document.body).contentWindow;
			
			$justForIE = function(hash) {
				historyManager._getHash = function() { return hash; }
				historyManager._monitorDefault.call(historyManager);
				location.hash = hash;
			}
			
			function waitForIframeLoad() {
				if (historyManager._iframe && historyManager._iframe.document && historyManager._iframe.document.body) {
					if (!historyManager._iframe.document.body.innerHTML)
							historyManager.addState(historyManager._currentLocation, true);
				}
				else setTimeout(waitForIframeLoad, 50);
			}
			waitForIframeLoad();
		}
		else if (window.webkit419) {
			this._form = new Element("form", {method: 'get'}).inject(document.body);
			this._historyCounter = history.length;
			this._stateHistory = [];
			this._stateHistory[history.length] = this._getHash();
			
			this.addState = this._addStateSafari;
			this._monitorSafari.periodical(250, this);
		}
		else if (window.opera) {
			this.addState = this._addStateDefault;

			$justForOpera = function() {
				historyManager._monitorDefault.call(historyManager);
			}
			new Element('img', {
				src: "javascript:location.href='javascript:$justForOpera();';",
				style: "position: absolute; top: -1000px;"
			}).inject(document.body);
		}
		else {
			this.addState = this._addStateDefault;
			this._monitorDefault.periodical(250, this);
		}
	},
	
	getCurrentLocation: function() {
		return this._currentLocation;
	},
	
	_getHash: function() {
		return location.href.split('#')[1] || '';
	},
	
	_addStateIE: function(hash, override) {
		if (this._currentLocation == hash && !override) return;

		this._currentLocation = hash;
		this._iframe.document.write('<html><body onload="top.$justForIE(\'', hash ,'\');">Loaded</body></html>');
		this._iframe.document.close();
	},
	
	_addStateSafari: function(hash) {
		if (this._currentLocation == hash) return;

		this._form.setProperty('action', '#' + hash).submit()
		this._currentLocation = hash;
		this._stateHistory[history.length] = this._getHash();
		this._historyCounter = history.length;
	},

	_monitorSafari: function() {	
		if (history.length != this._historyCounter) {
			this._historyCounter = history.length;
			this._currentLocation = this._stateHistory[history.length];
			this.fireEvent('onHistoryChange', [this._stateHistory[history.length]]);
		}
	},

	_addStateDefault: function(hash) {
		if (this._currentLocation == hash) return;
		location.hash = '#' + hash;
		this._currentLocation = hash;
	},

	_monitorDefault: function() {
		var hash = this._getHash();

		if (hash != this._currentLocation) {
			this._currentLocation = hash;
			this.fireEvent('onHistoryChange', [hash]);
		}
	}
});


var Site = {
	Implements: [Events],

	getQS: function (key,url) {  
	    if(arguments.length < 2) url =location.href;  
	    
	    if(arguments.length > 0 && key != ""){  
	    	if(key == "#"){var regex = new RegExp("[#]([^$]*)");} 
	    	else if(key == "?"){var regex = new RegExp("[?]([^#$]*)");} 
	        else {var regex = new RegExp("[?&]"+key+"=([^&#]*)");}
	          
	        var results = regex.exec(url);  
	        return (results == null )? "" : results[1]; 
	    } 
	    
        url = url.split("?");  
        var results = {};  
        if(url.length > 1){  
            url = url[1].split("#");  
            if(url.length > 1) results["hash"] = url[1];  
            url[0].split("&").each(function(item,index){  
                item = item.split("=");  
                results[item[0]] = item[1];  
            });  
        }  
        return results;  
	},
	
	mooflow: function(history, page){
		if ($('coverflow'))
		{
			var mf = new MooFlow($('coverflow'), {
				useCaption:true, 
				useSlider:true, 
				useCaption:true,
				useResize: true,
				useMouseWheel: true,
				useKeyInput: true,
				useViewer: true,
				onClickView: function(obj){
					if (obj.href)
						Site.loadPage(history, obj.href);
				},
				onEmptyinit: function(){
					this.loadJSON('appData.php?'+Site.getQS("?",page));
				}
			});
		}
	},
	
	validateForm: function() {
		if ($('frm')) 
			new Form.Validator.Inline($('frm'), {evaluateFieldsOnBlur:false, stopOnFirst:true, errorPrefix:""});	
	},
	
	fadeIn: function () {
        var div = $('panel').setStyles({  
            display:'block',  
            opacity: 0  
        });  
		myFx = new Fx.Morph(div, { duration: 600, wait: false }).start({ opacity: 1 });
	},
	
	loadPage: function(history, selectedPage) {
		
		new Request({
			method: 'get', 
			url: selectedPage,
			evalScripts: true,
			onSuccess: function(html) {
				history.addState(selectedPage);
				$('panel').set('html',html);
				Site.fadeIn();
				Site.validateForm();
				Site.mooflow(history, selectedPage);
			}
		}).send();
	},
	
	init: function(){
	
		var history = new HistoryManager();
		var list = $$('#accordion li div.collapse');
		var headings = $$('#accordion li h2');
		var collapsibles = new Array();
		var links = $$('#accordion li div.collapse li a');	
		
		headings.each( function(heading, i) {

			var collapsible = new Fx.Slide(list[i], { 
				duration: 500, 
				transition: Fx.Transitions.quadIn
			});

			collapsible.hide();			
			collapsibles[i] = collapsible;
			
			heading.addEvent('click', function(){
				heading.setStyle('font-weight','bold');
				
				for(var j = 0; j < collapsibles.length; j++){
					if(j!=i) {
						collapsibles[j].slideOut();
						headings[j].setStyle('font-weight','normal');
					}
				}
				collapsible.toggle();
			});
		});
		
		links.each (function(link, i) {
			link.addEvent('click', function(evt){
				evt.stop();
				Site.loadPage(history, link.get('href'));
			});
		});
		
		collapsibles[2].toggle();
		headings[2].setStyle('font-weight','bold');
		
		var selected = 'pageApps.htm';
		
		if (window.location.href.indexOf("#") != -1)
			selected = window.location.href.substr(window.location.href.indexOf("#")+1);

		history.addEvent('onHistoryChange', function(hash) {
			Site.loadPage(history, hash);
		});
		history.fireEvent('onHistoryChange', selected);
    }
};

window.addEvent('domready', Site.init);

