
var m = MochiKit;
var hyp = {};

hyp.ui = {
		
	//public methods
	centerElement : function(elem) {
		elem = $(elem);
		removeElement(elem);
		document.body.appendChild(elem);
		elem.style.position = 'absolute'
		var port = getViewportDimensions();	
		var elemSize = elementDimensions(elem);
		var center = new Coordinates(
			Math.round(port.w / 2 - elemSize.w / 2),
			Math.round(port.h / 2 - elemSize.h / 2)
		);
		
		setElementPosition(elem, center);
	},

    registerSIFR : function(selector, options) {
        if(typeof sIFR == "function"){
            if(!options) { options = {}; }
            if (!options.sFlashSrc) { options.sFlashSrc = 'dax-mediumitalic.swf' }
            if(!options.sColor) { options.sColor = '#57585c' }
            if(!options.wMode) { options.wMode = 'transparent' }
            options.sFlashSrc = '/assets/js/sifr/' + options.sFlashSrc;
    		sIFR.replaceElement(selector, named(options));    				
    	};
    },

	printFlash : function(a,b,c,d,e,f,g,h) {
        //Replace with a better flash print routine
        var self = hyp.ui;
		self._checkFlash();
		if (hyp.environment.flash >= d) {
			var oeTags = '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="'+b+'" height="'+c+'" codebase="https://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab">'
			+ '<param name="movie" value="'+e+'.swf" /><param name="FlashVars" value="'+f+'" /><param name="loop" value="true" /><param name="wmode" value="opaque"><param name="menu" value="false" /><param name="quality" value="high" /><param name="scale" value="exactfit" />'
			+ '<embed src="'+e+'.swf" flashvars="'+f+'" name="movie" loop="true" wmode="opaque" menu="false" quality="high" swLiveConnect="true" width="'+b+'" height="'+c+'" play="true" loop="false" quality="high" allowScriptAccess="sameDomain" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer"></embed></object>';
			document.write(oeTags);
		} else {
			if (a=="promoTop") {
			    var htmlFallback = '<div><img src="/assets/images/' + g + '" width="893" height="236" alt="" usemap="#promoTop" /><map name="promoTop"><area coords="767,131,885,90" alt="" href="/public/how.aspx?page=programs#lean" /><area coords="885,132,725,176" alt="" href="/public/how.aspx?page=programs#fitness" /><area coords="885,177,682,222" alt="" href="/public/how.aspx?page=programs#performance" /></map></div>';
			} else {
				var htmlFallback = '<div class="'+a+'"><a href="'+h+'" target="_blank"><img src="/assets/images/'+g+'" width="'+b+'" height="'+c+'" alt=""/></a></div>';
			}
			document.write(htmlFallback);
		}
	},


    //private methods
	_initiate : function() {	
		var self = hyp.ui;	
        hyp.environment._initiate();
        self.registerSIFR(".sifr");
        self.registerSIFR(".article h1", { sFlashSrc: "dax-regular.swf", sColor: "#f06721" });  
        self.registerSIFR("h1.title");         	
        self.popUpManager = new atoPopUpManager();
        self.loading._initiate(); 
	},


	//Replace with a better flash checking routine.
	_checkFlash : function() {
		var self = hyp.ui;		
		var fx = null; //getCookie("flash_exist"); // Bypass corrupt flash installs with cookie
		if (fx) {
			hyp.environment.flash = 10;
		} else {
			if (document.all) {
				document.write('<SCR' + 'IPT LANGUAGE=VBScript\> \n');
				document.write('on error resume next \n');
				document.write('flash6 = false \n');
				document.write('flash7 = false \n');
				document.write('flash8 = false \n');
				document.write('flash9 = false \n');
				document.write('flash6 = (IsObject(CreateObject("ShockwaveFlash.ShockwaveFlash.6"))) \n');
				document.write('flash7 = (IsObject(CreateObject("ShockwaveFlash.ShockwaveFlash.7"))) \n');
				document.write('flash8 = (IsObject(CreateObject("ShockwaveFlash.ShockwaveFlash.8"))) \n');
				document.write('flash9 = (IsObject(CreateObject("ShockwaveFlash.ShockwaveFlash.9"))) \n');
				document.write('flash10 = (IsObject(CreateObject("ShockwaveFlash.ShockwaveFlash.10"))) \n');				
				document.write('</SCR' + 'IPT\> \n');
				if (flash6) hyp.environment.flash = 6;
				if (flash7) hyp.environment.flash = 7;
				if (flash8) hyp.environment.flash = 8;
				if (flash9) hyp.environment.flash = 9;
				if (flash10) hyp.environment.flash = 10;								
			} else {
				if (navigator.plugins["Shockwave Flash"]) {
					var flashDescription = navigator.plugins["Shockwave Flash"].description;
					var flashver = parseInt(flashDescription.charAt(flashDescription.indexOf(".") - 1));
					if (flashver == 1) flashver = 10;
					hyp.environment.flash = flashver;
				}
			}
		}		
	}
};
m.DOM.addLoadEvent(hyp.ui._initiate);

