// (c) 2007-2008 GramCast, LLC -- All Rights Reserved

// globals
var	GCHuserInfoObj = new GCAuserInfo;			// info about the user
//var GCHsessionInfoObj = new GCSsessionInfo;		// info about the session
var	GCHmaterialsLoaded;
var	GCHpresentationLoaded;
var	GCHndaLoaded;
var GCHpresentName;								// name of Presentation shown (in right area)
var	GCHactiveSelection;							// handle the toggling of the presentation stage
var GCHactiveButton;							// "
var	GCHcssLoaded = new Array;
var	GCHbaseUserActionBoxHeight;					// base height of the userActionBox (with just the single NDA select item)

//add jQuery helper functions
jQuery.fn.hasClass = function(c) {
	return this.is('.'+c)
};


// This function returns the name of a given function. It does this by
// converting the function to a string, then using a regular expression
// to extract the function name from the resulting code.
function funcname(f) {
    var s = f.toString().match(/function (\w*)/)[1];
    if ((s == null) || (s.length == 0)) return "anonymous";
    return s;
}

// This function returns a string that contains a "stack trace."
function stacktrace() {
    var s = "";  // This is the string we'll return.
    // Loop through the stack of functions, using the caller property of
    // one arguments object to refer to the next arguments object on the
    // stack.
    for(var a = arguments.caller; a != null; a = a.caller) {
        // Add the name of the current function to the return value.
        s += funcname(a.callee) + "\n";

        // Because of a bug in Navigator 4.0, we need this line to break.
        // a.caller will equal a rather than null when we reach the end 
        // of the stack. The following line works around this.
        if (a.caller == a) break;
    }
    return s;
}

function GCHloadCSS(href, media) {
	if (media != undefined) str += ' media="' + media + '"';
	var checkStr = href+media;
	if (! GCHcssLoaded[checkStr]) {
		var str = '<link rel="stylesheet" type="text/css" href="' + href + '"';
		str += '"/>';
		var node = $(str);
		node.appendTo('#GChead');
		GCHcssLoaded[checkStr] = true;
	}
}

function GCHinitSelection(a,o) {
	//var a is the <a> tag object
	//var o is the stage object
	a.toggleClass('userOptionSelected').toggleClass('userOption');
	GCHactiveButton = a;
	$("#busyBox").hide();
	o.show();
	GCHactiveSelection = o;
}

function GCHnewSelectionLoaded(o) {
	$("#busyBox").hide();
	o.show();
}

function GCHchangeSelection(a,o,f) {
	//var a is the <a> tag object
	//var o is the stage object
	//var f is a flag that indicates an async content load is needed, and so invoker will take care of calling GCHnewSelectionLoaded()
	if (a.attr('id') != GCHactiveButton.attr('id')) {
		//clear the already selected button, and highlight the new selection -- unless attribute 'selectToggle' is 'no'
		if (a.attr('selectToggle') != 'no') a.toggleClass('userOptionSelected').toggleClass('userOption');
		if (GCHactiveButton.attr('selectToggle') != 'no') GCHactiveButton.toggleClass('userOptionSelected').toggleClass('userOption');
		GCHactiveButton = a;
		if (o.css('display') == 'none') {
			// 1. hide the active selection & show the busyBox
			GCHactiveSelection.hide();
			$("#busyBox").show();
			//2. load the content of the new selection (load is asynchronous, so we pass a callback which must invoke GCHnewSelectionLoaded()
			if (! (f == true)) GCHnewSelectionLoaded(o);	//funy test expression is so undefined evaluates to true
			GCHactiveSelection = o;
		}
	}
}

