//types of calls
var MAIN_RESULTS_CALL = 0;
var CHANNEL_RESULTS_CALL = 1;
var CATEGORY_RESULTS_CALL = 2;
var CATEGORY_SCHEDULE_CALL = 3;
var USER_LOGIN_CALL = 4;
var ADD_USER_EVENT_CALL = 5;
var REMOVE_USER_EVENT_CALL = 6;
var INCREMEMNT_USER_EVENT_CALL = 7;
var GET_USER_EVENTS_CALL = 8;

//types of prefixes for calls
var CATEGORY_PREFIX = "category:";
var CHANNEL_PREFIX = "channel:";
var TAG_PREFIX = "tag:";

function ntGetElementById(element)
{
	if (document.getElementById) element = document.getElementById(element);
	else if (document.all) element = document.all[element];
	else element = null;
	return element;
}

function gup( name )
{
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( window.location.href );
  if( results == null )
    return "";
  else
    return unescape(results[1]);
} 

function inviteToEvent(eventID) {
	//alert(eventID);
	cacheName = getCurrentCache();
	window.location = '/servlet/EmailServlet?cacheName='+cacheName+'&eventID='+eventID;
}

function getCurrentCache() {
	return getCookie("setCategory");
}
function updateCrumb(value) {
 	ntGetElementById("cookiecrumb").innerHTML = value;
}
function doSearchwithTermAndSetCookie(term,cookie)
	{
	//alert(term);
	setCookie('setCategory', cookie, 30, '/', '', '');
	doSearchwithTerm(term)
	}


function doSearchwithTerm(term)
	{
		//alert(term);
		ntGetElementById("searchterm").value = term;
		ntGetElementById("cacheName").value = getCookie('setCategory');
		
		doSearch();
	}

function doSearch()
	{
	document.myform.submit();
	}

function makeRequest(url,requestIndex) {
	//ignore the cache for all ajax requests
	d = new Date();
	localTime = d.getTime();
	if (url.indexOf("?") != -1) {
		url = url + "&noCache="+localTime;
	}
	else {
		url = url + "?noCache="+localTime;
	}
	//alert(url);
	var httpRequest;
	//ntGetElementById("loadingImage").style.visibility ='visible';
	if (window.XMLHttpRequest) { // Mozilla, Safari, ...
		httpRequest = new XMLHttpRequest();			
	   if (httpRequest.overrideMimeType) {
		   httpRequest.overrideMimeType('text/xml');
			// See note below about this line
		}
	} 
	else if (window.ActiveXObject) { // IE
		try {
			httpRequest = new ActiveXObject("Msxml2.XMLHTTP");
			} 
			catch (e) {
					   try {
							httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
						   } 
						 catch (e) {}
					  }
								   }

	if (!httpRequest) {
		alert('Giving up :( Cannot create an XMLHTTP instance');
		return false;
	}
	//calling for the main results

	if (requestIndex == MAIN_RESULTS_CALL)
	{		
		httpRequest.onreadystatechange = function() { buildResultSet(httpRequest); };		
	}	
	//calling for a specific channel
	else if (requestIndex == CHANNEL_RESULTS_CALL)
	{
		httpRequest.onreadystatechange = function() { buildChannelSet(httpRequest); };		
	}	
	//calling for categories
	else if (requestIndex == CATEGORY_SCHEDULE_CALL)
	{
		httpRequest.onreadystatechange = function() { buildCategorySchedule(httpRequest); };	
	}
	//calling for user events
	else if (requestIndex == GET_USER_EVENTS_CALL)
	{
		httpRequest.onreadystatechange = function() { buildMyEvents(httpRequest); };	
	}
	//calling for user login
	else if (requestIndex == USER_LOGIN_CALL)
	{
		httpRequest.onreadystatechange = function() { buildUserID(httpRequest); };	
	}
	//calling for incrememnting rating
	else if (requestIndex == INCREMEMNT_USER_EVENT_CALL)
	{
		httpRequest.onreadystatechange = function() { incrementRating(httpRequest); };	
	}
	//calling to add an event to my queue
	else if (requestIndex == ADD_USER_EVENT_CALL)
	{
		httpRequest.onreadystatechange = function() { addUserEvent(httpRequest); };	
	}
	//calling to remove an event to my queue
	else if (requestIndex == REMOVE_USER_EVENT_CALL)
	{
		httpRequest.onreadystatechange = function() { removeUserEvent(httpRequest); };	
	}
	
	httpRequest.open('GET', url, true);
	httpRequest.send('');	 
}

