var allDialogs = ['ContactUs','YourStory','YourCircle','ContactNutritionist','Ingredients','HowItWorks','TheDifference','Login','ForgotPassword'];
var allQueues = [];

var dialogsContainer = null;
var dialogBusy = null;
var dialogResults = null;
var blackBack = null;

var isIE = false;
var browserVersion = 0;


function $ (id, extend) {
	var el = document.getElementById(id);
	
	//add our setOpacity function
	
	if (extend) {
		el.setOpacity = function (percent, steps, delay) {
			if (arguments.length == 1) {
				if (percent == 100) {
					this.style.filter = "";
				}
				else {
					//this.style.filter = "alpha(opacity="+ percent +")";
					this.style.filter = "progid:DXImageTransform.Microsoft.BasicImage(opacity="+ (percent/100) +")";
				}
				this.style.opacity = percent/100;	
				this.opacity = percent;
			}
			else {
				var current = this.opacity;
				var op = 0;
				var queue = new Queue(this.id + "opacity", true);
				for (var i=0; i < steps; i++) {
					queue.push(
						function (el, opac) {
							el.setOpacity(opac);
						},
						[this, current + ((i+1) * ((percent - current)/steps))],
						delay
					);
				}
				queue.push(
					function (el) {
						el.setOpacity(percent);
					},
					this
				);
				return queue;
			}
		};	
	}
	
	return el;
}


function showDialog (dialogId) {
	
	var dialog = $('dialog' + dialogId);
	var dialogBody = $('dialog' + dialogId + "Body");
	var form = null;
	//var intro = $('intro');
	
	hideAllDialogs();
	
	resetDialogResults(dialogId);
	
	dialogBody.style.visibility = 'visible';
	dialogsContainer.style.top = getScrollTop() + "px";
	dialogsContainer.style.display = 'block';
	dialog.style.display = 'block';	
	
	blackBack.setOpacity(0);
	blackBack.setOpacity(70, 4, 1);
	
	//try to autofocus
	
	form = dialogBody.getElementsByTagName('form');
	
	if (form) {
		form = form[0];

		for (i=0; i < form.elements.length; i+=1) {
			if (form.elements[i].type == "text" || form.elements[i].type == "password" || form.elements[i].type == "textarea") {
				form.elements[i].focus();
				form.elements[i].select();
				break;
			}
		}
	}

	//hacked video code to make IE6 work right

	if (dialogId == 'HowItWorks') {
		var so = new SWFObject("/assets/swf/FLVPlayer_Progressive.swf", "How it works", "465", "280", "8", "#ffffff");
		so.addParam("movie","/assets/swf/FLVPlayer_Progressive.swf");
		so.addParam("salign","lt");
		so.addParam("quality","high");
		so.addParam("scale","noscale");
		so.addParam("wmode", "opaque");
		so.addVariable("MM_ComponentVersion","1");
		so.addVariable("skinName","/assets/swf/Corona_Skin_3");
		//so.addVariable("streamName","/flv/CN01_Full_Preview3");
		//so.addVariable("streamName","/flv/CN01_Full_11_25_08");
		so.addVariable("streamName","/assets/flv/CN01_Full_Preview4_NoTestimonial");
		so.addVariable("autoPlay","true");
		so.addVariable("autoRewind","false");
		so.write("flash");	
	}
	
	//if (intro) {
	//	intro.style.visibility = 'hidden';
	//}
}


function resetDialogResults (dialogId) {
	var dialog = $('dialog' + dialogId);	

	//dialogBusy.style.display = 'none';
	//dialogResults.style.display = 'none';	
	//dialogResults.innerHTML = '';	

	dialogBusy = pullFromDOM(dialogBusy);
	dialogResults = pullFromDOM(dialogResults);
}


function dialogSubmitOnEnter (dialogId, ev) {
	var keyCode = (ev.which || ev.keyCode);
	
	if (keyCode == 13) {
		dialogSubmit(dialogId);
	}
}


function dialogSubmit (dialogId) {
	var dialog = $('dialog' + dialogId);	
	
	var dialogBody = $('dialog' + dialogId + "Body");
	var form = eval('document.dialog' + dialogId + "Form");
	
	if (form) {
		dialogBody.style.visibility = 'hidden';
		stickIntoDOM(dialogBusy, dialog);	
		dialogBusy.style.display = 'block'
		form.submit();
	}
}


function showDialogResults (dialogId, text, success) {
	var html = "<p>" + text + "</p>";
	var dialog = $('dialog' + dialogId);	
	
	if (success) {
		//close button
		html+= "<a href='javascript:hideAllDialogs()'>close</a>";
	}
	else {
		//back
		html+= "<a href=\"javascript:showDialog('" + dialogId + "')\">back</a>";
	}

	stickIntoDOM(dialogResults, dialog);	
	dialogResults.innerHTML = html;
	dialogBusy.style.display = 'none';
	dialogResults.style.display = 'block';
}