function GCHinit() {

	// init variables
	var hs = $('#userActionBox').css('height');
	var i = hs.indexOf('px');
	GCHbaseUserActionBoxHeight = parseInt(hs.substr(0,i));

	//load newz into news stage, and show
	$("#newz_stage").load("./html/frag_newz.html", function(){
		//load the css stylesheet
		GCHloadCSS('./css/newz.css');
		GCHinitSelection($('#selectNews'), $('#presentNews'));
	});
	
	/* set up all the user action button bindings */
	$('#selectNews').bind('click', function(){
		GCHchangeSelection($(this), $('#presentNews'));
		return false;
	});

	$('#selectNDA').bind('click', function(){
		var needToLoad = ! GCHndaLoaded;
		GCHchangeSelection($(this), $('#presentNDA'), needToLoad);
		if (needToLoad) {
			GCHloadCSS('./css/nda.css');
			$("#nda_stage").load("./html/frag_ndaViewer.html", function(){
				GCHnewSelectionLoaded($('#presentNDA'));
			});
			GCHndaLoaded = true;
		}
		return false;
	});
		
	$('#selectGramio').bind('click', function(){
		GCHchangeSelection($(this), $('#presentGramio'));
		return false;
	});

	$('#selectGramioDload').bind('click', function(){
		GCHchangeSelection($(this), $('#presentGramioDload'));
		return false;
	});

	$('#selectStreams').bind('click', function(){
		GCHchangeSelection($(this), $('#presentStreams'));
		return false;
	});

	$('#selectGramcastChannels').bind('click', function(){
		GCHchangeSelection($(this), $('#presentGramcastChannels'));
		return false;
	});

	$('#selectGramcastImg').bind('click', function(){
		GCHchangeSelection($('#selectGramcast'), $('#presentGramcasts'));
		return false;
	});

	// mouse-overs
	$('#selectGramcastChannels').bind('mouseover', function(){
		$('#gramcastAnim').hide();
		$('#gramcastAnimREV').show();
	}).bind('mouseout', function(){
		$('#gramcastAnimREV').hide();
		$('#gramcastAnim').show();
	});


	function GCHloadPresentationSource (selection) {
		//determine which presentation to load
		GCHpresentName = selection.attr('presentName');
		var needToLoad = (GCHpresentationLoaded != GCHpresentName);
		GCHchangeSelection(selection, $('#presentPresentation'), needToLoad);
		if (needToLoad) {
			GCPloadPresentation(GCHpresentName);
			GCHpresentationLoaded = GCHpresentName;
			GCHnewSelectionLoaded($('#presentPresentation'));
		}
	}
		
	$('.selectPresentation').bind('click', function(cb) {
		var selection = $(this);
		if (! GCHpresentationLoaded) {
			//load the css stylesheets
//			GCHloadCSS('./css/pagenavi.css');
//			GCHloadCSS('./css/presentation.css');
// loading these in with links on home html page
			//load the Javascript
			$.getScript('./js/presentation.js', function() {
				GCHloadPresentationSource(selection);
			});
		} else {
			GCHloadPresentationSource(selection);
		}
		return false;
	});

	$('.selectDisplayFrag').bind('click', function() {
		var selection = $(this);
		var name = selection.attr('name');
		var imageSpec = selection.attr('image');
		var loadCSS = selection.attr('loadCSS');
		var	fileName;
		if (loadCSS) {
			fileName = './css/' + name;
			GCHloadCSS(fileName);
		}
		if (imageSpec) {
			$('#presentFragmentImage').attr('src',imageSpec).show();
		} else {
			$('#presentFragmentImage').hide();
		}
		
		fileName = './html/frag' + name;
		$("#fragmentsStage").empty().load(fileName, function(){
			GCHnewSelectionLoaded($('#presentFragments'));
		});
		GCHchangeSelection($(this), $('#presentFragments'));
		return false;
	});


	$('#selectLogoutButton').bind('click', function() {
		GCHchangeSelection($(this), $('#presentNews'));
		GCLogout();
		$("#loggedInContainer").fadeOut('slow', function() {
			$("#loginButton").fadeIn('slow');
			$("#loggedInMessage").text('');		//be sure to clear as user name is only set if the text is empty
		});
		GCHsetUserDisplays();
		return false;
	});


	//mouse-overs

	$("#gramioContainer").bind("mouseover", function(e) {
		$("#GramioBoxBackground").show();
		}).bind("mouseout", function(e) {
			$("#GramioBoxBackground").hide();
		});
	
	
	// check if the user already has a session (from cookie info)
	// page-related stuff
//	GCHsessionInfoObj.loadFromCookie();
	// user-realted stuff:
	GCHuserInfoObj.loadFromCookie();
	if (GCHuserInfoObj.hasLoggedIn()) {
		GCHsetUserNameLogin(true);		//flag informs that this is init set-up -- before user could have logged in
		GCHsetUserDisplays();
	}	
}

