/* Copyright 2006-2010 Panagiotis Tsimpoglou. All rights reserved. */
//http://slides.html5rocks.com/#slide8
(function($) {
  $.fn.outerHTML = function() {
    //return $(this).clone().wrap('<div></div>').parent().html();
		if($(this).attr('outerHTML')) {
    	return $(this).attr('outerHTML');
		} else {
    	var content = $(this).wrap('<div></div>').parent().html();
			$(this).unwrap();
			return content;
    }
  }
})(jQuery);

(function($) {
  $.fn.hasAttr = function(name) {  
		return (typeof(this.attr(name)) !== 'undefined' && this.attr(name) !== false);
	};
})(jQuery);

/* Simple JavaScript Inheritance
 * By John Resig http://ejohn.org/
 * MIT Licensed.
 */
// Inspired by base2 and Prototype
(function(){
  var initializing = false, fnTest = /xyz/.test(function(){xyz;}) ? /\b_super\b/ : /.*/;
  // The base Class implementation (does nothing)
  this.Class = function(){};
  
  // Create a new Class that inherits from this class
  Class.extend = function(prop) {
    var _super = this.prototype;
    
    // Instantiate a base class (but only create the instance,
    // don't run the init constructor)
    initializing = true;
    var prototype = new this();
    initializing = false;
    
    // Copy the properties over onto the new prototype
    for (var name in prop) {
      // Check if we're overwriting an existing function
      prototype[name] = typeof prop[name] == "function" && 
        typeof _super[name] == "function" && fnTest.test(prop[name]) ?
        (function(name, fn){
          return function() {
            var tmp = this._super;
            
            // Add a new ._super() method that is the same method
            // but on the super-class
            this._super = _super[name];
            
            // The method only need to be bound temporarily, so we
            // remove it when we're done executing
            var ret = fn.apply(this, arguments);        
            this._super = tmp;
            
            return ret;
          };
        })(name, prop[name]) :
        prop[name];
    }
    
    // The dummy class constructor
    function Class() {
      // All construction is actually done in the init method
      if ( !initializing && this.init )
        this.init.apply(this, arguments);
    }
    
    // Populate our constructed prototype object
    Class.prototype = prototype;
    
    // Enforce the constructor to be what we expect
    Class.constructor = Class;

    // And make this class extendable
    Class.extend = arguments.callee;
    
    return Class;
  };
})();


var Anamo = new Object();

/*
Anamo.Javascript.LoadScript('http://localhost:8080/labsonstaticacustomerservice/js/jquery.timer.js', function() { $.timer(2000, function(timer) {alert(1);});});
*/
Anamo.Javascript = new Object();

Anamo.Javascript.LoadScript = function(ByValScriptURI, ByValOnReadyState) {
	var head = document.getElementsByTagName('head')[0];
	var script = document.createElement('script');
	script.type= 'text/javascript';
	script.onreadystatechange = function() {
		if(this.readyState == 'complete') {
			ByValOnReadyState();
		}
	}
	script.async = true;
	script.onload = ByValOnReadyState;
	script.src = ByValScriptURI;
	head.appendChild(script);
};









Anamo.Core = new Object();

String.prototype.contains = function(it) { return this.indexOf(it) != -1; };

Anamo.Core.ObjectCount = function(obj) {
	var size = 0;
	for(var key in obj) {
		if (obj.hasOwnProperty(key)) size++;
	}
	return size;
};

Anamo.Core.VarDump = function(arr,level) {
	/**
	 * Function : dump()
	 * Arguments: The data - array,hash(associative array),object
	 *    The level - OPTIONAL
	 * Returns  : The textual representation of the array.
	 * This function was inspired by the print_r function of PHP.
	 * This will accept some data as the argument and return a
	 * text that will be a more readable version of the
	 * array/hash/object that is given.
	 * Docs: http://www.openjs.com/scripts/others/dump_function_php_print_r.php
	 */
	var dumped_text = "";
	if(!level) level = 0;
	
	//The padding given at the beginning of the line.
	var level_padding = "";
	for(var j=0;j<level+1;j++) level_padding += "    ";
	
	if(typeof(arr) == 'object') { //Array/Hashes/Objects 
		for(var item in arr) {
			var value = arr[item];
			
			if(typeof(value) == 'object') { //If it is an array,
				dumped_text += level_padding + "'" + item + "' ...\n";
				dumped_text += Anamo.Core.VarDump(value,level+1);
			} else {
				dumped_text += level_padding + "'" + item + "' => \"" + value + "\"\n";
			}
		}
	} else { //Stings/Chars/Numbers etc.
		dumped_text = "===>"+arr+"<===("+typeof(arr)+")";
	}
	return dumped_text;
};

Anamo.Core.EventExists = function(eventName, element) {
	var TAGNAMES = {
		'select':'input','change':'input',
		'submit':'form','reset':'form',
		'error':'img','load':'img','abort':'img'
	};
	element = element || document.createElement(TAGNAMES[eventName] || 'div');
	eventName = 'on' + eventName;
	
	var isSupported = (eventName in element);
	
	if (!isSupported) {
		// if it has no `setAttribute` (i.e. doesn't implement Node interface), try generic element
		if (!element.setAttribute) {
			element = document.createElement('div');
		}
		if (element.setAttribute && element.removeAttribute) {
			element.setAttribute(eventName, '');
			isSupported = typeof element[eventName] == 'function';

			// if property was created, "remove it" (by setting value to `undefined`)
			if (typeof element[eventName] != 'undefined') {
				element[eventName] = 'undefined';
			}
			element.removeAttribute(eventName);
		}
	}
	
	element = null;
	return isSupported;
}

Anamo.Core.GenerateRandomString = function(Length) {
    var text = "";
    var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

    for( var i=0; i < Length; i++ ) {
        text += possible.charAt(Math.floor(Math.random() * possible.length));
		}
    return text;
}