function getXMLElement(currentElement, elementID) {
	subElement = currentElement.getElementsByTagName(elementID)[0];
		if (subElement != null) {			
			if (subElement.childNodes[0] != null) {
				return subElement.childNodes[0].nodeValue;											
			}
			else {
				return "";
			}
		}
		return null;
					
}

function buildUserID(httpRequest) {	
		 if (httpRequest.readyState == 4) {
            if (httpRequest.status == 200) {
					    //alert(httpRequest.responseXML);
		                var response = httpRequest.responseXML.documentElement;				
						// get data from xml
						var currentElement = response.getElementsByTagName("User")[0];	
						//user does not exist
						if (currentElement == null) {
							alert("No user for user name and pa10:39 PM 9/4/2007ssword");
							return;
						}
						// get user data
						userID = getXMLElement(currentElement,"UserID");
						userName = getXMLElement(currentElement,"UserName");
						//set the needed user cookies
						setCookie('userID', userID, 30, '/', '', '');						
						setCookie('userName', userName, 30, '/', '', '');	
						lastTermUsed = "";
						if (getCookie("lastsearchterm") != null) {
							lastTermUsed = "?searchterm="+getCookie("lastsearchterm");
						}
						window.location = "home.htm" + lastTermUsed;
            } else {
				alert("buildUserID");				
                alert('There was a problem with the request.');
            }
		//ntGetElementById("loadingImage").style.visibility ='hidden';							
        }

}

function incrementRating(httpRequest) {	
		 if (httpRequest.readyState == 4) {
            if (httpRequest.status == 200) {
			    //alert("Rating Incrememnted in server");
            } else {
				alert("incrementRating");
                alert('There was a problem with the request.');
            }
		//ntGetElementById("loadingImage").style.visibility ='hidden';							
        }

}

function buildMyEvents(httpRequest) {	
		 if (httpRequest.readyState == 4) {
            if (httpRequest.status == 200) {
				createMyEventsTab();
                var myEventResponse = httpRequest.responseXML.documentElement;	
				//user requested does not exist do not continue;
				if (myEventResponse==null) return;
				var numberOfEvents = myEventResponse.getElementsByTagName("Event").length;		
				//add relevant events to table
				for (var eventSeq = 0; eventSeq < numberOfEvents; eventSeq++)
				{		
						// get data from xml
						var currentElement = myEventResponse.getElementsByTagName("Event")[eventSeq];		
						eventName = getXMLElement(currentElement,"Name");
						eventID = getXMLElement(currentElement,"ID");					
						add2MyEvents(eventID,eventName);				
				}
            } else {
				alert("buildMyEvents");
                alert('There was a problem with the request.');
            }
		//ntGetElementById("loadingImage").style.visibility ='hidden';							
        }

}

function addUserEvent(httpRequest) {	
		if (httpRequest.readyState == 4) {
            if (httpRequest.status == 200) {	
				if (getCookie("userName") != null) {		
					var response = httpRequest.responseXML.documentElement;						
					if (response !=null ) 
					{
						createMyEventsTab();
						var numberOfEvents = response.getElementsByTagName("Event").length;								
						//add relevant events to table
						for (var eventSeq = 0; eventSeq < numberOfEvents; eventSeq++)
						{		
								// get data from xml
								var currentElement = response.getElementsByTagName("Event")[eventSeq];		
								eventName = getXMLElement(currentElement,"Name");
								eventID = getXMLElement(currentElement,"ID");					
								add2MyEvents(eventID,eventName);				
						}
					}
				}
	        } else {
					alert("addUserEvent");
	                alert('There was a problem with the request.');
	        }
        }
}