function GCHsetUserNameLogin(flag) {
	if (GCHuserInfoObj.hasLoggedIn()) {
		var userBackAgain = flag || (GCHuserInfoObj.loginCount() > 1);
		if ($("#loggedInMessage").text() == '') {
			$("#loggedInMessage").text('Welcome' + ((userBackAgain) ? ' back' : '') + ', ' + GCHuserInfoObj.dispName() + ((userBackAgain) ? '.' : '!'));
		}
		if (! $("#loggedInContainer").is(":visible")) {
			$("#loginButton").fadeOut(function(){
				$("#loggedInContainer").fadeIn();
			});
		}
	} else {
		if ($("#loggedInMessage").text() != '') {
			$("#loggedInMessage").text('');
		}
		if ($("#loggedInContainer").is(":visible")) {
			$("#loggedInContainer").fadeOut(function() {
				$("#loginButton").fadeIn();
			});
		}
	}
}	

// FOR FUTURE REFERENCE/RE_USE
// currently, we don't show this publically
//var l = window.location.href;
//var i = l.indexOf('imagine');
//if (i > 0) {
//			$('#selectPresentationImagine').show(); n+=.5;
//}


function GCHsetUserActionBox () {
	var o = $('#userActionBox');
	var n = 0;							//each item gets a score for how much of a line it takes
	var r = 0;
	var h = GCHbaseUserActionBoxHeight;
	if (GCHuserInfoObj.hasLoggedIn()) {
		if (GCHuserInfoObj.hasAgreedNDA()) {
			//determine which resources can be viewed
			$('#titleInfo').show(); r++;
//			if (GCHuserInfoObj.canAccessResource('pAbout')) {$('#selectPresentationAbout').show(); n+=.5}
			$('#selectGlance').show(); n+=.5;
//			$('#selectOrigins').show(); n+=.5;
			$('#selectGramCastIs').show(); n+=.5;
			$('#selectScreencasts').show(); n+=.5;
			$('#selectPresentationBizPlan').show(); n+=.5;
			$('#selectPresentationExecPlan').show(); n+=.5;
//			$('#selectPresentationImagine').show(); n+=.5;
//			$('#selectPresentationOvw').show(); n+=.5;
//			$('#selectPresentationPoc').show(); n+=.5;
			r += Math.ceil(n)
			n = 0;
			$('#titleResources').show(); r++;
			$('#selectMaterials').show(); n+=.25;
			
			n+=.25;		//for the NDA select tab -- which is shown by default
			r += Math.ceil(n);
			h = Math.ceil(h + ((r-1) * h * .7));
			o.css('height', h);
		}
		// always show box because it has the NDA tab
		if (o.css('display') == 'none') {
			o.slideDown('slow');
		}
	} else {
		// make sure hidden (i.e., a user may have logged out)
		if (o.css('display') != 'none') {
			o.slideUp('slow');
			o.css('height', GCHbaseUserActionBoxHeight);	// set back to base height
		}
	}
}

function GCHsetUserNeedsNDABox () {
	var o = $('#needNDABox');
	if (! GCHuserInfoObj.hasLoggedIn() || GCHuserInfoObj.hasAgreedNDA()) {
		// hidden
		if (o.css('display') != 'none') {
			o.slideUp('slow');
		}
	} else {
		// shown
		if (o.css('display') != 'block') {
			o.slideDown('slow');
		}
	}
}


function GCHsetUserDisplays (){
	GCHsetUserActionBox();
	GCHsetUserNeedsNDABox();
}


function GCHbindLoginButton () {
	$("#loginButton").bind("click", function(e) {
		if ($("#loginFormBox").is(":visible")) {
			$("#loginFormContainer").fadeOut(function(){	
				$("#loginFormBox").slideUp('slow', function(){
					if (GCHuserInfoObj.hasLoggedIn()) {
						GCHsetUserNameLogin();
						GCHsetUserDisplays();
						if (! GCHuserInfoObj.hasAgreedNDA()) {
							$("#selectNDA").click();
						}
					}
				});
			});
			GCclearInputLoginFields();
		} else {
			GCclearInputLoginFields();
			$("#loginFormBox").slideDown("slow", function(){
				$("#loginFormContainer").fadeIn();
				GCLnameInput.focus();
			});
		}
		return false;
	});
}

function GCHuserHasDisagreedNDA () {
	GCHchangeSelection($('#selectNews'), $('#presentNews'));
}

function GCHuserHasAgreedNDA (val) {
	//val is the time-stamp associated with the date that was displayed in the NDA text
	GCHchangeSelection($('#selectNews'), $('#presentNews'));
	GCLsetUserHasAgreedNDA(val);
	GCHsetUserDisplays();
}