hyp.environment = {
     flash : 0, 
     query : null,
     browser : null,
     controllerURL: location.protocol + '//' + location.host + '/fitness/async/ctr_program.aspx?',
     dataCache: {},
     multiThumbPath: location.protocol + '//' + location.host + '/videos/multishot/',
     thumbPath: location.protocol + '//' + location.host + '/videos/thumbs/',
  
     
     _initiate : function() {
         var self = hyp.environment;
         self.query = m.Base.parseQueryString(location.search.replace('?',''));
         self.browser = BrowserDetect
         self.browser.init();     
     }
};

hyp.ui.warningPanel = {
	_initiate: function(options) {
		self.element = null;
	},

	hide: function(element, time) {
		self.element = $(element);
		if(!time) { time = 1000; };
		var temp = SPAN(null, ' ');
		var timer = setTimeout(function() { 
			fade(self.element); 
			self.element.parentNode.insertBefore(temp, self.element);
		}, time);
	}
}


hyp.ui.loading = {

    isOpen: false,
    panel: null,    

    //public methods
    show : function(text) {
        var self = hyp.ui.loading;
        self._setText(text);
        appear(self.panel, {to: .7});
        self.isOpen = true;
        signal(self, 'onShow');
    },

    hide : function() {
        var self = hyp.ui.loading;
        fade(self.panel, {to: 0});
        self.isOpen = false;
        signal(self, 'onHide');
    },
	toggle : function() {
		var self = hyp.ui.loading;		
		if(self.isOpen) { self.hide(); } else { self.show(); }		
		signal(self, 'onToggle');
	},
    
    //private methods
	_initiate : function() {	
		var self = hyp.ui.loading;			
		self._createWindow();        	
	},

    _createWindow : function() {
        var self = hyp.ui.loading
        self.panel = DIV({'id': 'loading-window', 'style': 'display: none;'}, DIV({'class': 'loading-content'}, 'Loading...'));
        document.body.appendChild(self.panel);
        self.panel.style.zIndex = '30000';
        roundElement(self.panel, {isTransparent: true});
        hyp.ui.centerElement(self.panel);
    },
    _setText : function(text) {
        var self = hyp.ui.loading
        if(!text) { text = 'Loading...' }
        //replaceChildNodes(self.panel, text);
    }
}


/*
 *
 * Printing Functionality
 *
 */
hyp.ui.print = {};
hyp.ui.print._Class = function(){
	this.box = DIV({id:'print-data', 'class': 'print'}, null);
//    var container = getElementsByTagAndClassName('div', 'container')[0];
	var container = document.getElementById("container");
    var foot = getElementsByTagAndClassName('div', 'footer')[0];
    //container.insertBefore(this.box, foot);	
}
hyp.ui.print.printThis = function(data){
	hyp.ui.print.myClass.box.innerHTML  = data;
    addElementClass(document.body, 'print-view');
    setTimeout(hyp.ui.print.cleanUp, 1000);
	window.print();
}
hyp.ui.print.cleanUp = function() {
    removeElementClass(document.body, 'print-view');    
    hyp.ui.print.myClass.box.innerHTML = '';
}
m.DOM.addLoadEvent(function(){ hyp.ui.print.myClass = new hyp.ui.print._Class(); });



/*
 *
 * PopUp and PopUp Manager
 *
 */
 
var atoPopUp = function(options) {
	//public
	this.element = null;
	this.hideClass = 'hide'
	this.showTriggers = [];
	this.hideTriggers = [];	
	this.toggleTriggers = [];
	this.autoBodyClickHide = true;
	this.isModal = false;
	this.isExlusive = false;
	if(options && typeof(options) == 'object') { update(this, options); }
		
	//private
	this._bodySignalId = null;
	this._isShown = false;
	this._isOver = false;
	
	//events
	this.onShow = null;
	this.onHide = null;
		
	this._initiate();
}