Anamo.Core.HTMLSpecialChars = function (string, quote_style, charset, double_encode) {
	// http://phpjs.org/functions/htmlspecialchars:426
	// Convert special characters to HTML entities  
	// 
	// version: 1103.1210
	// discuss at: http://phpjs.org/functions/htmlspecialchars
	// +   original by: Mirek Slugen
	// +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
	// +   bugfixed by: Nathan
	// +   bugfixed by: Arno
	// +    revised by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
	// +    bugfixed by: Brett Zamir (http://brett-zamir.me)
	// +      input by: Ratheous
	// +      input by: Mailfaker (http://www.weedem.fr/)
	// +      reimplemented by: Brett Zamir (http://brett-zamir.me)
	// +      input by: felix
	// +    bugfixed by: Brett Zamir (http://brett-zamir.me)
	// %        note 1: charset argument not supported
	// *     example 1: htmlspecialchars("<a href='test'>Test</a>", 'ENT_QUOTES');
	// *     returns 1: '&lt;a href=&#039;test&#039;&gt;Test&lt;/a&gt;'
	// *     example 2: htmlspecialchars("ab\"c'd", ['ENT_NOQUOTES', 'ENT_QUOTES']);
	// *     returns 2: 'ab"c&#039;d'
	// *     example 3: htmlspecialchars("my "&entity;" is still here", null, null, false);
	// *     returns 3: 'my &quot;&entity;&quot; is still here'
	var optTemp = 0,
			i = 0,
			noquotes = false;
	if (typeof quote_style === 'undefined' || quote_style === null) {
			quote_style = 2;
	}
	string = string.toString();
	if (double_encode !== false) { // Put this first to avoid double-encoding
			string = string.replace(/&/g, '&amp;');
	}
	string = string.replace(/</g, '&lt;').replace(/>/g, '&gt;');

	var OPTS = {
			'ENT_NOQUOTES': 0,
			'ENT_HTML_QUOTE_SINGLE': 1,
			'ENT_HTML_QUOTE_DOUBLE': 2,
			'ENT_COMPAT': 2,
			'ENT_QUOTES': 3,
			'ENT_IGNORE': 4
	};
	if (quote_style === 0) {
			noquotes = true;
	}
	if (typeof quote_style !== 'number') { // Allow for a single string or an array of string flags
			quote_style = [].concat(quote_style);
			for (i = 0; i < quote_style.length; i++) {
					// Resolve string input to bitwise e.g. 'PATHINFO_EXTENSION' becomes 4
					if (OPTS[quote_style[i]] === 0) {
							noquotes = true;
					} else if (OPTS[quote_style[i]]) {
							optTemp = optTemp | OPTS[quote_style[i]];
					}
			}
			quote_style = optTemp;
	}
	if (quote_style & OPTS.ENT_HTML_QUOTE_SINGLE) {
			string = string.replace(/'/g, '&#039;');
	}
	if (!noquotes) {
			string = string.replace(/"/g, '&quot;');
	}

	return string;
}

/*
*
*	jQuery Timer plugin v0.1
*		Matt Schmidt [http://www.mattptr.net]
*
*	Licensed under the BSD License:
*		http://mattptr.net/license/license.txt
*
*/

Anamo.Core.Timer = function(interval, callback) {
/**
*
* timer() provides a cleaner way to handle intervals  
*
*	@usage
* $.timer(interval, callback);
*
*
* @example
* $.timer(1000, function (timer) {
* 	alert("hello");
* 	timer.stop();
* });
* @desc Show an alert box after 1 second and stop
* 
* @example
* var second = false;
*	$.timer(1000, function (timer) {
*		if (!second) {
*			alert('First time!');
*			second = true;
*			timer.reset(3000);
*		}
*		else {
*			alert('Second time');
*			timer.stop();
*		}
*	});
* @desc Show an alert box after 1 second and show another after 3 seconds
*
* 
*/

	var interval = interval || 100;
	
	if (!callback)
		return false;
	
	_timer = function (interval, callback) {
		this.stop = function () {
			clearInterval(self.id);
		};
		
		this.internalCallback = function () {
			callback(self);
		};
		
		this.reset = function (val) {
			if (self.id)
				clearInterval(self.id);
			
			var val = val || 100;
			this.id = setInterval(this.internalCallback, val);
		};
		
		this.interval = interval;
		this.id = setInterval(this.internalCallback, this.interval);
		
		var self = this;
	};
	
	return new _timer(interval, callback);
};









Anamo.Core.Tracking = new Object();

Anamo.Core.Tracking.InitilizeGoogleAnalytics = function() {
	try {
		var _gaq = _gaq || [];
		_gaq.push(['_setAccount', 'UA-4448808-1']);
		_gaq.push(['_setDomainName', 'none']);
		_gaq.push(['_setAllowLinker', true]);
		_gaq.push(['_setAllowHash', false]);
		_gaq.push(['_trackPageview']);
	} catch(ex) {}
};









/*
	Requires Google Translate API.
*/
Anamo.Globalization = new Object();

Anamo.Globalization.TranslateResource = function(Resource, ToLanguageIsoAlpha2Key, OnSuccessToTrigger) {
	if(Resource) {
		google.language.translate(Resource, '', ToLanguageIsoAlpha2Key, OnSuccessToTrigger);
	}
};









Anamo.Presentation = new Object();

/*Anamo.Presentation.VarDump = function(arr,level) {
	*
	 * Function : dump()
	 * Arguments: The data - arr
	 return dumped_text;
};*/








Anamo.Presentation.Messages = new Object();

Anamo.Presentation.Messages.PreparePHPMessages = function() {
	// Events.
	$('.anamo-ws-msgdiv').live('click', function(e) {
		try {
			var elem0 = $(this).find('canvas');
			elem0.html('1');
		} catch(ex) {}
		$(this).fadeOut(555);
		return false;
	});
	// Positioning.
	if($('.anamo-ws-msgdiv').length > 0) {
		$('.anamo-ws-msgdiv').slideDown('fast', function() {
			if($('.anamo-ws-msgdiv').length > 1) {
				var offset = $('.anamo-ws-msgdiv:eq(0)').offset();
				$('.anamo-ws-msgdiv:eq(1)').css('top', offset.top + $('.anamo-ws-msgdiv:eq(0)').height()+22+'px');
			}
		});
		$('.anamo-ws-msgdiv').each(function(intIndex) {
			// Position.
			Anamo.Presentation.Messages.PositionMessage($(this), intIndex);
			
			// Progress bar.
			Anamo.Presentation.Messages.PrepareMessageProgressbar($(this), 12);
		});
		Anamo.Core.Timer(12000, function(timer) {
			$('.anamo-ws-msgdiv').fadeOut(5000);
			timer.stop();
		});
	}
};

Anamo.Presentation.Messages.PositionMessage = function(Element, intIndex) {
	Element.css('margin-left', '-'+Element.width() / 2+'px');
	if(intIndex > 0) {
		var PreviousMessage = $('.anamo-ws-msgdiv:eq('+(intIndex - 1)+')');
		var offset = PreviousMessage.offset();
		Element.css('top', offset.top + PreviousMessage.height()+22+'px');
	}
};

Anamo.Presentation.Messages.PrepareMessageProgressbar = function(MsgDiv, Interval) {
	try {
		var elem0 = MsgDiv.find('canvas');
		var elem = elem0.get(0);
		var context = elem.getContext('2d');
		
		if(MsgDiv.hasClass('warning')) {
			context.strokeStyle = '#f171aa';
		} else {
			context.strokeStyle = '#8db05a';
		}
		context.fillStyle = 'transparent';
		context.lineWidth = 2;
		context.lineCap = 'round';
		context.translate(3, 19);
		context.rotate(-90 * Math.PI / 180);
		context.shadowBlur = 2.6;
		context.shadowColor = '#adadad';
		
		Anamo.Core.Timer(100, function(timer) {
			elem0.html(new Number(elem0.html()) + new Number(parseFloat(1 / Interval / 10).toPrecision(2)));
			context.clearRect(0, 0, 22, 22);
			context.beginPath();
			context.arc(8, 8, 6, 0, parseFloat(elem0.html()) * (Math.PI * 2), false);
			context.stroke();
			if(parseFloat(elem0.html()) >= 1) {
				timer.stop();
			}
		});
	} catch(ex) {}
};

Anamo.Presentation.Messages.ShowNotification = function(Root, Type, Content, Title, ToLanguageIsoAlpha2Key) {
	Anamo.Globalization.TranslateResource(Content, ToLanguageIsoAlpha2Key, function(result) {
		if(!result.error) {
			TranslatedContent = result.translation;
			if(Title) {
				Anamo.Globalization.TranslateResource(Title, ToLanguageIsoAlpha2Key, function(result) {
					if(!result.error) {
						TranslatedTitle = result.translation;
						
						$(Root).prepend('<div class="anamo-ws-msgdiv '+Type+'"><div><div class="hdr"><div class="anamo-ui-large anamo-ui-strong">'+TranslatedTitle+'</div><canvas width="22" height="22"></canvas></div><div>'+TranslatedContent+'</div></div></div>');
						var NewlyAddedElement = $(Root).children('.anamo-ws-msgdiv:first');
						NewlyAddedElement.slideDown('fast', function() {
							$('.anamo-ws-msgdiv').each(function(intIndex) {
								// Position.
								Anamo.Presentation.Messages.PositionMessage($(this), intIndex);
							});
							// Progress bar.
							Anamo.Presentation.Messages.PrepareMessageProgressbar($(this), 12);
							Anamo.Core.Timer(12000, function(timer) {
								NewlyAddedElement.fadeOut(5000, function() {
									$(this).remove();
								});
								timer.stop();
							});
						});
					}
				});
			} else {
				$(Root).prepend('<div class="anamo-ws-msgdiv '+Type+'"><div><div class="hdr"><div class="anamo-ui-large anamo-ui-strong"></div><canvas width="22" height="22"></canvas></div><div>'+TranslatedContent+'</div></div></div>');
				var NewlyAddedElement = $(Root).children('.anamo-ws-msgdiv:first');
				NewlyAddedElement.slideDown('fast', function() {
					$('.anamo-ws-msgdiv').each(function(intIndex) {
						// Position.
						Anamo.Presentation.Messages.PositionMessage($(this), intIndex);
					});
					// Progress bar.
					Anamo.Presentation.Messages.PrepareMessageProgressbar($(this), 12);
					Anamo.Core.Timer(12000, function(timer) {
						NewlyAddedElement.fadeOut(5000, function() {
							$(this).remove();
						});
						timer.stop();
					});
				});
			}
		}
	});
};









Anamo.Presentation.ContextMenus = new Object();

Anamo.Presentation.ContextMenus.HasContextMenuAction = false;
Anamo.Presentation.ContextMenus.SmartHideMenus = function(e) {
	if(e) {
		var CParent = $(e.target).parents('.anamo-ui-contextmenu:first');
		if(CParent.length == 0) {
			$('.anamo-ui-contextmenu').each(function(intIndex) {
				$(this).parents('*.selected:first').removeClass('selected');
			});
			$('.anamo-ui-contextmenu').hide();
		} else {
			var CParentIndex = $('.anamo-ui-contextmenu').index(CParent);
			$('.anamo-ui-contextmenu').each(function(intIndex) {
				if($('.anamo-ui-contextmenu').index($(this)) != CParentIndex) {
					$(this).parents('*.selected:first').removeClass('selected');
					$(this).hide();
				}
			});
		}
	} else {
		$('.anamo-ui-contextmenu').each(function(intIndex) {
			$(this).parents('*.selected:first').removeClass('selected');
		});
		$('.anamo-ui-contextmenu').hide();
	}
};

Anamo.Presentation.ContextMenus.ToggleMyContextMenu = function(Element, e) {
	var HasDiv = Element.parents('*:first').children('.anamo-ui-contextmenu');
	if(HasDiv.length > 0) {
		if(HasDiv.css('display') != 'none') {
			Anamo.Presentation.ContextMenus.SmartHideMenus(e);
			return false;
		}
		Anamo.Presentation.ContextMenus.SmartHideMenus(e);
		Element.parents('*:first').addClass('selected');
		HasDiv.show();
		this.HasContextMenuAction = true;
	}
};









Anamo.Web = new Object();

Anamo.Web.ParseUrlVariables = function(url, startofparams, startofparamsoffset) {
	var startOfQueryString = url.indexOf(startofparams);
	
	var urlParams = {};
	var e,
		a = /\+/g,  // Regex for replacing addition symbol with a space
		r = /([^&=]+)=?([^&]*)/g,
		d = function (s) { return decodeURIComponent(s.replace(a, " ")); },
		q = (startOfQueryString == -1? url: url.substring(startOfQueryString + startofparamsoffset));
		
	while (e = r.exec(q)) {
		urlParams[d(e[1])] = d(e[2]);
	}
	
	return urlParams;
};









Anamo.ArrayList = new Object();

Anamo.ArrayList.Remove = function(Arr, What) {
	for(var i in Arr) {
		if(Arr[i] == What) {
			Arr.splice(i, 1);
			break;
		}
	}
};/* Copyright 2006-2010 Panagiotis Tsimpoglou. All rights reserved. */
/*
var ff = new Anamo.Notifications();
	ff.OnClose = function() {alert('closed')};
	ff.RequestPermissions(function() {
	ff.Show('assa', 'asas', 'fgfg');
});
*/
Anamo.Notifications = function() {};
Anamo.Notifications.prototype.OnDisplay = function() {};
Anamo.Notifications.prototype.OnClose = function() {};

Anamo.Notifications.prototype.HasPermissions = function() {
	if(window.webkitNotifications) {
		return (window.webkitNotifications.checkPermission() == 0);
	}
	return false;
};
Anamo.Notifications.prototype.RequestPermissions = function(ByValCallBack) {
	if(!window.webkitNotifications) {
		return false;
	}
	if(this.HasPermissions()) {
		return ByValCallBack();
	}
	window.webkitNotifications.requestPermission((typeof(ByValCallBack) == 'undefined' || typeof(ByValCallBack) != 'function'? function() {}: ByValCallBack));
	return false;
};
Anamo.Notifications.prototype.Show = function(ByValIconUrl, ByValTitle, ByValMessage) {
	if(!window.webkitNotifications) {
		return false;
	}
	var popup = window.webkitNotifications.createNotification(ByValIconUrl, ByValTitle, ByValMessage);
	popup.ondisplay = this.OnDisplay;
	popup.onclose = this.OnClose;
	popup.show();
	return true;
};
Anamo.Notifications.prototype.ShowHtml = function(ByValHTMLUrl) {
	if(window.webkitNotifications) {
		return false;
	}
	var popup = window.webkitNotifications.createHTMLNotification(ByValHTMLUrl);
	popup.ondisplay = this.OnDisplay;
	popup.onclose = this.OnClose;
	popup.show();
	return true;
};/* Copyright 2006-2010 Panagiotis Tsimpoglou. All rights reserved. */
/*
#Example.
Imports Jquery;
var ff = new Anamo.Navigation({ autoInitialize:true });

<body>
	<div data-role="page"></div>
	<div data-role="page"></div>
</body>
*/
Anamo.Navigation = function(options) {
	if(typeof(options) != 'undefined') {
		if(typeof(options.ns) != 'undefined') {alert(123);
			this.ns = options.ns;
		}
	}
	var Me = this;
	if(!Anamo.Core.EventExists('hashchange')) {
		Anamo.Core.Timer(1, function(timer) {
			if(Me.PageHash != window.location.hash) {
				var OldHash = Me.PageHash;
				Me.PageHash = window.location.hash;
				$(Me).trigger('hashchange', [OldHash]);
			}
		});
	} else {
		$(window).bind('hashchange', function(e) {
			var OldHash = Me.PageHash;
			Me.PageHash = window.location.hash;
			$(Me).trigger('hashchange', [OldHash]);
		});
	}
	if(typeof(options) != 'undefined') {
		if(typeof(options.autoInitialize) != 'undefined') {
			$(document).bind('ready', function(e) {
				Me.initializePage();
			});
		}
	}
};
Anamo.Navigation.prototype.ns = ''; //"mynamespace-"
Anamo.Navigation.prototype.activePageClass = 'anamo-ui-page-active';
Anamo.Navigation.prototype.transitionPageClass = 'anamo-ui-page-transition';
Anamo.Navigation.prototype.pageLoadingClass = 'anamo-ui-page-loading';
Anamo.Navigation.prototype.xhr = null;
Anamo.Navigation.prototype.xhrList = [];
Anamo.Navigation.prototype.defaultTransition = 'slide';
Anamo.Navigation.prototype._transitions = {
	slide: {
		normalClass: 'slide',
		reverseClass: 'revert',
		normalDuration: 300,
		reverseDuration: 300
	},
	slideup: {
		normalClass: 'vertical',
		reverseClass: 'revertical',
		normalDuration: 350,
		reverseDuration: 300
	}
};
Anamo.Navigation.prototype.pageContainer = null;
Anamo.Navigation.prototype.PageHash = window.location.hash;
Anamo.Navigation.prototype.PageHashVariables = {};
Anamo.Navigation.prototype.ExtendVarsDictionary = {};

Anamo.Navigation.prototype.initializePage = function(p) {
	if(this.pageContainer == null) {
		this.pageContainer = $('body');
	}
	if(p != null) {
		p.trigger('pagebeforecreate');
		// do stuff.
		if(!p.attr('data-'+this.ns+'url') && p.attr('id')) {
			p.attr('data-'+this.ns+'url', '#'+p.attr('id'));
		}
		// do stuff.
		p.trigger('pagecreate');
	} else {
		this.pageContainer.children('*[data-'+this.ns+'role=page]').trigger('pagebeforecreate');
		// do stuff.
		var Me = this;
		this.pageContainer.children('*[data-'+this.ns+'role=page]:not([data-'+this.ns+'url])[id]').each(function(intIndex) {
			$(this).attr('data-'+Me.ns+'url', '#'+$(this).attr('id'));
		});
		var CurrentPage = this.currentPage();
		if(CurrentPage) {
			if(!CurrentPage.hasClass(this.activePageClass)) {
				CurrentPage.addClass(this.activePageClass);
			}
		}
		// do stuff.
		this.pageContainer.children('*[data-'+this.ns+'role=page]').trigger('pagecreate');
		
		$(this).trigger('navinit');
	}
	$(this).trigger('navready');
};

Anamo.Navigation.prototype.currentPage = function() {
	var CurrentPage = this.pageContainer.children('*[data-'+this.ns+'role=page].'+this.activePageClass);
	if(CurrentPage.length == 0) {
		CurrentPage = this.pageContainer.children('*[data-'+this.ns+'role=page]:first');
	}
	if(CurrentPage.length == 0) {
		return null;
	}
	return CurrentPage;
};

Anamo.Navigation.prototype._pageLoading = function(what) {
	var ToShow = (what? (what == true? false: true): true);
	if(ToShow) {
		$('.'+this.pageLoadingClass).addClass('anamo-ui-isvisible');
	} else {
		$('.'+this.pageLoadingClass).removeClass('anamo-ui-isvisible');
	}
};
Anamo.Navigation.prototype.showPageLoadingMsg = function() {
	this._pageLoading();
};
Anamo.Navigation.prototype.hidePageLoadingMsg = function() {
	this._pageLoading(true);
};




Anamo.Navigation.prototype._changePage = function(CurrentPage, NextPage, TransitionProperty, IsReverseAnimationProperty, ChangeHashProperty) {
	// Trigger event.
	$(this).trigger('navigating');
	
	if(CurrentPage) {
		CurrentPage.trigger('pagebeforehide');
	}
	NextPage.trigger('pagebeforeshow');
	
	// Trigger events AND add classes.
	this.pageContainer.children('*[data-'+this.ns+'role=page]').removeClass(this.activePageClass).removeClass('in').removeClass('out');
	for(var i in this._transitions) {
		var Transition = this._transitions[i];
		this.pageContainer.children('*[data-'+this.ns+'role=page]').removeClass(Transition['normalClass']).removeClass(Transition['reverseClass']);
	}
	
	// Transition OR Not.
	var Me = this;
	if(TransitionProperty == 'slide' || TransitionProperty == 'slideup') {
		$(Me).trigger('navanimationstart', [TransitionProperty]);
		
		if(TransitionProperty == 'slideup') {
			//var PageToTransition = (IsReverseAnimationProperty? CurrentPage: NextPage);
			if(CurrentPage) {
				CurrentPage.addClass(Me.transitionPageClass).addClass(Me._transitions[TransitionProperty][(IsReverseAnimationProperty? 'reverse': 'normal')+'Class']).addClass('out');
			}
			NextPage.addClass(Me.transitionPageClass).addClass(Me._transitions[TransitionProperty][(IsReverseAnimationProperty? 'reverse': 'normal')+'Class']).addClass('in');
		} else {
			if(CurrentPage) {
				CurrentPage.addClass(Me.transitionPageClass).addClass(Me._transitions[TransitionProperty][(IsReverseAnimationProperty? 'reverse': 'normal')+'Class']).addClass('out');
			}
			NextPage.addClass(Me.transitionPageClass).addClass(Me._transitions[TransitionProperty][(IsReverseAnimationProperty? 'reverse': 'normal')+'Class']).addClass('in');
		}
		
		$(Me).trigger('navanimationstart2', [TransitionProperty]);
		
		CurrentPage.one('webkitAnimationEnd', function(e) {
			CurrentPage.trigger('pagehide').removeClass(Me.transitionPageClass);
		});
		NextPage.one('webkitAnimationEnd', function(e) {
			NextPage.trigger('pageshow').removeClass(Me.transitionPageClass).addClass(Me.activePageClass);
			if(ChangeHashProperty && NextPage.attr('data-'+Me.ns+'url')) {
				window.location.hash = (NextPage.attr('data-'+Me.ns+'url').substring(0, 1) != '#'? '#!': '')+NextPage.attr('data-'+Me.ns+'url');
			}
			$(Me).trigger('navigated');
		});
		/*Anamo.Core.Timer(Me._transitions[TransitionProperty][(IsReverseAnimationProperty? 'reverse': 'normal')+'Duration'], function(timer) {
			if(CurrentPage) {
				CurrentPage.trigger('pagehide').removeClass(Me.transitionPageClass);
			}
			NextPage.trigger('pageshow').removeClass(Me.transitionPageClass).addClass(Me.activePageClass);
			if(ChangeHashProperty && NextPage.attr('data-'+Me.ns+'url')) {
				window.location.hash = (NextPage.attr('data-'+Me.ns+'url').substring(0, 1) != '#'? '#!': '')+NextPage.attr('data-'+Me.ns+'url');
			}
			$(Me).trigger('navigated');
			timer.stop();
		});*/
	} else {
		if(CurrentPage) {
			CurrentPage.trigger('pagehide');
		}
		NextPage.trigger('pageshow').addClass(Me.activePageClass);
		if(ChangeHashProperty && NextPage.attr('data-'+Me.ns+'url')) {
			window.location.hash = (NextPage.attr('data-'+Me.ns+'url').substring(0, 1) != '#'? '#!': '')+NextPage.attr('data-'+Me.ns+'url');
		}
		$(Me).trigger('navigated');
	}
};




Anamo.Navigation.prototype.changePage = function(to, transition, reverse, changeHash) {
	var FromPage = null;
	var ToPage = null;
	var Data = '';
	var DataType = '';
	var NavType = 'local';
	if($.type(to) === 'array') { // [from, to] || form:[from, url, data: serialized form data, type: "get" or "post"}
		if(to.length == 1) {
			ToPage = to[0];
		} else if(to.length == 2) {
			FromPage = to[0];
			ToPage = to[1];
		} else if(to.length == 3) {
			NavType = 'ajax';
			ToPage = to[0];
			Data = to[1];
			DataType = to[2];
		} else if(to.length == 4) {
			NavType = 'ajax';
			FromPage = to[0];
			ToPage = to[1];
			Data = to[2];
			DataType = to[3];
		}
	} else if($.type(to) === 'string') { // 'about/us.html'
		NavType = 'ajax';
		Data = '';
		DataType = 'GET';
		ToPage = to;
	} else { // '#about'
		NavType = 'mesh';
		ToPage = to;
	}
	var TransitionProperty = (transition? transition: this.defaultTransition);
	var IsReverseAnimationProperty = (reverse? reverse: false);
	var ChangeHashProperty = (changeHash == false? false: true);//alert(FromPage+'----'+to+'---'+NavType+'---'+TransitionProperty+'---'+IsReverseAnimationProperty+'---'+ChangeHashProperty);
	
	// Try Navigate.
	// Abort page loading.
	if(this.xhr != null) {
		this.xhr.abort();
		this.xhr = null;
	}
	// Abort and Clear list of AyncReqs.
	for(var i in this.xhrList) {
		this.xhrList[i].abort();
	}
	this.xhrList.splice(0, this.xhrList.length);
	
	try {
		// Determine CurrentPage.
		var CurrentPage = this.currentPage();
		if(FromPage) {
			CurrentPage = $(FromPage);
		}
		if(CurrentPage) {
			if(!CurrentPage.hasClass(this.activePageClass)) {
				CurrentPage.addClass(this.activePageClass);
			}
		}
		
		// Everything is here.
		var Me = this;
		if(NavType == 'local' || NavType == 'mesh') {
			// Determine NextPage.
			var NextPage = null;
			if(NavType == 'local') {
				NextPage = $('*[data-'+Me.ns+'url="'+ToPage+'"]:first');
			} else {
				NextPage = $(ToPage);
			}
			if(NextPage.length == 0) {
				throw new Error('NextPage was not found');
			}
			
			Me._changePage(CurrentPage, NextPage, TransitionProperty, IsReverseAnimationProperty, ChangeHashProperty);
		} else if(NavType == 'ajax') {
			//$.mobile.loadPage (method)
			Me.xhr = $.ajax({
				type: DataType,
				url: ToPage,
				data: Data,
				dataType: 'html',
				global: false,
				beforeSend: function(XMLHttpRequest) {
					$(Me).trigger('fetching');
					Me.showPageLoadingMsg();
				},
				error: function(XMLHttpRequest, textStatus, errorThrown) {
					if(textStatus != 'abort') { // FIX for error while aborted.
						$(Me).trigger('navigationerror', ['Nav Error: Could not find resource to load', textStatus, errorThrown]);
					}
				},
				success: function(data, textStatus, XMLHttpRequest) {
					var divs = $(data).filter(function() {
						return ($(this).attr('data-'+Me.ns+'role') == 'page'); //return $(this).is('div');
					});
					var DataToAppend = '';
					if(divs.length > 0) {
						DataToAppend = $(divs[0]).outerHTML();
					} else {
						if($(data).find('*[data-'+Me.ns+'role=page]:first').length > 0) {
							DataToAppend = $(data).find('*[data-'+Me.ns+'role=page]:first').outerHTML();
						} else {
							DataToAppend = data;
						}
					}
					if(Me.pageContainer.children('*[data-'+Me.ns+'role=page]:last').length > 0) {
						Me.pageContainer.children('*[data-'+Me.ns+'role=page]:last').after(DataToAppend); //$(DataToAppend).insertAfter('*[data-'+Me.ns+'role=page]:last');
					} else {
						Me.pageContainer.append(DataToAppend);
					}
					// Determine NextPage.
					var NextPage = Me.pageContainer.children('*[data-'+Me.ns+'role=page]:last');
					if(NextPage.length == 0) {
						throw new Error('NextPage was not found 2');
					}
					Me.initializePage(NextPage);
					
					Me._changePage(CurrentPage, NextPage, TransitionProperty, IsReverseAnimationProperty, ChangeHashProperty);
				},
				complete: function(XMLHttpRequest, textStatus) {
					Me.xhr = null;
					Me.hidePageLoadingMsg();
				}
			});
		}
	} catch(ex) {
		if(ex) {
			$(this).trigger('navigationerror', [ex.message]);
		} else {
			$(this).trigger('navigationerror', ['Unknown error']);
		}
	}
};/* Copyright 2006-2010 Panagiotis Tsimpoglou. All rights reserved. */
/*
#Example.
Imports Jquery;
var MobileService = new Anamo.MobileService(true);

<html class="">
<body class="">
</body>
*/
Anamo.Mobile = new Object();




Anamo.MobileService = function(autoInitialize) {
	try {
		//this.deviceSupportsTouches = (Anamo.Core.EventExists('touchstart') && Anamo.Core.EventExists('touchend'));
		this.deviceSupportsTouches = ('createTouch' in document);
	} catch(ex) {}
	this.deviceStartEvent = (this.deviceSupportsTouches? 'touchstart': 'mousedown');
	this.deviceMoveEvent = (this.deviceSupportsTouches? 'touchmove': 'mousemove');
	this.deviceEndEvent = (this.deviceSupportsTouches? 'touchend': 'mouseup');
	try {
		this.deviceIsiOSDevice = ((navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/iPod/i)) || (navigator.userAgent.match(/iPad/i)));
	} catch(ex) {}
	try {
		this.deviceiOSDeviceIsInPortrait = window.navigator.standalone;
	} catch(ex) {}
	try {
		this.deviceiOSDeviceIsInFullScreenMode = (window.orientation % 180 == 0);
	} catch(ex) {}
	var Me = this;
	$(window).bind('orientationchange', function(e) {
		switch(window.orientation) {
			case 0:   // Portrait
				break;
			case 180: // Upside-down Portrait
				// Javascript to setup Portrait view
				break;
			case -90: // Landscape: turned 90 degrees counter-clockwise
				break;
			case 90:  // Landscape: turned 90 degrees clockwise
				// Javascript to steup Landscape view
				break;
		}
		try {
			Me.deviceiOSDeviceIsInPortrait = (window.orientation % 180 == 0);
		} catch(ex) {}
		$(Me).trigger('orientationchange');
	});
	if(autoInitialize) {
		$(document).bind('ready', function(e) {
			Me.initializeApp();
		});
	}
};
Anamo.MobileService.prototype.deviceSupportsTouches = false;
Anamo.MobileService.prototype.deviceIsiOSDevice = false;
Anamo.MobileService.prototype.deviceiOSDeviceIsInPortrait = false;
Anamo.MobileService.prototype.deviceiOSDeviceIsInFullScreenMode = false;
Anamo.MobileService.prototype.deviceStartEvent = false;
Anamo.MobileService.prototype.deviceMoveEvent = false;
Anamo.MobileService.prototype.deviceEndEvent = false;
Anamo.MobileService.prototype.activeBtnClass = 'active';

Anamo.MobileService.prototype.initializeApp = function(n) {
	var Me = this;
	if(n != null) {
		$(n).bind('navigated', function(e) {
			// Clear any bugs/misclicks.
			$('.anamo-ui-mobile-body *[href].'+Me.activeBtnClass).removeClass(Me.activeBtnClass);
			//n.currentPage().find('*[href].active').removeClass('active');
		});
	}
	
	$('.anamo-ui-mobile-body > .viewport > section > section').addClass('rootgrid');
	
	$('.anamo-ui-mobile-body > .viewport > section > nav a[data-rel=back],body > .viewport > section > nav a[data-rel=forward]').each(function(intIndex) {
		$(this).addClass('ui-button-has-arrow').addClass('ui-'+$(this).attr('data-rel')).html('<font>'+$(this).html()+'</font><div><span></span></div>');
	});
	$('.anamo-ui-mobile-body > .viewport > section > nav a[data-icon]').each(function(intIndex) {
		$(this).addClass('ui-hasicon').prepend('<i class="ui-icon-'+$(this).attr('data-icon')+'"></i>');
		if(typeof($(this).attr('data-iconpos')) !== 'undefined' && $(this).attr('data-iconpos') !== false) {
			if($(this).attr('data-iconpos') == 'notext') {
				$(this).addClass('ui-hasnotext');
			}
		}
	});
	
	$(this).trigger('appstartup');
};




Anamo.Mobile.Utilities = new Object();
/*Anamo.Mobile.Utilities.disableScrolling = function(a) {
	a.stopPropagation();
	window.addEventListener('touchmove', this.preventEventDefault, true);
	window.addEventListener('touchend', this.restoreScrollingBehavior, true);
	window.addEventListener('touchcancel', this.restoreScrollingBehavior, true);
};
Anamo.Mobile.Utilities.preventEventDefault = function(a) {
	a.preventDefault();
};
Anamo.Mobile.Utilities.restoreScrolling = function() {
	window.removeEventListener('touchmove', this.preventEventDefault, true);
	window.removeEventListener('touchend', this.restoreScrollingBehavior, true);
	window.removeEventListener('touchcancel', this.restoreScrollingBehavior, true);
};*/
Anamo.Mobile.Utilities.disablePageScrolling = function() {
	document.body.addEventListener('touchmove', function(e) {
		e.preventDefault(); // This prevents native scrolling from happening.
	}, false);
};




Anamo.Mobile.UI = new Object();




Anamo.Mobile.UI.TouchButton = function(element, handler) {
	this.element = element;
  this.handler = handler;

  element.addEventListener(MobileService.deviceStartEvent, this, false);
  element.addEventListener('click', this, false);
};
Anamo.Mobile.UI.TouchButton.prototype.handleEvent = function(event) {
  switch (event.type) {
    case 'touchstart': this.onTouchStart(event); break;
    case 'touchmove': this.onTouchMove(event); break;
    case 'touchend': this.onClick(event); break;
    case 'click': this.onClick(event); break;
  }
};
Anamo.Mobile.UI.TouchButton.prototype.onTouchStart = function(event) {
  event.stopPropagation();

  this.element.addEventListener(MobileService.deviceEndEvent, this, false);
  document.body.addEventListener(MobileService.deviceMoveEvent, this, false);

  this.startX = event.touches[0].clientX;
  this.startY = event.touches[0].clientY;
};
Anamo.Mobile.UI.TouchButton.prototype.onTouchMove = function(event) {
  if (Math.abs(event.touches[0].clientX - this.startX) > 10 || Math.abs(event.touches[0].clientY - this.startY) > 10) {
    this.reset();
  }
};
Anamo.Mobile.UI.TouchButton.prototype.onClick = function(event) {
  event.stopPropagation();
  this.reset();
  this.handler(event);

  if (event.type == MobileService.deviceEndEvent) {
    Anamo.Mobile.UI.ClickBuster.preventGhostClick(this.startX, this.startY);
  }
};
Anamo.Mobile.UI.TouchButton.prototype.reset = function() {
  this.element.removeEventListener(MobileService.deviceEndEvent, this, false);
  document.body.removeEventListener(MobileService.deviceMoveEvent, this, false);
};




Anamo.Mobile.UI.ClickBuster = new Object();
Anamo.Mobile.UI.ClickBuster.coordinates = [];
Anamo.Mobile.UI.ClickBuster.Initialize = function() {
	document.addEventListener('click', Anamo.Mobile.UI.ClickBuster.onClick, true);
};
Anamo.Mobile.UI.ClickBuster.preventGhostClick = function(x, y) {
  Anamo.Mobile.UI.ClickBuster.coordinates.push(x, y);
  window.setTimeout(Anamo.Mobile.UI.ClickBuster.pop, 2500);
};
Anamo.Mobile.UI.ClickBuster.pop = function() {
  Anamo.Mobile.UI.ClickBuster.coordinates.splice(0, 2);
};
Anamo.Mobile.UI.ClickBuster.onClick = function(event) {
  for(var i = 0; i < Anamo.Mobile.UI.ClickBuster.coordinates.length; i += 2) {
    var x = Anamo.Mobile.UI.ClickBuster.coordinates[i];
    var y = Anamo.Mobile.UI.ClickBuster.coordinates[i + 1];
    if (Math.abs(event.clientX - x) < 25 && Math.abs(event.clientY - y) < 25) {
      event.stopPropagation();
      event.preventDefault();
    }
  }
};




/*Anamo.Mobile.UI.Scroller = function(element) {
  this.element = element;
  this.startTouchY = 0;
  this.animateTo(0);

  element.addEventListener('touchstart', this, false);
  element.addEventListener('touchmove', this, false);
  element.addEventListener('touchend', this, false);
};
Anamo.Mobile.UI.Scroller.prototype.element = null;

Anamo.Mobile.UI.Scroller.prototype.handleEvent = function(e) {
  switch(e.type) {
    case 'touchstart':
      this.onTouchStart(e);
      break;
    case 'touchmove':
      this.onTouchMove(e);
      break;
    case 'touchend':
      this.onTouchEnd(e);
      break;
  }
};

Anamo.Mobile.UI.Scroller.prototype.onTouchStart = function(e) {
  // This will be shown in part 4.
  this.stopMomentum();

  this.startTouchY = e.touches[0].clientY;
  this.contentStartOffsetY = this.contentOffsetY;
};

Anamo.Mobile.UI.Scroller.prototype.onTouchMove = function(e) {
  if(this.isDragging()) {
    var currentY = e.touches[0].clientY;
    var deltaY = currentY - this.startTouchY;
    var newY = deltaY + this.contentStartOffsetY;
    this.animateTo(newY);
  }
};

Anamo.Mobile.UI.Scroller.prototype.onTouchEnd = function(e) {
  if(this.isDragging()) {
    if (this.shouldStartMomentum()) {
      // This will be shown in part 3.
      this.doMomentum();
    } else {
      this.snapToBounds();
    }
  }
};

Anamo.Mobile.UI.Scroller.prototype.animateTo = function(offsetY) {
  this.contentOffsetY = offsetY;

  // We use webkit-transforms with translate3d because these animations
  // will be hardware accelerated, and therefore significantly faster
  // than changing the top value.
  this.element.style.webkitTransform = 'translate3d(0, ' + offsetY + 'px, 0)';
};

// Implementation of this method is left as an exercise for the reader.
// You need to measure the current position of the scrollable content
// relative to the frame. If the content is outside of the boundaries
// then simply reposition it to be just within the appropriate boundary.
Anamo.Mobile.UI.Scroller.prototype.snapToBounds = function() {
  //...
};

// Implementation of this method is left as an exercise for the reader.
// You need to consider whether their touch has moved past a certain
// threshold that should be considered 'dragging'.
Anamo.Mobile.UI.Scroller.prototype.isDragging = function() {
  //...
};

// Implementation of this method is left as an exercise for the reader.
// You need to consider the end velocity of the drag was past the
// threshold required to initiate momentum.
Anamo.Mobile.UI.Scroller.prototype.shouldStartMomentum = function() {
  //...
};

Anamo.Mobile.UI.Scroller.prototype.doMomentum = function() {
  // Calculate the movement properties. Implement getEndVelocity using the
  // start and end position / time.
  var velocity = this.getEndVelocity();
  var acceleration = velocity < 0 ? 0.0005 : -0.0005;
  var displacement = - (velocity * velocity) / (2 * acceleration);
  var time = - velocity / acceleration;

  // Set up the transition and execute the transform. Once you implement this
  // you will need to figure out an appropriate time to clear the transition
  // so that it doesn't apply to subsequent scrolling.
  this.element.style.webkitTransition = '-webkit-transform ' + time +
      'ms cubic-bezier(0.33, 0.66, 0.66, 1)';

  var newY = this.contentOffsetY + displacement;
  this.contentOffsetY = newY;
  this.element.style.webkitTransform = 'translate3d(0, ' + newY + 'px, 0)';
};

Anamo.Mobile.UI.Scroller.prototype.stopMomentum = function() {
  if (this.isDecelerating()) {
    // Get the computed style object.
    var style = document.defaultView.getComputedStyle(this.element, null);
    // Computed the transform in a matrix object given the style.
    var transform = new WebKitCSSMatrix(style.webkitTransform);
    // Clear the active transition so it doesn't apply to our next transform.
    this.element.style.webkitTransition = '';
    // Set the element transform to where it is right now.
    this.animateTo(transform.m42);
  }
};*/