function hideAllDialogs () {
	var dialog = null;
	//var intro = $('intro');
	var fadeQueue = null;
	
	for (i=0; i < allDialogs.length; i++) {
		dialog = $('dialog' + allDialogs[i]);
		if (dialog) {
			dialog.style.display = 'none';
		}
	}

	fadeQueue = blackBack.setOpacity(0, 4, 1);
	
	fadeQueue.push(
		function () {
			dialogsContainer.style.display = 'none';
		}
	);
	
	//hacked video code to make IE6 work right

	$('flash').innerHTML = 'This page requires the Adobe Player.  You can download the player from free from <a href="http://get.adobe.com/flashplayer/" target="_blank">Adobe.com</a>';
	
	//if (intro) {
	//	intro.style.visibility = 'visible';
	//}
}




function toggleDrawer (linkElement, drawerId) {
	var drawer = $('drawer' + drawerId);
	var hidden = (drawer.style.display != 'block');
	
	if (hidden) {
		linkElement.className = "drawerLinkOpen";
		drawer.style.display = 'block';
	}
	else {
		linkElement.className = "drawerLinkClosed";
		drawer.style.display = 'none';
	}
}


function pullFromDOM (el) {
	if (el && el.parentNode) {
		var result = el.parentNode.removeChild(el);
	}
	return el;
}


function stickIntoDOM (el, newParent) {
	if (el && newParent) {
		newParent.appendChild(el);
	}
}


function stopEvent (ev) {
	ev = (ev || window.event);
	if (ev) {
		if (ev.stopPropagation) {
			ev.stopPropagation();
		}
		ev.cancelBubble = true;
	}			
}


function getScrollTop () {
    if(typeof pageYOffset!= 'undefined'){
        //most browsers
        return pageYOffset;
    }
    else{
        var B= document.body; //IE 'quirks'
        var D= document.documentElement; //IE with doctype
        D= (D.clientHeight)? D: B;
        return D.scrollTop;
    }
}


/*
function onEvent (evName, action) {
	if (window.addEventListener) {
		window.addEventListener(evName, action, false);
	}
	else if (window.attachEvent) {
		window.attachEvent(evName, action);
	}
}
*/

function setShadowsHeight () {
	//hack to make the dropshadows compatible with IE6

	var height = document.body.scrollHeight;
	var leftShadow = null;
	var rightShadow = null;

	if (isIE && browserVersion < 7) {
		if (height) {
			leftShadow = $('leftMainShadow');
			rightShadow = $('rightMainShadow');
			
			leftShadow.style.height = height + "px";
			rightShadow.style.height = height + "px";
		}
	}
}


function userLogout () {
	document.logoutForm.submit();
}


function initializePage () {
	var appVer = navigator.appVersion;
	var agent = navigator.userAgent;
	
	dialogsContainer = $('dialogsContainer');
	dialogBusy = pullFromDOM($('dialogBusy'));
	dialogResults = pullFromDOM($('dialogResults'));
	blackBack = $('dialogContainerBlackBack', true);

	for (i=0; i < allDialogs.length; i++) {
		el = $('dialog' + allDialogs[i]);
		
		if (el) {
			el.onclick = function (ev) {
				stopEvent(ev);
			};
		}
	}

	if (appVer.indexOf("MSIE") > -1 && document.all) {
		var start = appVer.indexOf("MSIE ") + 5;
		isIE = true;
		browserVersion = parseFloat(appVer.substring(start, appVer.indexOf(";", start)));
	}
	
	window.onscroll = hideAllDialogs;
	window.onresize = setShadowsHeight;
	
	setShadowsHeight();
}


function TextCycler (elementId) {
	
	var thisthis = this;
	
	this.element = $(elementId, true);
	this.messages = [];
	this.currentMessage = 0;
	this.currentPart = 0;

	this.startDelay = 500;
	this.messageGap = 1000;
	this.partGap = 300;	
	this.fadeDelay = 25;
	this.fadeSteps = 10;
	this.slideSteps = 14;
	this.slideDistance = 26;
	
	this.init = function () {
		this.element.setOpacity(0);
		this.element.innerHTML = '';
	};
	
	this.addMessage = function () {
		var parts = arguments;
		var message = new TextCyclerMessage(this);
	
		for (var i=0; i < parts.length; i++) {
			message.addPart(parts[i]);
		}
		this.messages.push(message);
	};
	
	this.start = function () {
		setTimeout(function () { thisthis.next(); }, this.startDelay);
	};
	
	this.next = function () {
		var thisthis = this;
		var message = this.messages[this.currentMessage];
		var part = message.parts[this.currentPart];
		var queue = part.show();
		
		if (message && part) {
			this.currentPart++;
			
			if (this.currentPart >= message.parts.length) {
				//rotate to next message		
				this.currentPart = 0;
				this.currentMessage++;		
			
				if (this.currentMessage >= this.messages.length) {
					//rotate back to beginning
					this.currentMessage = 0;
				}
					
				queue.push(
					function () { 
						var queue2 = part.fadeOut(); 
						queue2.push(function () { thisthis.next(); }, [], thisthis.messageGap);
					},
					[],
					part.displayTime
				);
			}
			else {
				//go to next message part
	
				queue.push(
					function () { 
						var queue2 = part.fadeOut(); 
						queue2.push(function () { thisthis.next(); }, [], thisthis.partGap);
					},
					[],
					part.displayTime
				);
			}
		}
	};
	

	this.init();
}