update(atoPopUp.prototype, {	 

	//public functions 
	 show : function() {
	 	var self = this;
		appear(self.element, {duration: .2});		
		self._isShown = true;
		if(self.autoBodyClickHide) { 
			self._bodySignalId = connect(document.body, 'onclick', function() { if(self._isShown && !self._isOver) { self.hide();  }});
			connect(self.element, 'onmouseover', function() { self._isOver = true; });
			connect(self.element, 'onmouseout', function() { self._isOver = false; });
		}
		signal(self, 'onShow', self);
	},

	 hide : function() {
	 	var self = this;		
        fade(self.element, {duration: .2});
		self._isShown = false;
		self._isOver = false;
		disconnect(self._bodySignalId);
		signal(self, 'onHide', self);
	},

	toggle : function() {	
		if(this._isShown) { this.hide(); } else { this.show(); }		
	},
	

	positionRelativeTo : function(element, offSet) {
		var self = this;
		element = $(element);
		removeElement(self.element);
		document.body.appendChild(self.element);
		var p = getElementPosition(element);
		p.x = p.x + offSet.x;
		p.y = p.y + offSet.y;
		setElementPosition(self.element, p);		
	},

	//pseudo constructor
	_initiate : function() {
        var self = this;
		self.element = $(self.element);
		
        hideElement(self.element);
        removeElementClass(self.element, 'hide');
		forEach(this.showTriggers, function(e) {
			connect(e, 'onclick', function(j) { j.stop(); self.show(); });
		});
		forEach(this.hideTriggers, function(e) {
			connect(e, 'onclick', function(j) { j.stop(); self.hide(); });
		});
		forEach(this.toggleTriggers, function(e) {
			connect(e, 'onclick', function(j) { j.stop(); self.toggle(); });
		});
	}

	//private methods	
	
});

var atoPopUpManager = function(options) {
	//public
	this.overlayColor = 'black';
	this.popUps = [];
	this._overlayOn = false;
	if(options && typeof(options) == 'object') { update(this, options); }	
}

update(atoPopUpManager.prototype, {
	//public functions 
	showAll : function() {
		forEach(this.popUps, function(e) { e.show(); });
	},

	hideAll : function() {
		forEach(this.popUps, function(e) { if(e._isShown) { e.hide(); } });
	},

	hideAllOthers : function(popup) {
		forEach(this.popUps, function(e) { if(e != popup) { e.hide(); } });
	},

	toggleAll : function() {	
		forEach(this.popUps, function(e) { e.toggle(); });		
	},

	add : function (e) {
		if(isArrayLike(e)) { this.popUps = concat(this.popUps, e); } else { this.popUps.push(e); }		
	},

	create : function(options) {
		var self = this;
		var n = new atoPopUp(options);
		connect(n, 'onShow', self, '_onPopUpShow');
		connect(n, 'onHide', self, '_onPopUpHide');		
		this.add(n);
		return n;
	},

	_onPopUpShow : function(popup) {
		var self = this;		
		if(popup.isExclusive) {			
			self.hideAllOthers(popup);
		}
		if(popup.isModal) { self._toggleOverlay(); }
		self._setZIndex(popup);
	},

	_onPopUpHide : function(popup) {
		var self = this;		
		if(popup.isModal) { self._toggleOverlay(); }		
	},

	_setZIndex : function(e) {
		var self = this;		
		forEach(self.popUps, function(j) {
			j.element.style.zIndex = '1000';
		});
		e.element.style.zIndex = '20000';		
	},

	_toggleOverlay : function(opacity) {
		var self = this;		

		//hide flash for FF PC and IE
		if(hyp.environment.browser.browser == "Firefox" && (hyp.environment.browser.OS == "Windows")) {
			if(self._overlayOn) {
				embeds = document.getElementsByTagName('embed');
				for(i = 0; i < embeds.length; i++) {
				    embeds[i].style.display = 'block';
				}
			} else {				
				embeds = document.getElementsByTagName('embed');
				for(i = 0; i < embeds.length; i++) {
					embeds[i].style.display = 'none';
				}
			}			
		}
		

		if(hyp.environment.browser.browser != "Explorer") { //Just guess why this is needed....because IE is teh sux0r
			if(!self.overlay) {
				self.overlay = DIV({'id': 'ato-overlay'}, null);
				self.overlay.style.position = 'absolute';
				document.body.appendChild(self.overlay);
				setElementDimensions(self.overlay, {w: self._getPageSize()[0], h: self._getPageSize()[1]});
				setElementPosition(self.overlay, {x:0,y:0});
				self.overlay.style.zIndex = '100';
				self.overlay.style.padding = '0';
				hideElement(self.overlay);
				self.overlay.style.backgroundColor = self.overlayColor;	
				setOpacity(self.overlay, .5);					
			}		
			if(self._overlayOn) { 
				hideElement(self.overlay);
				self._overlayOn = false;
			} else {			
				log('ide');
				showElement(self.overlay);
				self._overlayOn = true;
			}
		}

		

		

	},

	_getPageSize : function() {
	
		var xScroll, yScroll;
		
		if (window.innerHeight && window.scrollMaxY) {	
			xScroll = document.body.scrollWidth;
			yScroll = window.innerHeight + window.scrollMaxY;
		} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
			xScroll = document.body.scrollWidth;
			yScroll = document.body.scrollHeight;
		} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
			xScroll = document.body.offsetWidth;
			yScroll = document.body.offsetHeight;
		}
		
		var windowWidth, windowHeight;
		if (self.innerHeight) {	// all except Explorer
			windowWidth = self.innerWidth;
			windowHeight = self.innerHeight;
		} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
			windowWidth = document.documentElement.clientWidth;
			windowHeight = document.documentElement.clientHeight;
		} else if (document.body) { // other Explorers
			windowWidth = document.body.clientWidth;
			windowHeight = document.body.clientHeight;
		}	
		
		// for small pages with total height less then height of the viewport
		if(yScroll < windowHeight){
			pageHeight = windowHeight;
		} else { 
			pageHeight = yScroll;
		}
	
		// for small pages with total width less then width of the viewport
		if(xScroll < windowWidth){	
			pageWidth = windowWidth;
		} else {
			pageWidth = xScroll;
		}
	
	
		arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight) 
		return arrayPageSize;
	}

});