function removeUserEvent(httpRequest) {	
		 if (httpRequest.readyState == 4) {
            if (httpRequest.status == 200) {
				createMyEventsTab();
				if (getCookie("userName") != null) {		
					var response = httpRequest.responseXML.documentElement;	
					var numberOfEvents = response.getElementsByTagName("Event").length;		
					//add relevant events to table
					for (var eventSeq = 0; eventSeq < numberOfEvents; eventSeq++)
					{		
							// get data from xml
							var currentElement = response.getElementsByTagName("Event")[eventSeq];		
							eventName = getXMLElement(currentElement,"Name");
							eventID = getXMLElement(currentElement,"ID");					
							add2MyEvents(eventID,eventName);				
					}
				}				
            } else {
				alert("removeUserEvent");
                alert('There was a problem with the request.');
            }
		}
}

//only get here from adding an event
function showDivandAddEvents(eventID) {	
	// show the right pane and set the cookie
	showOnehideOther('myeventdiv','queuediv');
	setCookie('showingPane', 'myeventdiv', 30, '/', '', '');
	//only add if you are logged in
	if (getCookie("userName") != null) {
		makeRequest('http://liventer.com/admin/AddPersonalEvent.aspx?userid='+getCookie("userID")+'&EventId='+eventID,ADD_USER_EVENT_CALL);
		//add2MyEvents(eventID,eventName)
	}
}

function add2MyEvents(eventID,eventName) {
		
		pingButton = 'pingButton'+eventID;
		recordButton = 'recordButton'+eventID;
		deleteButton = 'deleteButton'+eventID;
		// name='+deleteButton+' onmouseover="roll_over(\''+deleteButton+'\', \'home_files/delete_over.gif\')" onmouseout="roll_over(\''+deleteButton+'\', \'home_files/delete.gif\')"	
		//need to add the remove event link
		var firstImage2add = 	'<img id='+pingButton+' onmouseover="roll_over(\''+pingButton+'\', \'home_files/ping_over.gif\')" onmouseout="roll_over(\''+pingButton+'\', \'home_files/ping.gif\')"	 src="home_files/ping.gif" alt="Track and Ping"> ';
		var secondImage2add =	'<img id='+recordButton+' onmouseover="roll_over(\''+recordButton+'\', \'home_files/record_over.gif\')" onmouseout="roll_over(\''+recordButton+'\', \'home_files/record.gif\')"	 src="home_files/record.gif" alt="Record event"> ';
		var thirdImage2add =	'<img onclick="javascript:removeEventCall('+eventID+')"' +
						' id='+deleteButton+' onmouseover="roll_over(\''+deleteButton+'\', \'home_files/delete_over.gif\')" onmouseout="roll_over(\''+deleteButton+'\', \'home_files/delete.gif\')"	 src="home_files/delete.gif" alt="Delete event">';
		var eventName2add = '<a href="javascript:doSearchwithTerm(\''+eventName+'\')">'+eventName+'</a>';						
		var tbody = ntGetElementById("myeventData");
	    var row = document.createElement("TR")
	    var td1 = document.createElement("TD")
		var td2 = document.createElement("TD")
		var td3 = document.createElement("TD")
		var td4 = document.createElement("TD")
	    td1.innerHTML = firstImage2add;
		td2.innerHTML = secondImage2add;
		td3.innerHTML = thirdImage2add;
		td4.innerHTML = eventName2add;
	    row.appendChild(td1);	    
		row.appendChild(td2);	  
		row.appendChild(td3);
		row.appendChild(td4);
	    tbody.appendChild(row);
		
	}

//make the remove call to the server	
function removeEventCall(eventID) {
	makeRequest('http://liventer.com/admin/RemovePersonalEvent.aspx?userid='+getCookie("userID")+'&EventId='+eventID,REMOVE_USER_EVENT_CALL);	
}
// to be used only for gui purposes	
function createMyEventsTab() {
		//make call for the users events if the user is logged in otherwise display the log in message
		if (getCookie("userName") != null) {	
				ntGetElementById("myeventdiv").innerHTML = 	'<br><table cellpadding="2" cellspacing="1">' +
															'<tbody id=myeventData >' +															
															'</tbody></table>';
		} 
		else {				
				ntGetElementById("myeventdiv").innerHTML = 	'<br><table cellpadding="5" cellspacing="0">' +
															'<tbody id=myeventData >' +
															'<tr>' +
															'<td id="" valign="top"><b><center>' +
															'<a href="login.htm">Login</a> for your events</center></b></td>' +
															'</tr>' +
															'</tbody></table>';
		}
}

