/**
 * Wapple Orientation Manager
 */
var wOM = function(){
	return {
		/**
		 * refresh source images with orientation param
		 */
		imageSourceRefresh : function(mode) {
			var allImages = document.body.getElementsByTagName("img");			
			var testLoop = allImages.length;
			var images = [];
			var readyImages = 0;
            var imgClass;
            var params;
            var http;
			
			while (testLoop--)
			{
			    if (allImages[testLoop].src.match('\/images\/mp')) {
			        images.push(allImages[testLoop]);
			    }
			}
			
			var i = images.length;
			var ik = i;
			var imageTotal = i;			
			
                        var src = null
                        
			while (i--) {
				imgClass = images[i].getAttribute('class');

                                if (images[i].src.match('orientation')){
                                    src = images[i].src.split('&orientation')[0];
                                } else {
                                    src = images[i].src;
                                }

				images[i].src = src+'&orientation='+mode;			
				
				images[i].onload = function(){
					readyImages++;
					if (readyImages == imageTotal)
					{
						while (ik--) {
							images[ik].width = images[ik].naturalWidth;
							images[ik].height = images[ik].naturalHeight;
						}
					}
				};
			}

			if(navigator.appName == "Microsoft Internet Explorer") {
				http = new ActiveXObject("Microsoft.XMLHTTP");
			} else {
				http = new XMLHttpRequest();
			}
			
			params = 'orientation='+mode+'&service_id='+serviceID;
			
			http.open("POST", window.location.protocol+'//'+window.location.host+'/orientation_handler', true);
			http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
			http.setRequestHeader("Content-length", params.length);
			http.setRequestHeader("connection", "close");
			http.send(params);
		},
		imageOrientationHandler : function() {
			switch(window.orientation){
					case 0:
						// we need to revert phone dimensions
						wOM.imageSourceRefresh('portrait');
				break;
					case -90:
					case 90:
						// we have gone landscape
						wOM.imageSourceRefresh('landscape');
				break; 
			}
		}
	}
}();

var supportsOrientationChange = "onorientationchange" in window;
var orientationEvent = supportsOrientationChange ? "orientationchange" : "resize";

window.addEventListener(orientationEvent, wOM.imageOrientationHandler, false);