function TextCyclerMessage (textCycler) {
	
	this.textCycler = textCycler;
	this.parts = [];
	
	this.addPart = function (messageInfo) {
		this.parts.push(new TextCyclerMessagePart(textCycler, messageInfo.text, messageInfo.displayTime));
	};
	
}


function TextCyclerMessagePart (textCycler, text, displayTime) {

	var thisthis = this;

	this.textCycler = textCycler;
	this.text = text;
	this.displayTime = displayTime;

	
	this.show = function () {
		var el = this.textCycler.element;
		var queue = null;
		var slideQueue = new Queue("slide" + el.id, true);
		var totalTime = (this.textCycler.fadeDelay * this.textCycler.fadeSteps);
		var slideDelay = totalTime / this.textCycler.slideSteps;
		
		var radius = this.textCycler.slideDistance/2;
		var circle = new Circle({ 'x':radius, 'y':0 }, radius);

		//totalTime+= totalTime * 0.1;
		
		el.innerHTML = this.text;
		el.style.paddingTop = this.textCycler.slideDistance + "px";
		queue = el.setOpacity(100, this.textCycler.fadeSteps, this.textCycler.fadeDelay);

		for (var i=180; i >= 0; i-=(180/this.textCycler.slideSteps)) {
			slideQueue.push(
				function (top, angle) {
					el.style.paddingTop = top + "px";
					//console.log('top ' + top);
				},
				[circle.getPosition(i-90).x, i],
				slideDelay
			);
			
			
		}		
		
		return queue;
	};
	
	
	this.fadeOut = function (queue) {
		var el = this.textCycler.element;
		var queue = el.setOpacity(0, this.textCycler.fadeSteps, this.textCycler.fadeDelay);
		return queue;
	};	
	
}


/* *** QUEUE FUNCS ************************************************************************** */

function Queue (name, autoAdvance) {
	this.actions = [];
	this.name = name;
	this.autoAdvance = autoAdvance;
	this.timer = null;

	var thisQueue = this;
	
	this.push = function (func, args, delay) {
		this.add(func, args, false, delay);
	};
	
	this.unshift = function (func, args, delay) {
		this.add(func, args, true, delay);
	};
	
	this.add = function (func, args, top, delay) {
		if (!args) {
			args = [];	
		}
		else if (!isArray(args)) {
			args = [args];
		}
		if (top) {
			this.actions.unshift(new QueueAction(func, args, delay));
		}
		else {
			this.actions.push(new QueueAction(func, args, delay));
		}
		//console.log("Adding " + func.toString());
		if (this.timer == null && this.autoAdvance) {
			this.next();
		}
	};
	
	this.next = function () {
		this.clearTimeout();
		if (this.actions.length > 0) {
			var action = thisQueue.actions.shift();
			if (action.delay) {
				this.timer = setTimeout(
					function () { 
						action.run();
						delete action;
						if (thisQueue.autoAdvance) {
							thisQueue.next();
						}
					}, 
					action.delay
				);
			}
			else {
				action.run();
			}
		}
	};
	
	this.addPause = function (ms) {
		this.push(function () {true;}, [], ms);
	};
	
	this.stop = function () {
		this.clearTimeout();
		allQueues[name] = null;
	};
	
	this.clearTimeout = function () {
		clearTimeout(this.timer);
		this.timer = null;
	};
	
	if (allQueues[name]) {
		allQueues[name].stop();
	}
	allQueues[name] = this;		
	
}


function QueueAction (func, args, delay) {
	this.func = func;
	this.args = args;
	this.delay = delay ? delay : 1;
	
	this.run = function () {
		this.func.apply(this, args);
		//console.log(this.func.toString());
	};
}


function Circle (midpoint, radius) {
	
	this.midpoint = midpoint;
	this.radius = radius;
	
	this.getPosition = function (angle) {
		var x = this.midpoint.x + Math.round(this.radius * Math.sin(toRadians(angle)));
		var y = this.midpoint.y + Math.round(this.radius * Math.cos(toRadians(angle)));
		return { 'x':x, 'y':y };
	};
}


function toRadians (d) {
	return d * (Math.PI/180);
}


function isArray (obj) {
	if (typeof obj == 'object' && obj.length != null && obj.pop) {
		return true;
	}
	return false;
}