function buildCategorySchedule(httpRequest) {	
		 if (httpRequest.readyState == 4) {
            if (httpRequest.status == 200) {
			    //alert(httpRequest.responseXML);
                var response = httpRequest.responseXML.documentElement;
				//alert(response);
				var numberOfCategories = response.getElementsByTagName("Category").length;	
				var beforeResult = '<table cellpadding="5" cellspacing="0" <tbody>' +
									'<tr>' +
										'<td valign="top" id="cominguptop">' +
											'Coming up in the next <select onChange="javascript:getCategoryschedule()" id="queueselect">' +									
																	'<option value="3">3</option>' +
																	'<option value="12">12</option>' +
																	'<option value="24">24</option> ' +
																'</select> ' +
											 'hours ...</td>' +		
									'</tr>';
				var oneResult = '';
				for (var categotySeq = 0; categotySeq < numberOfCategories; categotySeq++)
				{		
						// get data from xml
						var currentElement = response.getElementsByTagName("Category")[categotySeq];		
						categoryName = getXMLElement(currentElement,"CategoryName");
						categoryID = getXMLElement(currentElement,"CategoryID");
						numberOfEvents = getXMLElement(currentElement,"NumberOfEvents");
						
						oneResult += 	'<tr>' +
										'<td id="" valign="top">' +	
										'<a href="javascript:doSearchwithTerm(\'category:'+categoryName+'\')">'+numberOfEvents+' \''+categoryName+'\' events</a></td>' +
										'</tr>';
				}
				var afterResult = '</tbody></table>';																	
				ntGetElementById("queuediv").innerHTML = beforeResult + oneResult + afterResult;
				ntGetElementById("queueselect").options[getCookie("selectedTimeFrame")].selected = true;
            } else {
				alert("buildCategorySchedule");
                alert('There was a problem with the request.');
            }
		//ntGetElementById("loadingImage").style.visibility ='hidden';							
        }

}

function getCategoryschedule() 
{
	//get the selected value
	numberOfHoursToQuery = ntGetElementById("queueselect").value;
	setCookie('selectedTimeFrame', ntGetElementById("queueselect").selectedIndex, 30, '/', '', '');
	makeRequest('http://liventer.com/proto/home_files/categoryschedule.xml',CATEGORY_SCHEDULE_CALL);
}

//usage example setCookie('mycookie', eventName, 30, '/', '', '');
function setCookie( name, value, expires, path, domain, secure ) 
{
	// set time, it's in milliseconds
	var today = new Date();
	today.setTime( today.getTime() );

	/*
	if the expires variable is set, make the correct 
	expires time, the current script below will set 
	it for x number of days, to make it for hours, 
	delete * 24, for minutes, delete * 60 * 24
	*/
	if ( expires )
	{
	expires = expires * 1000 * 60 * 60 * 24;
	}
	var expires_date = new Date( today.getTime() + (expires) );

	document.cookie = name + "=" +escape( value ) +
	( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) + 
	( ( path ) ? ";path=" + path : "" ) + 
	( ( domain ) ? ";domain=" + domain : "" ) +
	( ( secure ) ? ";secure" : "" );
	
}

// this function gets the cookie, if it exists
function getCookie( name ) {
	
	var start = document.cookie.indexOf( name + "=" );
	var len = start + name.length + 1;
	if ( ( !start ) &&
	( name != document.cookie.substring( 0, name.length ) ) )
	{
	return null;
	}
	if ( start == -1 ) return null;
	var end = document.cookie.indexOf( ";", len );
	if ( end == -1 ) end = document.cookie.length;
	return unescape( document.cookie.substring( len, end ) );
}