var BrowserDetect = {
	init: function () {
		this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
		this.version = this.searchVersion(navigator.userAgent)
			|| this.searchVersion(navigator.appVersion)
			|| "an unknown version";
		this.OS = this.searchString(this.dataOS) || "an unknown OS";
	},
	searchString: function (data) {
		for (var i=0;i<data.length;i++)	{
			var dataString = data[i].string;
			var dataProp = data[i].prop;
			this.versionSearchString = data[i].versionSearch || data[i].identity;
			if (dataString) {
				if (dataString.indexOf(data[i].subString) != -1)
					return data[i].identity;
			}
			else if (dataProp)
				return data[i].identity;
		}
	},
	searchVersion: function (dataString) {
		var index = dataString.indexOf(this.versionSearchString);
		if (index == -1) return;
		return parseFloat(dataString.substring(index+this.versionSearchString.length+1));
	},
	dataBrowser: [
		{
			string: navigator.vendor,
			subString: "Apple",
			identity: "Safari"
		},
		{
			prop: window.opera,
			identity: "Opera"
		},
		{
			string: navigator.vendor,
			subString: "iCab",
			identity: "iCab"
		},
		{
			string: navigator.vendor,
			subString: "KDE",
			identity: "Konqueror"
		},
		{
			string: navigator.userAgent,
			subString: "Firefox",
			identity: "Firefox"
		},
		{	// for newer Netscapes (6+)
			string: navigator.userAgent,
			subString: "Netscape",
			identity: "Netscape"
		},
		{
			string: navigator.userAgent,
			subString: "MSIE",
			identity: "Explorer",
			versionSearch: "MSIE"
		},
		{
			string: navigator.userAgent,
			subString: "Gecko",
			identity: "Mozilla",
			versionSearch: "rv"
		},
		{ 	// for older Netscapes (4-)
			string: navigator.userAgent,
			subString: "Mozilla",
			identity: "Netscape",
			versionSearch: "Mozilla"
		}
	],
	dataOS : [
		{
			string: navigator.platform,
			subString: "Win",
			identity: "Windows"
		},
		{
			string: navigator.platform,
			subString: "Mac",
			identity: "Mac"
		},
		{
			string: navigator.platform,
			subString: "Linux",
			identity: "Linux"
		}
	]

};

function checkAllNone(namePart, state) 
{
   for (var i=0;i < document.forms.length;i++) 
   {
	   for (var j=0;j < document.forms[i].length;j++) 
	   {
		  fe = document.forms[i].elements[j];
		  if ((fe.type == 'checkbox') && (fe.name.indexOf(namePart) != -1)) { 
			if (state == 'select') {
				fe.checked = true;
			} else if (state == 'unselect') {
				fe.checked = false;
			} else {
				fe.checked = (fe.checked) ? true : false;
			}
		  }
	   }
	}
}