// this deletes the cookie when called
function deleteCookie( name, path, domain ) {
	if ( getCookie( name ) ) document.cookie = name + "=" +
	( ( path ) ? ";path=" + path : "") +
	( ( domain ) ? ";domain=" + domain : "" ) +
	";expires=Thu, 01-Jan-1970 00:00:01 GMT";
}
	
function ntGetElementById(element)
{
	if (document.getElementById) element = document.getElementById(element);
		else if (document.all) element = document.all[element];
			else element = null;
	return element;
}

function logout() {
	deleteCookie('userID','/','');						
	deleteCookie('userName','/','');	
	window.location = "home.htm";
}


//left, top, width, height represent needed positions for the window
//shouldHide is set to true if we want to hide this and false otherwise

function positionFloatingElement(left, top, width, height, shouldHide) {
	//hide
	if (shouldHide) {
		ntGetElementById("Floating").style.visibility="hidden";
	}
	//move
	ntGetElementById("Floating").style.left=left + "px";
	ntGetElementById("Floating").style.top=top + "px";
	ntGetElementById("Floating").style.width=width + "px";
	ntGetElementById("Floating").style.height=height + "px";
	//unhide
	if (!shouldHide) {
		ntGetElementById("Floating").style.visibility="visible";
	}
}

//left, top, width, height represent needed positions for the window
//shouldHide is set to true if we want to hide this and false otherwise

function positionEmailForm(left, top, width, height, shouldHide) {
	//hide
	if (shouldHide) {
		ntGetElementById("emailForm").style.visibility="hidden";
	}
	//move
	ntGetElementById("emailForm").style.left=left + "px";
	ntGetElementById("emailForm").style.top=top + "px";
	ntGetElementById("emailForm").style.width=width + "px";
	ntGetElementById("emailForm").style.height=height + "px";
	//unhide
	if (!shouldHide) {
		ntGetElementById("emailForm").style.visibility="visible";
	}
}

function getPosition(e,ID,isChannel) {
    e = e || window.event;
    var cursor = {x:0, y:0};
    if (e.pageX || e.pageY) {
        cursor.x = e.pageX;
        cursor.y = e.pageY;
    } 
    else {
        var de = document.documentElement;
        var b = document.body;
        cursor.x = e.clientX + 
            (de.scrollLeft || b.scrollLeft) - (de.clientLeft || 0);
        cursor.y = e.clientY + 
            (de.scrollTop || b.scrollTop) - (de.clientTop || 0);
    }

	if (!isChannel) {

    	ntGetElementById("emailForm").src="/emailform/sendEmail.jsp?eventID="+ID+"&cacheName="+getCookie("setCategory");
    }
    else {

    	ntGetElementById("emailForm").src="/emailform/sendEmail.jsp?channelID="+ID+"&cacheName="+getCookie("setCategory");
    }    
    positionEmailForm(cursor.x,cursor.y-100,451,285,false);
}

function getChannelPosition(e,channelID) {
    e = e || window.event;
    var cursor = {x:0, y:0};
    if (e.pageX || e.pageY) {
        cursor.x = e.pageX;
        cursor.y = e.pageY;
    } 
    else {
        var de = document.documentElement;
        var b = document.body;
        cursor.x = e.clientX + 
            (de.scrollLeft || b.scrollLeft) - (de.clientLeft || 0);
        cursor.y = e.clientY + 
            (de.scrollTop || b.scrollTop) - (de.clientTop || 0);
    }

    ntGetElementById("emailForm").src="/emailform/sendEmail.jsp?channelID="+channelID;
    positionEmailForm(cursor.x,cursor.y-100,451,285,false);
}

//rollover effect for images

function roll_over(img_name, img_src){
   ntGetElementById(img_name).src = img_src;
   }

function changeElementColor(element, color) {	

	alert(ntGetElementById(element).style.width);
	ntGetElementById(element).style.color = "black";
}

//used for display purposes

function doNothing() 
{}




/*
	Date Format 1.1
	(c) 2007 Steven Levithan <stevenlevithan.com>
	MIT license
	With code by Scott Trenda (Z and o flags, and enhanced brevity)
*/

/*** dateFormat
	Accepts a date, a mask, or a date and a mask.
	Returns a formatted version of the given date.
	The date defaults to the current date/time.
	The mask defaults ``"ddd mmm d yyyy HH:MM:ss"``.
*/
var dateFormat = function () {
	var	token        = /d{1,4}|m{1,4}|yy(?:yy)?|([HhMsTt])\1?|[LloZ]|"[^"]*"|'[^']*'/g,
		timezone     = /\b(?:[PMCEA][SDP]T|(?:Pacific|Mountain|Central|Eastern|Atlantic) (?:Standard|Daylight|Prevailing) Time|(?:GMT|UTC)(?:[-+]\d{4})?)\b/g,
		timezoneClip = /[^-+\dA-Z]/g,
		pad = function (value, length) {
			value = String(value);
			length = parseInt(length) || 2;
			while (value.length < length)
				value = "0" + value;
			return value;
		};

	// Regexes and supporting functions are cached through closure
	return function (date, mask) {
		// Treat the first argument as a mask if it doesn't contain any numbers
		if (
			arguments.length == 1 &&
			(typeof date == "string" || date instanceof String) &&
			!/\d/.test(date)
		) {
			mask = date;
			date = undefined;
		}

		date = date ? new Date(date) : new Date();
		if (isNaN(date))
			throw "invalid date";

		var dF = dateFormat;
		mask   = String(dF.masks[mask] || mask || dF.masks["default"]);

		var	d = date.getDate(),
			D = date.getDay(),
			m = date.getMonth(),
			y = date.getFullYear(),
			H = date.getHours(),
			M = date.getMinutes(),
			s = date.getSeconds(),
			L = date.getMilliseconds(),
			o = date.getTimezoneOffset(),
			flags = {
				d:    d,
				dd:   pad(d),
				ddd:  dF.i18n.dayNames[D],
				dddd: dF.i18n.dayNames[D + 7],
				m:    m + 1,
				mm:   pad(m + 1),
				mmm:  dF.i18n.monthNames[m],
				mmmm: dF.i18n.monthNames[m + 12],
				yy:   String(y).slice(2),
				yyyy: y,
				h:    H % 12 || 12,
				hh:   pad(H % 12 || 12),
				H:    H,
				HH:   pad(H),
				M:    M,
				MM:   pad(M),
				s:    s,
				ss:   pad(s),
				l:    pad(L, 3),
				L:    pad(L > 99 ? Math.round(L / 10) : L),
				t:    H < 12 ? "a"  : "p",
				tt:   H < 12 ? "am" : "pm",
				T:    H < 12 ? "A"  : "P",
				TT:   H < 12 ? "AM" : "PM",
				Z:    (String(date).match(timezone) || [""]).pop().replace(timezoneClip, ""),
				o:    (o > 0 ? "-" : "+") + pad(Math.floor(Math.abs(o) / 60) * 100 + Math.abs(o) % 60, 4)
			};

		return mask.replace(token, function ($0) {
			return ($0 in flags) ? flags[$0] : $0.slice(1, $0.length - 1);
		});
	};
}();

// Some common format strings
dateFormat.masks = {
	"default":       "ddd mmm d yyyy HH:MM:ss",
	shortDate:       "m/d/yy",
	mediumDate:      "mmm d, yyyy",
	longDate:        "mmmm d, yyyy",
	fullDate:        "dddd, mmmm d, yyyy",
	shortTime:       "h:MM TT",
	mediumTime:      "h:MM:ss TT",
	longTime:        "h:MM:ss TT Z",
	isoDate:         "yyyy-mm-dd",
	isoTime:         "HH:MM:ss",
	isoDateTime:     "yyyy-mm-dd'T'HH:MM:ss",
	isoFullDateTime: "yyyy-mm-dd'T'HH:MM:ss.lo"
};

// Internationalization strings
dateFormat.i18n = {
	dayNames: [
		"Sun", "Mon", "Tue", "Wed", "Thr", "Fri", "Sat",
		"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"
	],
	monthNames: [
		"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
		"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"
	]
};

// For convenience...
Date.prototype.format = function (mask) {
	return dateFormat(this, mask);
}
